Week 3 Python Fundamental 2
Week 3: Python Fundamental Part 2
# Loop list
neighborhoods = ['Indian Hill', 'Burncoat', 'Greendale']
for single_nei in neighborhoods:
print(single_nei)
Indian Hill Burncoat Greendale
Exercise 1: Loop a dictionary¶
Please loop key, values and items seperately from a dictionary
worcester = {'state':'MA', 'population':206518, 'gov_type':'council_manager' }
- loop key
worcester = {'state':'MA',
'population':206518,
'gov_type':'council_manager'
}
for i in worcester:
print(i)
state population gov_type
- loop values? (hint: how to get the values from dictionary?)
for i in worcester.values():
print(i)
MA 206518 council_manager
- loop items? (hint: how to get the items from dictionary?)
for all in worcester.items():
print(all)
('state', 'MA') ('population', 206518) ('gov_type', 'council_manager')
for values, keys in worcester.items():
print(keys)
MA 206518 council_manager
2. Conditionals: If...Elif...Else¶
if statement and loops is way to determine the condition and make decision.
cities = {'Boston':653833,
'Worcester':207621,
'Springfield':153672,
'Cambridge':118214}
for city, pop in cities.items():
# print(city)
if pop > 200000:
print('{} is a large city'.format(city))
Boston is a large city Worcester is a large city
Exercise 3: print the population if the city name is 'Boston'¶
hint: equal in Python is '=='
for city, pop in cities.items():
# print(city)
if city == 'Boston':
print('{} population is {}'.format(city, pop))
Boston population is 653833
2.1 elif add the second contion in for loop¶
for city, pop in cities.items():
if pop < 150000:
print('{} is a small city'.format(city))
elif pop > 200000:
print('{} is a large city'.format(city))
else:
print('{} does not belong to any group'.format(city))
Boston is a large city Worcester is a large city Springfield does not belong to any group Cambridge is a small city
for city, pop in cities.items():
if pop > 200000:
print('{} is a large city, population is {}'.format(city,pop))
break
Boston is a large city, population is 653833
Exercise 4. Replace break with continue¶
Replace the break with continue to see the difference
You shoud get two results since the code will continue
for city, pop in cities.items():
for i in range(1,3):
if pop > 500:
print('{} is a large city, population is {}'.format(city,pop))
# i = i+1
# print(i)
continue
Boston is a large city, population is 653833 Boston is a large city, population is 653833 Worcester is a large city, population is 207621 Worcester is a large city, population is 207621 Springfield is a large city, population is 153672 Springfield is a large city, population is 153672 Cambridge is a large city, population is 118214 Cambridge is a large city, population is 118214
4. Functions¶
A function takes one or more inputs and return one of more outputs
The code wihitn the function runs only when it is called
# def funtion_name(input):
# ...
# return outputs
def find_large_city(input_dict, population_num):
for city,pop in input_dict.items():
if pop > population_num:
return '{} is a large city, population is {}'.format(city,pop)
cities = {'Boston':653833,
'Worcester':207621,
'Springfield':153672,
'Cambridge':118214}
find_large_city(cities,500)
'Boston is a large city, population is 653833'
Exercise 5: User-defined function¶
Previous function only return one result as soon as it finds the first city with a population greater than the specified number.
If you want it to return all citie that meet the criteria, you can modify the function to collect all matching cities and return them.
- create a empty list inside the function
- append each result to the list
def find_large_city(input_dict, population_num):
# empty list
newlist = []
for city,pop in input_dict.items():
if pop > population_num:
# append city to list
newlist.append(city)
# return '{} is a large city, population is {}'.format(city,pop)
return newlist
find_large_city(cities,500)
['Boston', 'Worcester', 'Springfield', 'Cambridge']
Exercise 6: User-defined function¶
Given a dictionary parks = { 'Green hill':1875, 'Elm': 1854, 'Institute': 1887, 'Salisbury': 1887 }, write a function to ouput the year of the park based on input as dictionary and park's name (string)
parks = {
'Green hill':1875,
'Elm': 1854,
'Institute': 1887,
'Salisbury': 1887
}
4.1 and
and or
are logical operators used to combine multiple conditions.
def check_numbers(a, b):
if a > 0 and b > 0:
return "Both numbers are positive."
elif a > 0 or b > 0:
return "At least one number is positive."
else:
return "Neither number is positive."
check_numbers(5,-3)
'At least one number is positive.'
Exercise 7: User-defined function¶
You can set up initial values for the arguments in the check_numbers function by providing defautl values in the fucntion definition.
def check_numbers(a=0, b=0):
if a > 0 and b > 0:
return "Both numbers are positive."
elif a > 0 or b > 0:
return "At least one number is positive."
else:
return "Neither number is positive."
check_numbers(a=3)
'At least one number is positive.'
5. Module¶
Module is a folder that contain a set of functions you want to include in your applications
Using the import
statement to use the module
Build-in modules are pre-installed with the Python installation.
random module¶
random
module in Python provides functions for generating random numbers
- randint() function return a random integer between a and b:
random.randint(a,b)
import random
num = randint(0,10)
print(num)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[1], line 2 1 import random ----> 2 num = randint(0,10) 3 print(num) NameError: name 'randint' is not defined
if you want to use randint()
directly without the random
prefix. You can import the function specifically like this
from random import randint
number = randint(1,10)
print(number)
3
Exercise 8: Get the sine of a number from math module¶
- import
math
module - use
sin()
function in math module to calculatesin(3)
Exercie 9. Writing and Using Python Modules¶
- Creating a module is simple:
- Write your Python code in a .py file.
- Save the file with a meaningful name.
Write function in the module
Import function from the module
import defined_math
defined_math.add_numbers(7,9)
16
import math_function
math_function.divide(4,2)
2.0
6. While loop¶
With the while loop we can execute a set of statements as long as a condition(or expression) is true
Below example is to show the while loop generate a list of numbers but remember that to increase i, or else the loop will continue forever
While expression:
statements
i = 1
while i <= 5:
print(i)
i += 1
1 2 3 4 5
Exercie 11:Counting Down Timer¶
Let the while counts down from 10 to 1. When countdown reaches 0, the loop stops, and a message is printed
i = 10
while i >= 0:
print(i)
i -= 1
10 9 8 7 6 5 4 3 2 1 0
6. User input¶
input()
function get user input, and converting that input from a string to an integer
Syntax:
input(prompt) prompt: a string, representing a message before the input
get_name = input("Please input a number")
print("okay, the number is " + get_name)
okay, the number is 10
6.1 input and if¶
get_num = int(input("Please input a number"))
if get_num <= 5:
print('Your number is smaller than 5')
else:
print('Your number is larger than 5')
Your number is smaller than 5
Exercise 12: Guess the Secret Number¶
Write a python program that generates a random number between 1 and 20. The program will then repeatedly prompt the user to guess the number. The loop will continue until the user guesses the correct number.
import random
# 1. generate a random integer number between 1 and 20
import random
get_random_num = random.randint(1,20)
selected_num = None
# 2. use a while loop to keep asking the user for guesses
while selected_num != get_random_num:
# 3. use input function to get the input number
selected_num = int(input("Please input a number"))
# 4. After each incorrect guess, tell the user whether their guess was too high or too low: using if condition
if selected_num < get_random_num:
print('Your guessed number is lower')
elif selected_num > get_random_num:
print("Your guessed number is higher")
else:
print("Congrats! Your number is correct!")
Your guessed number is higher Your guessed number is lower Your guessed number is lower Your guessed number is lower Congrats! Your number is correct!
6.2 The break statement¶
With the break statement we can stop the while loop
i = 1
while i < 8:
print(i)
i += 1
if i == 3:
break
1 2
7. Error Handing exception¶
Error is the common issue in your code, how your responds to these errors, called exceptions.
- try | except | finally
- try statement is used to process a block of code
- except is used to catch the error
- finally always run the code regardless of whether an exception occurred, providing feedback that the process is complete
def calculate(num):
rst = num/3
print(rst)
calculate('str')
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[21], line 4 2 rst = num/3 3 print(rst) ----> 4 calculate('str') Cell In[21], line 2, in calculate(num) 1 def calculate(num): ----> 2 rst = num/3 3 print(rst) TypeError: unsupported operand type(s) for /: 'str' and 'int'
def calculate(num):
try:
rst = num/3
return rst
except TypeError:
print('Please input a valid number')
finally:
print("The function is ended, and the result is listed below")
rst_num = calculate(3)
print(rst_num)
The function is ended, and the result is listed below 1.0
print(calculate(6))
Exercise 13¶
The function below is about devide two number. But it raise a 'ZeroDevisionError'. Please modify the function to handle the error.
def divide_numbers(a, b):
try:
result = a / b
return result
# except ZeroDivisionError:
# print('no zero for b')
finally:
print("The function execution is complete.")
# Example usage
result_value = divide_numbers(10, 0)
print(result_value)
The function execution is complete.
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) Cell In[26], line 11 8 print("The function execution is complete.") 10 # Example usage ---> 11 result_value = divide_numbers(10, 0) 12 print(result_value) Cell In[26], line 3, in divide_numbers(a, b) 1 def divide_numbers(a, b): 2 try: ----> 3 result = a / b 4 return result 5 # except ZeroDivisionError: 6 # print('no zero for b') 7 finally: ZeroDivisionError: division by zero
Exercise 14: Understanding if name == "main": in module¶
The special construct if name == "main" is used for:
- Imported as a module in another script.
- Determine whether a script is being run as the main program
# Imported as a module in another script.
import print_number
print_number.numbers()
5
# Run the script directly in terminal