Week 5 Python Fundamental 2
Week 5: Python Fundamental Part 2
# Loop list
neighborhoods = ['Downtown Conway', 'Centennial Valley', 'West Conway']
for nei in neighborhoods:
print(nei)
Downtown Conway Centennial Valley West Conway
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
conway = {
'state': 'AR',
'population': 64000,
'gov_type': 'mayor_council'
}
## get keys
state population gov_type
- loop values? (hint: how to get the values from dictionary?)
## get values
AR 64000 mayor_council
- loop items? (hint: how to get the items from dictionary?)
## get items
state population gov_type
2. Conditionals: If...Elif...Else¶
if statement and loops is way to determine the condition and make decision.
cities = {
'Little Rock': 202591,
'Fort Smith': 89467,
'Fayetteville': 99940,
'Springdale': 84311
}
for city, pop in cities.items():
if pop > 200000:
print('{} is a large city'.format(city))
Little Rock is a large city
Exercise 3: print the population if the city name is 'Fort Smith'¶
hint: equal in Python is '=='
89467
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))
Little Rock is a large city Fort Smith is a small city Fayetteville is a small city Springdale is a small city
for city, pop in cities.items():
if pop > 85000:
print('{} is a large city, population is {}'.format(city,pop))
break
Little Rock is a large city, population is 202591
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
Little Rock is a large city, population is 202591 Fort Smith is a large city, population is 89467 Fayetteville is a large city, population is 99940
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 = {
'Little Rock': 202591,
'Fort Smith': 89467,
'Fayetteville': 99940,
'Springdale': 84311
}
find_large_city(cities,100000)
'Little Rock is a large city, population is 202591'
Exercise 6: User-defined function¶
Given a dictionary parks = {
'Cadron Settlement Park': 2006,
'Beaverfork Park': 1996,
'Laurel Park': 1921,
'Hendrix Creek Preserve': 2016
}, write a function to ouput the year of the park based on input as dictionary and park's name (string)
parks_dict = {
'Cadron Settlement Park': 2006,
'Beaverfork Park': 1996,
'Laurel Park': 1921,
'Hendrix Creek Preserve': 2016
}
find_park('Laurel Park', parks_dict)
1921
find_park('Hendrix Creek Preserve', parks_dict)
2016
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)
'Both numbers are 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.
'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 = random.randint(0,10)
print(num)
9
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
mathmodule - use
sin()function in math module to calculatesin(3)
from math import sin
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
from defined_math import substract_number, add_numbers
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 <= 8:
print(i)
i += 1
1 2 3 4 5 6 7 8
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
10 9 8 7 6 5 4 3 2 1 Time's up!
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)
Please input a number2 okay, the number is 2
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')
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
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')
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('str')
print(rst_num)
Please input a valid number The function is ended, and the result is listed below None
print(calculate(6))
The function is ended, and the result is listed below 2.0
Exercise 12¶
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
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) /tmp/ipython-input-2575125027.py in <cell line: 0>() 7 8 # Example usage ----> 9 result_value = divide_numbers(10, 0) 10 print(result_value) /tmp/ipython-input-2575125027.py in divide_numbers(a, b) 1 def divide_numbers(a, b): 2 try: ----> 3 result = a / b 4 return result 5 finally: ZeroDivisionError: division by zero
Error: Division by zero is not allowed. The function execution is complete. None