Python basics
Following is a summary of basic Python concepts covered in this class.
Variables
A variable references a value:
x = 5This means x references the integer 5, or x → 5.
Likewise:
name = 'Emma'means the variable name references the string 'Emma'. name → 'Emma'.
Types
The following are basic types in Python:
- string— e.g.- 'hello', can use single or double quotes
- integer— e.g.- 5— convert a string to an integer with- int()
- float— e.g.- 5.2— convert a string to a float with- float()
- boolean— must be- Trueor- False
Operators
Operators compute new values from a type.
Arithmetic operators
Arithmetic operators take two numbers and produce a result.
| Operator | Example | Result | 
|---|---|---|
| + | 7 + 2 | 9 | 
| - | 7 - 2 | 5 | 
| * | 7 * 2 | 14 | 
| / | 7 / 2 | 3.5 | 
| ** | 7 ** 2 | 49 | 
| // | 7 // 2 | 3 | 
| % | 7 % 2 | 1 | 
Comparison operators
Comparison operators take two numbers and produce a boolean result.
| Operator | Example | Result | 
|---|---|---|
| > | 2 > 1 | True | 
| < | 2 < 1 | False | 
| >= | 2 >=2 | True | 
| <= | 2 <= 2 | True | 
| == | 4 == 4 | True | 
| != | 4 != 6 | True | 
String operators
Some operators can also apply to strings.
| Operator | Example | Result | 
|---|---|---|
| + | “good” + “bye” | “goodbye” | 
| * | “ha” * 3 | “hahaha” | 
| > | “hello” > “goodbye” | True (alphabetically greater) | 
| < | “hello” < “until tomorrow” | True (alphabetically lesser) | 
If statements
An if runs a block of code once if the condition is true. For example:
if age < 35:
  print("Sorry, you can't run for President.")You can add else to handle the other case:
if age < 35:
  print("Sorry, you can't run for President.")
else:
  print("Good luck in your candidancy.")You can use elif to check multiple conditions:
if age < 25:
  print("These are the best years of your life.")
elif age > 65:
  print("These are the golden years of your life.")
else:
  print("Well, just muddle through, I guess.")You can use multiple conditions and combine them with or and and:
if age < 5 or height < 3:
  print("Sorry, you are not able to ride this roller coaster.")
if not qualified and money > 1000000:
  print("You're not qualified for this opportunity, but if you make a big enough donation we'll consider you anyway.")While loops
A while loop runs a block of code as long as the condition is true. Some
examples:
while bit.front_clear():
  bit.move()x = 5
while x > 0:
  print('hello')
  x = x - 1while True:
  age = int(input("What is your age?"))
  if age >= 18 and age <= 120:
    break
  print("That is not a valid age.")Functions
Functions let you organize your code into smaller pieces. For example, here is a function that tells you if you have guessed the right number:
def check_guess(guess, answer):
    if guess == answer:
        print("Good job!")
        return True
    if guess > answer:
        print("Lower")
    else:
        print("Higher")
    return FalseA function has these parts:
- def— a keyword that means you are starting a function definition
- function name
- parameters — zero or more parameters, separated by a comma (these are also called arguments)
- colon
- indented block of code to run
- optional return statement, which returns one or more values — if no return
statement the function returns None
Input
You can get input from the terminal using the input() command:
name = input('Enter your name: ')If you need to convert to an integer, use int():
age = int(input('Enter your age: '))Likewise you can use float() to convert to a float.
Output
You can print with the print() statement:
print('Hello')Formatted strings are particularly useful for output that needs to use a variable:
value = 5
result = f'Your value is: {value}'
print(result)A formatted string starts with an f and then can use a variable name (and even
operators) inside of curly brackets.
value = 5
result = f'One more than your value is: {value + 1}'
print(result)Breaking from a loop
You can break out of a loop with break:
while True:
  age = int(input("Enter an age for an adult: "))
  if age >= 18:
    break
  print("Try again.")
print(f'The age you entered: {age}')If a while loop is inside of a function and you want to break out of the loop and return at the same time, you can just use return:
def get_age():
  while True:
    age = int(input("Enter an age for an adult: "))
    if age >= 18:
      return age
    print("Try again.")Putting this all together
Here is a complete program that is a guessing game for you and a friend to play:
def get_number():
    print("Enter a number between 1 and 100 for your friend to guess.")
    while True:
        number = int(input("Number: "))
        if number >= 1 and number <= 100:
            return number
        print("Try again.")
def print_blank_lines(number):
    while number > 0:
        print()
        number = number - 1
def get_guess():
    return int(input("What is your guess? "))
def check_guess(guess, answer):
    if guess == answer:
        print("Good job!")
        return True
    if guess > answer:
        print("Lower")
    else:
        print("Higher")
    return False
def main():
    answer = get_number()
    print_blank_lines(10)
    while True:
        guess = get_guess()
        found = check_guess(guess, answer)
        if found:
            break
if __name__ == '__main__':
    main()