Module 1: Variables, Operators, Conditions

Logistics:

  • Press Shift + Enter keys to run each block of code on Google Colab environment or copy and paste the codes/comments into a python file.
  • Conceptual introductions and explanations are provided in text blocks. Code-related explanations are included as comments above the codes.
  • Exercises/practice problems are labeled in each module. For coding exercises, you could download an external Python IDE (e.g. Anaconda) to program and test your implementation. One possible implementation of the exercise are provided under the problem.

Learning Objectives:

  1. Define and modify variables of various data types. Convert between data types.
  2. Understand the characteristics and uses of each operation and the corresponding output.
  3. Understand and correctly these statements for checking conditions.

1.1: Variables

1.1.1: Variable Assignment

Variables are the same as variables in math, except math variables are often letters, but programming variables could be words.

Variable: a container that holds some information.

Note about variable declaration:

  • Case-sensitive
  • MUST start with either a letter or underscore; CANNOT start with numbers.
  • CANNOT be the same name as Python keywords (e.g. class, finally, etc.)
  • do NOT specify type of information stored in the variable. (Refer to the following codes for an example.)
In [ ]:
# Examples of variable declarations
width = 10

# Notice the "H" is capitalized
Height = 5

area = 0
In [ ]:
width
Out[ ]:
10
In [ ]:
# Expect an ERROR because the "height" variable is case-sensitive.
# ERROR CODE: "height" is not defined. 

height
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-6-d56756f3e5e3> in <module>()
      2 # ERROR CODE: "height" is not defined.
      3 
----> 4 height

NameError: name 'height' is not defined
In [ ]:
Height
Out[ ]:
5
In [ ]:
# Using a python keyword as a variable name
# ERROR CODE: invalid syntax
 
global = 1

global
  File "<ipython-input-8-4909dc42d849>", line 4
    global = 1
           ^
SyntaxError: invalid syntax
In [ ]:
# More declarations for different variable types 

# storing a string
helloMessage = "Hello World!"
first_name = "John"

# storing a char
character_example = 'a'

# storing a float 
_newFloat = 1.0

# storing a boolean value
bool_Condition = True
In [ ]:
helloMessage
Out[ ]:
'Hello World!'
In [ ]:
character_example
Out[ ]:
'a'
In [ ]:
_newFloat
Out[ ]:
1.0
In [ ]:
bool_Condition
Out[ ]:
True

1.1.2: Type Casting

From Topic 1.1.1, we learned how to properly declare a variable name for different date types. In this topic, we will explore how to "cast" or convert data type between one another.

Helpful function: type() defines the type of the data

In [ ]:
# From declaration above, width = 10 and 10 is an int, so we expects the function to return int
type(width)
Out[ ]:
int
In [ ]:
type(helloMessage)
Out[ ]:
str
In [ ]:
type(bool_Condition)
Out[ ]:
bool
In [ ]:
# Let's cast a float into an int and vice verse
# We will cast the type and the store it in a new variable
width_float = float(width)

type(width_float)
Out[ ]:
float
In [ ]:
# Cast from float to int
width_int = int(width_float)

type(width_int)
Out[ ]:
int
In [ ]:
# Cast between string and int
# Recall that width stores an int

# convert width to string
width_string = str(width)
type(width_string)
Out[ ]:
str
In [ ]:
# convert width_string back to an int
type(int(width_string))
Out[ ]:
int

1.2: Operators

1.1.1 Mathematical Operators

In [ ]:
# Basic mathematical operations with Numbers

# Addition
print(5+23)

# Subtraction
print(100-25)

# Multiplication
print(5*10)

# Power/Exponent
# ** operator is equivalent to exponent
print(5**2)

# 5*5 = 5^2 = 5**2 
print(5*5)


# Division (float)
# Return the actual decimal value of division
print(36/4)
print(10/3)         

