Learning Objectives:

1.1: Variables

1.1.1: Variable Assignment

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 reserved keywords (e.g. class, type, etc.)

# Example of variable creation
age = 21
Time = 0

Using a python keyword as a variable name

global = 1

global
## invalid syntax (<string>, line 1)
# More declarations for different variable types 

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

# storing a char
character_example = 'r'

# storing a float 
_newFloat = 1.0

# storing a boolean value
boolean = True

1.1.2 Types of Variables

type(age)
## <class 'int'>
type(first_name)
## <class 'str'>
type(boolean)
## <class 'bool'>

Let’s transform a float into an interger and vice versa

# We will transform the type and the store it in a new variable
age_float = float(age)
type(age_float)

# Transform from float to int
## <class 'float'>
age_int = int(age_float)
type(age_int)

# Transform between string and int. Convert age to string
## <class 'int'>
age_string = str(age)
type(age_string)

# Transform age_string back to an int
## <class 'str'>
type(int(age_string))
## <class 'int'>

1.2: Operators

# Basic mathematical operations with Numbers

# Addition
print(5+23)

# Subtraction
## 28
print(100-25)

# Multiplication
## 75
print(5*10)

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

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

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

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

# Modular Division: return the remainder of division
## 3
print(10%3)

# Operations with Strings and Characters
## 1
print("bar" * 5)
## barbarbarbarbar
print('xo'*3)
## xoxoxo
# ERROR: cannot concatenate an int to a string --> need to cast int to string
print("hello" + 5)

# Fix
## Error: TypeError: can only concatenate str (not "int") to str
print("hello " + str(5))

# String addition = concatenation
## hello 5
print("hello " + "world")
## hello world

1.1.2: Other Operators

# Comparators: return a boolean value

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

# Greater than >
## True
print(7 > 1)

# Less than <
## True
print(1.5 < 90)
## True
# Greater than or equal to >=
print(5.0 >= 5)
## True
print(5.0 >= 4)
## True
print(5 >= 13)

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

print("hello" < "world")
## True
print("hello" == "world")
## False
print("hello" > "world")
## False
print("hello" == "hello")
## True
print("cat" < "dog")
## True

1.3: Conditional Statements

1.3.1: If Conditions

  • 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 ().
x = 5
y = 20


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 or squared of x")
## y is NOT double or squared of x

Loops & Functions

2.1: Loops 2.1.1: For/While Loops Python has one implementation/structure of the FOR loop that works for both the regular for loop and the forEach loop from other programming languages.

There are a few structural differences for the Python FOR loop. Consider them in the examples below.

# The variable i serves as the counter over the RANGE of [0,10), inclusive of lower but exclusive of upper bound.

# The lower bound of 0 does NOT need to be specify; it is implemented by default unless another lower bound is specified.

# Also by default, i increments by 1. 

for i in range(10):
  print(i)
## 0
## 1
## 2
## 3
## 4
## 5
## 6
## 7
## 8
## 9

This examples specifies a lower bound that differs from the default value of 0.

The order of the parameter is ALWAYS: 1. Starting position, inclusive 2. Stopping position, exclusive 3. Incremental value

# In this example, x starts at the value of 2 and stops at 9 inclusively, or 10 exclusive, with x increments by 1 with each iteration.

for x in range(2, 10):
  print(x)
  
# The third parameter in range() defines the number of steps to increment the counter. In this example, x starts at the value of 0 and stops at 9 inclusively, or 10 exclusive, with x increments by 3 with each iteration.
## 2
## 3
## 4
## 5
## 6
## 7
## 8
## 9
for x in range(0, 10, 3):
  print(x)

# forEeach loop over the each character in a string. In this example, the variable 'i' represents every element/character of 'hello.'
## 0
## 3
## 6
## 9
for i in "hello!":
  print(i)
  
# We could also iterate over the string by index. Consider the following example that iterates over the string by index, starting at index 0 and ending at the last element, with the counter increments by 2, so ONLY printing every other element in the string. 
## h
## e
## l
## l
## o
## !
string = "hello world!"
for i in range(0, len(string), 2):
  print(str(i) + "th letter is "+ string[i])
  
  
# The structure of the WHILE loop remains mostly identical to other programming languages.
## 0th letter is h
## 2th letter is l
## 4th letter is o
## 6th letter is w
## 8th letter is r
## 10th letter is d
count = 0
while (count < 10):
  print(count)

  # IMPORTANT!!! Updating the counter!
  count += 1
## 0
## 1
## 2
## 3
## 4
## 5
## 6
## 7
## 8
## 9

2.1.2: Continue/Break Keywords

How to manipulate loops (FOR and WHILE):

  • Break: skip the remaining codes in the loop and the remaining iterations, break out of the innermost loop.
  • Continue: skip the remaining codes in the loop and continue to the next iteration of the loop
while True:
  user = input("Enter something to be repeated: ")

  ## When break is triggered, the print() below will NOT run
  ## The program will break out of the loop when this keyword is read. 
  if user=="end":
    print("Terminating the program... byebye")
    break
  print(user)

Let’s consider a loop that counts from 1-20, but skip all numbers that are mulitple of 5. In this case, we could NOT use the “end” keyword, because that will terminate the loop. We want to “continue” the loop except for a few numbers. We will implement this with both a while and a for loop.

count = 1

# WHILE loop implementation
while count + 1 <= 20:
  if count % 5 == 0:
    print("SKIP")
    count += 1
    continue
  print(count)
  count += 1
  
# FOR loop implementation
for i in range (1, 20):
  if i % 5 == 0:
    print("SKIP")
    continue
  print(i)

2.2: Functions

Functions are useful when you are given a problem that could be broken down into multiple steps and some steps are used repetitively. Then, having a function for those steps are convenient because it reduces code repetition and makes code more organized.

Notes about defining a new function:

Determine if the user input is a palindrome: a word/sentence is spelled the same way when it is reversed. e.g., Hannah.

In stead checking if a word is a palindrome, we will test if a sentence is a palindrome.

In order to write this program, we will set a few specifications: - Treat capitalized letters as lowercase - Ignore all white spaces and punctuations - An empty sentence/string IS consider to be a palindrome.

import string # import the string package

# This implementation of the function RETURN with boolean value, True/False
import string

def isPalindrome(str):
  exclude = set(string.punctuation)
  str = ''.join(ch for ch in str if ch not in exclude)
  str = str.replace(" ", "").lower() # Cleaning the input
  if str == str[::-1]:
    return str + " is a palindrome!"
  else:
    return str + " is NOT a palindrome!"

def main():
  userSentence = input("Enter a sentence to be tested as a palindrome: ")
  print(isPalindrome(userSentence))

if __name__ == "__main__":
    main()