100 Days of Code day 12 - more Python

My name is Rick and I am in search for gig as a developer :)

This past December I finished up a year long study with a full-stack school in NYC called Codeimmersives. We explored HTML, CSS, JavaScript, and how to build applications using the MERN stack. I learned about class-based components, passing props around (prop-drilling) and utilizing the component lifecycle(componentWillMount, componentDidMount, etc). After learning class based components, we moved on to functional based components using hooks, custom hooks, and different ways to manage state, such as the useContext and Redux APIs. (This is just a brief overview of the technologies I studied over the past year). Currently I am enrolled with a great bunch at devCodeCamp learning the basics of Python. I am documenting my journey by sharing these blog posts. Please help me out by dropping a comment below on what you think!

Dynamic language

As opposed to statically typed languages (C# Java), where data types are defined at

compile time

Data types

  • Text Type: str

Characters strung together


  • Numeric Types: int, float, complex

int - whole number

float - decimal

complex - Deals with imaginary and real numbers (not important for now)


  • Sequence Types: list, tuple, range

list - ordered collection

tupal - similar to list, less functionality and takes up less memory.

range - The range() function returns a sequence of numbers, starting from 0 by default,

and increments by 1 (by default), and stops before a specified number.

range(start, stop, step)

start Optional. An integer number specifying at which position to start. Default is 0

stop Required. An integer number specifying at which position to stop (not included).

step Optional. An integer number specifying the incrementation. Default is 1


  • Mapping Type: dict

key value pairs


  • Set Types: set, frozenset

sets is a collection which is unordered, unchangeable*, and unindexed. No duplicate

members.


  • Boolean Type: bool (true and false)

  • Binary Types: bytes, bytearray, memoryview

Snake Casing

my_boolean = true

Order of operations

please excuse my dear aunt sally (left to right)

  • Parentheses

  • Exponents

  • Multiply/Divide

  • Add/Subtract

  • Left to Right

Arithmetic Operators

Addition    x + y    
 Subtraction    x - y    
 Multiplication    x * y    
 Division    x / y    
 Modulus    x % y    
 Exponentiation    x ** y    
 Floor division    x // y

Assignment Operators

=    x = 5    x = 5    
+=    x += 3    x = x + 3    
-=    x -= 3    x = x - 3    
*=    x *= 3    x = x * 3    
/=    x /= 3    x = x / 3    
%=    x %= 3    x = x % 3    
//=    x //= 3    x = x // 3    
**=    x **= 3    x = x ** 3    
&=    x &= 3    x = x & 3    
|=    x |= 3    x = x | 3    
^=    x ^= 3    x = x ^ 3    
>>=    x >>= 3    x = x >> 3    
<<=    x <<= 3    x = x << 3

Comparison Operators

==    Equal    x == y    
!=    Not equal    x != y    
>    Greater than    x > y    
<    Less than    x < y    
>=    Greater than or equal to    x >= y    
<=    Less than or equal to    x <= y

Logical Operators

and     Returns True if both statements are true    x < 5 and  x < 10    
or    Returns True if one of the statements is true    x < 5 or x < 4    
not    Reverse the result, returns False if the result is true    not(x < 5 and x < 10)

Identity Operators

is     Returns True if both variables are the same object    x is y    
is not    Returns True if both variables are not the same object    x is not y

Membership Operators

in     Returns True if a sequence with the specified value is present in the object    x in y    
not in    Returns True if a sequence with the specified value is not present in the object    x not in y

Bitwise Operators

&     AND    Sets each bit to 1 if both bits are 1
|    OR    Sets each bit to 1 if one of two bits is 1
 ^    XOR    Sets each bit to 1 if only one of two bits is 1
~     NOT    Inverts all the bits
<<    Zero fill left shift    Shift left by pushing zeros in from the right and let the leftmost bits fall off
>>    Signed right shift    Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off

-

my_age = 29

print(f'I am {my_age} years old')

first_name= input('Please enter your first name:   ', )

last_name= input('Please enter your last name:   ', )

full_name = f'{first_name} {last_name}'

print(f'My first name is {first_name} and my last name is {last_name}, which means my full name is {full_name}')

temp_bool = input('Hey, wanna see what a temperature in Fahrenheit is converted to Celsuis? (y or n only please): ', )


if(temp_bool ==  'y'):
  temp_fahrenheit = input('What temperature Fahrenheit would you like to convert?: numbers only please:  ', )
  try:
    int(temp_fahrenheit)

  except:
    print('Please only provide an integer to be evaluated')
elif(temp_bool == 'n'):
  print('Awe shucks, perhaps next time :( ')
else:
  print('you entered the wrong input')

if(temp_fahrenheit):

  celsius = (int(temp_fahrenheit) - 32) * 5.0/9.0
  print(f'{temp_fahrenheit} degrees Fahrenheit is {celsius} degrees Celsius....thank you and come on back to visit us again.')

Conditionals exercise

import random

# Conditionals
# 1.    Driving Age
# a.    Declare a variable and assign it the value of the legal driving age in the United States.
driving_age = 16
# b.    Declare a variable to store a user's age. Use the built-in Python input() function to retrieve the user’s age via user input.
age = input('Please provide your age represented by numbers only:  ')
if(age):
  try:
      age = int(age)
  except:
      print('Please provide numbers only.')

# c.    If the user’s age is greater than or equal to the legal driving age in the United States, then print to the console “You are legally able to drive.”
if age >= driving_age:
  print('You are legally able to drive.')
# d.    If the user’s age is less than the legal driving age in the United
else:
  print('You are not old enough to drive yet.')


# 2.    Random Number 
# a.    Declare a variable to store a random number between 0 and 10. You will need to do some research to determine how to generate a random number in Python.
random_num = random.randint(0, 10)
print(random_num)
# i.    A good search term to use: “random number Python”
# b.    If the number is between 0 and 2, print to the console “0 or 1 or 2”
if random_num >= 0 & random_num <= 2:
  print('0 or 1 or 2')
# c.    If the number is between 3 and 5, print to the console “3 or 4 or 5”
elif random_num >= 3 & random_num <= 5:
  print('3 or 4 or 5')
# d.    If the number is between 6 and 8, print to the console “6 or 7 or 8”
elif random_num >= 6 & random_num <= 8:
  print('6 or 7 or 8')
# e.    If the number is equal to 9 or 10, print to the console “9 or 10”
elif random_num == 9 & random_num == 10:
  print('9 or 10')



# 3.    NFL Teams
# a.    Declare a variable to store an NFL team name. Use the built-in Python input() function to retrieve a user’s inputted favorite NFL team.
nfl_team = input('Please provide your favorite NFL team:  ', )
# b.    Build out a conditional for “Bears”, in which if selected it will print to the console “Quarterback much?”
if nfl_team.upper() == 'BEARS':
  print('Quarterback much?')
# c.    Build out a conditional for “Vikings”, in which if selected it will print to the console “Loud noises!”
elif nfl_team.upper() == 'VIKINGS':
  print('Loud noises!')
# d.    Build out a conditional for “Lions”, in which if selected it will print to the console “LOL! They bad!” 
elif nfl_team.upper() == 'LIONS':
  print('LOL! They bad!')
# e.    Build out a conditional for “Packers” in which if selected it will print to the console “Best team in the world! Actually, the universe!” 
elif nfl_team.upper() == 'PACKERS':
  print('Best team in the world! Actually, the universe!')
# f.    Build out a “default” conditional to print to the console “Pick a different team” in the scenario where a user doesn’t input “Bears”, “Vikings”, “Lions”, or “Packers”.
else:
  print('Pick a different team')

Loops Exercize

import getpass
# Python Loops Worksheet
# In Python, loops are an important tool that allow developers to execute a block of code over and over as long as a condition holds true. This worksheet will allow you to practice a for loop and while loop.
# For Loop
# A for loop is ideal in a situation where you know exactly how many times you want the loop to run or you want to iterate over a collection. 
# To iterate for a specified number of times, use the built-in Python range() function.

# For Loop Tasks
# 1.    Write a for loop that will run five times and print “hello!” to the console five times
for num in range(5):
  print('hello!')
# a.    Expected Output

# 2.    Write a for loop that counts from 0 to 10, with each number being print to the console one at a time
for num in range(11):
  print(num)
# a.    Expected Output

# 3.    Write a for loop that counts from 10 to 0, with each number being print to the console one at a time. HINT: When calling the range function provide three arguments 
# “range(start number, stop number, step number)”
for num in range(10,-1,-1):
  print(num)
# a.    Expected Output

# 4.    Write a for loop that will run as many times as a user wants, with each iteration printing “devCodeCamp” to the console. HINT: you will need to use the Python input() function to gather user input
num_of_loops = input('How many times do wou want to see "devCodeCamp" printed to the console?', )

try:
  num_of_loops = int(num_of_loops)
except:
  print('Provide only a whole number please.')
# a.    Expected Output if user chooses 4
if(num_of_loops):
  for i in range(num_of_loops):
    print('devCodeCamp')

# 5.    Write a for loop that will print each character of the string “Packers” to the console. 
for char in "Packers":
  print(char)
# a.    Expected Output

# 6.    CHALLENGE: Fizz Buzz
# a.    Write a program that prints every number from 0 to 100 to the console
for num in range(101):
  if(num % 3 == 0 & num % 5 == 0):
    print('fizzbuzz')
  elif(num % 3 == 0):
    print('fizz')
  elif(num % 5):
    print('buzz')

# b.    If a number is divisible by 3, print ‘fizz’ instead of the number
# c.    If a number is divisible by 5, print ‘buzz’ instead of the number
# d.    If a number is divisible by 3 and 5, print ‘fizzbuzz’ instead of the number
# While Loop
# A while loop is ideal in a situation where do you not know how many times you want the loop to run. Instead, the loop will continue to iterate as long as the condition remains to be true. Once the condition becomes false then the loop completes.

# HINT: if isInstructorAwesome is set equal to true, make sure to have a way to set isInstructorAwesome equal to false somewhere inside the while loop to prevent an infinite loop from occurring
# While Loop Tasks
# 1.    Write a while loop that will run five times and print “hello!” to the console five times
num = 0

while num < 5:
  print('hello!')
  num += 1
# a.    Expected Output



# 2.    Write a while loop that will prompt a user for their password and will continue to prompt the user until the typed in password is correct. If correct, print to the console “User Validated”

# a.    Expected Output

# ask user for name and password

password = input('Please provide a password: ', )

password_verify = ''

while password != password_verify:
  password_verify = input('Please verify the password entered: ')

print('User is validated!')



# # 2.    Write a while loop that will prompt a user for their password and will continue to prompt the user until the typed in password is correct. If correct, print to the console “User Validated”

# a.    Expected Output

# ask user for name and password
username = input('Please provide a username: ', )
password = input('Please provide a password: ', )

# setting database variable to object containing username and password (key value store)
database = {username: password}

# ask user for username again
username = input("Enter Your Username : ")
# ask user for password again (but it's hidden)
password = getpass.getpass("Enter Your Password : ")
# iterate through the database object keys even though there's only one/
for i in database.keys():

    # checking to see if username matches the key

    if username == i:

        # Checking to see if password matches the valuestore and will continue to ask for password if it's not correct.
        # Nesting loops is never ideal and should be avoided O(n^2)

        while password != database.get(i):
            password = getpass.getpass("Enter Your Password Again : ")
        break

print("User Validated")

Codewars

My solution

def high_and_low(numbers):

    # seperate numbers by space
  numbers = numbers.split(' ')
    # turn the into integers
  integer_map = map(int, numbers)
  integer_list = list(integer_map)
    # find highest and lowest numbers
  maximum = max(integer_list)
  minimum = min(integer_list)
  # convert both nums back to string with a space
  a = str(maximum)
  b = str(minimum)

    # return them
  return f'{a} {b}'

Best practice

def high_and_low(numbers): #z.
    nn = [int(s) for s in numbers.split(" ")]
    return "%i %i" % (max(nn),min(nn))

Old

'%s %s' % ('one', 'two')

New

'{} {}'.format('one', 'two')

Output

one two

Old

'%d %d' % (1, 2)

New

'{} {}'.format(1, 2)

Output

1 2