# Division (int)
# Return an int. If the actual quotient is a decimal value, only whole number is returned 
print(10//3)
print(19//6)

# Modular Division: return the remainder of division
print(10%3)
28
75
50
25
25
9.0
3.3333333333333335
3
3
1
In [ ]:
# Operations with Strings and Characters
print("foo" * 5)
print('x'*3)
foofoofoofoofoo
xxx
In [ ]:
# ERROR: compiler treats x as a variable, not a character
print(x*3)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-23-47a2cb16f654> in <module>()
      1 # ERROR: compiler treats x as a variable, not a character
----> 2 print(x*3)

NameError: name 'x' is not defined
In [ ]:
# ERROR: cannot concatenate an int to a string --> need to cast int to string
print("hello" + 5)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-8beae78f288a> in <module>()
      1 # ERROR: cannot concatenate an int to a string --> need to cast int to string
----> 2 print("hello" + 5)

TypeError: must be str, not int
In [ ]:
# Fix
print("hello " + str(5))
hello 5
In [ ]:
# String addition = concatenation
print("hello " + "world")
hello world

1.1.2: Other Operators

In [ ]:
# Comparators: return boolean value

# Equality ==
# Note: MUST be Double equal signs, single equal sign is assignment
print(5 == 5.0)

# Greater than >
print(7 > 1)

# Less than <
print(1.5 < 90)

# Greater than or equal to >=
print(5.0 >= 5)
print(5.0 >= 4)
print(5 >= 13)

# Less than or equal to <=
print(10 <= 10.0)
print(10 <= 20)
print(8 <= 3)
True
True
True
True
True
False
True
True
False
In [ ]:
# Comparators on Strings

print("hello" < "world")
print("hello" == "world")
print("hello" > "world")

print("hello" == "hello")

print("cat" < "dog")
True
False
False
True
True

1.3: Conditional Statements

1.3.1: If Conditions

Important Notices:

  • Order of the conditions matter!
    • If more than one conditions are satified, then the actions associated with the first satifying condition will execute and skip the remaining conditions and codes.
  • "elif" = "else if"
    • "elif" denotes the same meaning as "else if"
  • At least one condition MUST be provided for both if and elif clauses, else ERROR!
  • Parentheses for if and elif is optional. Your code will work with or without the ().
In [ ]:
x = 7
y = 14


if (2*x == y):
  print("y is double of x")
elif (x**2 == y):
  print("y is the squared of x")
else:
  print("y is NOT double of x")
y is double of x
In [ ]:
x = 7
y = 49


if (2*x == y):
  print("y is double of x")
elif (x**2 == y):
  print("y is the squared of x")
else:
  print("y is NOT related to x")
y is the squared of x
In [ ]:
x = 7
y = 50


if (2*x == y):
  print("y is double of x")
elif (x**2 == y):
  print("y is the squared of x")
else:
  print("y is NOT double nor squared of x")
y is NOT double nor squared of x

1.3.2: Switch Cases

Python does NOT have an implementation for the switch cases, but one way to implement the switch case is with the dictionary, a data structure that stores the key-value pair (Module 3).

  • The switch conditions are stored as keys in the dictionary, and actions stored as the value.
    • If there is a series of actions for each case, then consider writing a function for each case and use the function calls as the value.
  • The default condition is manually listed as a key-value in the get().
In [ ]:
def switcher(number):

  # dictionary (from Module 3) to store switch cases
  # If not found, then get() the default value
  return {
    '0':"Entered 0",
    '1':"Entered 1",
    '2':"Entered 2",
    '3':"Entered 3",
    '4':"Entered 4",
    '5':"Entered 5",
    '6':"Entered 6",
    '7':"Entered 7",
    '8':"Entered 8",
    '9':"Entered 9",
  }.get(number,"Invalid number!")


# input() reads in an user input from stdin
number = input("Dial a number")
switcher(number)
Dial a number9
Out[ ]:
'Entered 9'
In [ ]:
"""
EXERCISE: implement the above switch case example using if/else conditions

Prompt: For each digit between 0-9, the program will print a confirmation 
for the entered value or print "invalid inputs" for all other numbers.
"""
Out[ ]:
'\nEXERCISE: implement the above switch case example using if/else conditions\n\nPrompt: For each digit between 0-9, the program will print a confirmation \nfor the entered value or print "invalid inputs" for all other numbers.\n'

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

In [ ]:
number = input("Dial a number")

if number == '0':
    print("Entered 0")
elif number == '1':
    print("Entered 1")
elif number == '2':
    print("Entered 2")
elif number == '3':
    print("Entered 3")
elif number == '4':
    print("Entered 4")
elif number == '5':
    print("Entered 5")
elif number == '6':
    print("Entered 6")
elif number == '7':
    print("Entered 7")
elif number == '8':
    print("Entered 8")
elif number == '9':
    print("Entered 9")
else:
    print("Invalid number!")
Dial a number9
Entered 9
In [ ]: