Introduction to Python
Introduction
● Name
● # of years in 77
● Project / Department
● Programming Experience
Topics
● What is Python? ● Set Operators and Methods
● Identifiers ● Dictionary Operators and
● Basic Syntax Methods
● Common Data Types ● Conditional Statements
● Operators ● Iterative Statements
● String Operators and Methods ● Functions
● List Operators and Methods ● Exceptions
What is Python?
● Python is a programming language
● Python is interpreted
● Python is beginner friendly
What is Python?
Major Python versions:
● Python 2.7 - Released July 2010
● Python 3.7 - Released June 2018 (We will use this)
Python 2.xx and 3.xx are INCOMPATIBLE
Check your Python version
Python Programming Modes
● Interactive Mode
● Script Mode
Demo
Hello World: Interactive Edition
Demo
Hello World: Script Edition
Identifiers
Identifiers
● Used to identify ‘something’ in a python program
○ variables
○ functions
○ modules
○ classes*
Identifiers: Rules
● Starts with a letter or an underscore
● Followed by zero or more: letters, underscores and numbers
● Word should not be reserved
Identifiers: Reserved Words
and as assert break class
continue def del elif else
except exec finally for from
global if import in is
lambda not or pass raise
return try while with yield
True False None async await
Identifiers: Exercise
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
Comments are ignored by the interpreter
# This is a comment
print(“Hi!”) # Comment after statements
Basic Syntax: Defining Strings
A string is a sequence of characters
Use either single quotes or double quotes to declare a string
● “Hello World”
● ‘This is a string’
● ‘1234567890’
● “”
Basic Syntax: Assignment
Use “=” to assign a value to a variable
● my_string = “Hello World”
● my_number = 1234
● name = “James”
● my_var = my_number
● x = y = z = “multiple assignments”
● one, two, three = 1, 2, 3
Basic Syntax: Waiting for user input
Use input() to accept user input
name = input(“Please enter your name: “)
print(name)
Common Data Types
Common Data Types
● None ● String
● Boolean ● List
● Numbers ● Tuple
○ Integer ● Set
○ Float ● Dictionary
○ Complex
Common Data Types: None
● Signifies an “Empty” variable
● Only one possible value: None
Common Data Types: Boolean
● Two possible values: True, False
Common Data Types: Number
● 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
● An ordered collection of items
● Mutable - can add, remove, or edit items
● Does not require elements to be of the same type
● Examples:
○ [“red”, “orange”, “yellow”, “green”]
○ [“mix”, 10, 2.5]
○ [[“a”, “b”, “c”], [1, 2, 3]]
Common Data Types: Sets
● An unordered collection of unique items
● Mutable - can add and remove items
● Does not require elements to be of the same type
● Examples:
○ {2, 4, 6, 8, 10}
○ {“nuggets”, “fries”, “burger”}
Common Data Types: Dictionaries
● An unordered collection of key-value pairs
● Mutable - can add, remove, or edit items
● Does not require keys and/or values to be of the same type
● Examples:
○ {“cat”: “kitten”, “dog”: “puppy”, “owl”: “owlet”}
○ {2018: “Catriona”, 2017: ”Demi-Leigh”, 2016: “Iris”,
2015: “Pia”, 1969: “Gloria”}
Operators
Operators: Types
● 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
len(string) Get length of the string (number of characters)
+ Concatenate strings
* Generate repeated strings
string[i] Get ith character (0-based index)
string[-i] Get ith to the last character
string[i:j] Get substring from position i (inclusive) to j (exclusive) (0-based index)
string[i:j:k] Generate string containing every kth letter in substring from i to j (0-based
index)
String Operations and Methods
string.strip() Generates new string without leading and trailing whitespace
string.lower() Generate new string with all characters converted to lowercase
string.upper() Generate new string with all characters converted to uppercase
string.replace(x, y) Generate new string by replacing all occurrences of x with y
string.split(x) Divides the string into a list of strings using the separator x
x in string Returns True if x is found in the string, False otherwise
x not in string Returns True if x is NOT found in the string, False otherwise
String Formatting
“Hi, I am {}. I am {} years old.”.format(“James”, 20)
“Hi, I am {name}. I am {age} years old. My dad’s name is also
{name}.”.format(age=20, name=“James”)
“Total cost is {cost:.2f}. It rounds to
{cost:.0f}.”.format(cost=99.0123)
f”Henlo, I am {name}”
List Operations and Methods
List Operations and Methods
list() or [] Initialize new empty list
[x, y, z] Initialize new list with values x, y, and z
my_list[i] Get/assign ith item of the list (0-based index)
my_list[-i] Get/assign ith to the last item of the list
my_list[i:j] Get/assign sublist from item i (inclusive) to j (exclusive) (0-based index)
my_list[i:j:k] Get/assign every kth item in sublist from i to j (0-based index)
List Operations and Methods
len(my_list) Get number of items in the list
my_list.append(x) Append x to the end of the list
my_list.insert(i, x) Insert x to the ith position of the list (0-based index)
del my_list[i] Delete ith item (0-based index)
my_list1 + my_list2 Combine items in my_list1 and my_list2 into a new list
my_list.sort() Sorts the items in the list
List Operations and Methods
max(my_list) Get max item in the list
min(my_list) Get min item in the list
list(my_list) or my_list[:] Creates a shallow copy of the list
list(my_set) or list(my_tuple) Creates a list out of the items from a set or tuple
x in my_list Returns True if x is found in the list, False otherwise
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() Initialize new empty set
{x, y, z} Initialize new set with values x, y, and z
my_set.add(x) Adds x to the set
my_set.remove(x) Removes x from the set (raises KeyError if not present)
my_set.discard(x) Removes x from the set if present
len(my_set) Get number of items in the set
Set Operations and Methods
x in my_set Returns True if x is found in the set, False otherwise
x not in my_set Returns True if x is NOT found in the set, False otherwise
my_set1.issubset(my_set2) Returns True if every element of my_set1 is found in my_set2,
False otherwise
my_set1.union(my_set2) Combine items in my_set1 and my_set2 into a new set
my_set1.intersection(my_set2) Create new set with items that are common in my_set1 and
my_set2
my_set1.difference(my_set2) Creates a new set from items that are in my_set1 but not in
my_set2
Set Operations and Methods
max(my_set) Get max item in the set
min(my_set) Get min item in the set
set(my_set) or my_set.copy() Creates a shallow copy of the set
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
dict() or {} Initialize new empty dictionary
{k1: v1, k2: v2, …, Initialize new dictionary with keys k1, k2, … , kn, with matching values v1,
kn: vn} v2, …, vn
my_dict[key] Get/assign value for key
del my_dict[key] Remove key from dictionary
my_dict.keys() Get all available keys
my_dict.values() Get all available values
Dictionary Operations and Methods
my_dict.items() Generate a list of (key, value) tuples
key in my_dict Check if key exists in dictionary
len(my_dict) Count number of entries
Conditional Statements
Conditional Statements
Question: How do you execute statements based on a condition?
Answer: Use conditional statements!
For Python, use if statements
Conditional Statements: If Syntax
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
By default, all NON-ZERO / NON-NONE / NON-EMPTY are considered True
True False
1 0
-1 None
[1, 2, 3] []
{‘a’ : 1} {}
“hello” “”
Iterative Statements
Iterative Statements
Question: How do you run statements until a condition is satisfied?
Answer: Use Iterative Statements!
Also known as loops
For Python, use while or for statements
Iterative Statements: While Syntax
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
my_list = ["Apple", "Orange", "Banana", "Strawberry", "Pineapple"]
while my_list:
element = my_list[0]
print(element)
del my_list[0]
Iterative Statements: For Syntax
for <variable_name> in <iterable>:
<statements that use variable_name>
Iterative Statements: For Syntax Example
my_list = [1, 3, “meow”, 7] OUTPUT:
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
Write a for loop that prints out this pattern:
*
**
***
****
*****
Iterative Statements: Break and Continue
● Use break to prematurely exit from a loop
● Use continue to skip the current iteration
Iterative Statements: Break Example
for x in range(1, 1000): OUTPUT:
if x % 7 == 0: 1
break 2
print(x) 3
4
5
6
Iterative Statements: Continue Example
for x in range(10): OUTPUT:
if x % 2 == 0: 1
continue 3
print(x) 5
7
9
Functions
Functions
A function is a block of reusable code.
Examples:
● print
● input
● len
● max
● min
Functions: Syntax
def function_name(param1, param2, …, paramN):
<function_code>
<optional return>
● When a function doesn’t return a value, it returns None by default
Functions: Example
Returning function No return function
def my_average(a, b): def print_average(a, b):
average = (a + b) / 2 average = (a + b) / 2
return average print(average)
ave = my_average(4, 6) print_average(4, 6)
print(ave)
Functions: Default parameter values
You can define a function with default parameter values
def print_stars(count=3):
print(“*” * count)
print_stars() # can call without parameter
print_stars(5) # can still call with parameter
Exceptions
Exceptions
An exception is an event that signals that something wrong happened in your
program
Exceptions: Scenario
Accept two numbers from a user, dividend =
then print the quotient. float(input(“Enter Dividend: “))
divisor =
float(input(“Enter Divisor: “))
print(dividend / divisor)
Exceptions: Scenario
dividend = What if the user entered non-numeric
float(input(“Enter Dividend: “)) inputs?
divisor =
float(input(“Enter Divisor: “)) What if the user entered 0 as divisor?
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:
raise Exception(“Exception Message”)
Exceptions: Raising Exceptions Example
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 [email protected]