Python
Python
Introduction
● Name
● # of years in 77
● Project / Department
● Programming Experience
Topics
● Interactive Mode
● Script Mode
Demo
Hello World: Interactive Edition
Demo
Hello World: Script Edition
Identifiers
Identifiers
global if import in is
1. H3llo 6. $test
2. 1world 7. del
3. w0rld 8. and_or
4. _1Hi 9. for
5. __hello_world_1_ 10. My_@var
Basic Syntax
Basic Syntax: Comments
# This is a comment
● “Hello World”
● ‘This is a string’
● ‘1234567890’
● “”
Basic Syntax: Assignment
● None ● String
● Boolean ● List
● Numbers ● Tuple
○ Integer ● Set
○ Float ● Dictionary
○ Complex
Common Data Types: None
● Integers
○ 1, -3, 0, 10000000
● Floats
○ 1.3, -3.5, 0.0, 3.14
● Complex*
○ 3j, 0.5j, 1 + 2j
Common Data Types: Strings
● Text values
● Examples:
○ “Hello world!”
○ “Everything inside these quotes are strings! Like 1, 2,
3, and true or false!”
Common Data Types: Lists
● Arithmetic
● Comparison
● Assignment
● Logical
● Membership
● Identity
● Bitwise*
Operators: Arithmetic
● Addition (+)
● Subtraction (-)
● Multiplication (*)
● Division (/)
● Modulus (%)
● Exponent (**)
● Floor Division (//)
Operators: Comparison
● Equals ( == )
● Not Equal ( != )
● Greater than ( > )
● Less than ( < )
● Greater than equal ( >= )
● Less than equal ( <= )
Operators: Assignment
● Assignment ( = )
● Add assign ( += )
● Subtract assign ( -= )
● Multiply assign ( *= )
● Divide assign ( /= )
● Modulus assign ( %= )
● Exponent assign ( **= )
● Floor Division assign ( //= )
Operators: Logical
● and
● or
● not
Operators: Membership
● in
● not in
Operators: Identity
● is
● is not
String Operations and Methods
String Operations and Methods
+ Concatenate strings
string[i:j:k] Generate string containing every kth letter in substring from i to j (0-based
index)
String Operations and Methods
string.split(x) Divides the string into a list of strings using the separator x
x not in string Returns True if x is NOT found in the string, False otherwise
String Formatting
f”Henlo, I am {name}”
List Operations and Methods
List Operations and Methods
my_list1 + my_list2 Combine items in my_list1 and my_list2 into a new list
list(my_set) or list(my_tuple) Creates a list out of the items from a set or tuple
x not in my_list Returns True if x is NOT found in the list, False otherwise
Set Operations and Methods
Set Operations and Methods
set(my_list) or set(my_tuple) Creates a set out of the items from a list or tuple
Dictionary Operations and
Methods
Dictionary Operations and Methods
{k1: v1, k2: v2, …, Initialize new dictionary with keys k1, k2, … , kn, with matching values v1,
kn: vn} v2, …, vn
if <condition>:
<statements to run>
elif <another condition>:
<other statement>
else: # if all conditions are false
<default statement>
Conditional Statements: If Syntax Example
x = 10
if x < 10:
print(“x is less than 10”) # won’t run
elif x > 10:
print(“x is greater than 10”) # won’t run
else: # if all conditions are false
print(“x is equal to 10”) # this will run
Conditional Statements: If Syntax Exercise
x = ?
if x % 3 == 0:
print(“foo”)
if x % 5 == 0:
print(“bar”)
Conditional Statements
True False
1 0
-1 None
[1, 2, 3] []
{‘a’ : 1} {}
“hello” “”
Iterative Statements
Iterative Statements
while <condition>:
<statements to run repeatedly>
Iterative Statements: While Syntax Example
x = 0 OUTPUT:
while x < 5: 0
print(x) 1
x += 1 2
3
4
Iterative Statements: While Syntax Exercise
while my_list:
element = my_list[0]
print(element)
del my_list[0]
Iterative Statements: For Syntax
for i in my_list: 1
print(i) 3
meow
7
Iterative Statements: Iterables
● String
● List
● Tuple
● Set
● Dictionary
● Range function
● Enumerate function
Iterative Statements: For Syntax Exercise
*
**
***
****
*****
Iterative Statements: Break and Continue
Examples:
● print
● input
● len
● max
● min
Functions: Syntax
def print_stars(count=3):
print(“*” * count)
print(dividend / divisor)
Exceptions: Scenario
print(dividend / divisor)
Exceptions: Try-Catch Syntax
try:
<Statements that might throw exceptions>
except <optional exception type>:
<Statements to handle exception>
else:
<Statements to execute if no exception happened>
Exceptions: Try-Catch Example
try:
dividend = float(input(“Enter Dividend: “))
divisor = float(input(“Enter Divisor: “))
print(dividend / divisor)
except ValueError: # exception when input string is not a number
print(“Invalid input number”)
except ZeroDivisionError: # exception when divisor is zero
print(“Divisor cannot be zero”)
else:
print(“No exception detected”)
Exceptions: Raising Exceptions
You can raise your own exceptions to signal errors. e.g. in your function
Use the raise keyword:
def param_cannot_be_10(param):
if param == 10:
raise Exception(“Parameter cannot be 10”)
print(“Parameter is ” + str(param))
try:
param_cannot_be_10(10)
except Exception as e:
print("In except clause: " + str(e))
Submission of homework
Email to rjosapasap@gmail.com