Week 3 Python Fundamental 2
Week 3: Python Fundamental Part 2
# Loop list
neighborhoods = ['Indian Hill', 'Burncoat', 'Greendale']
for nei in neighborhoods:
print(nei)
Indian Hill Burncoat Greendale
Exercise 1: Loop a dictionary¶
Please loop key, values and items seperately from a dictionary
- loop key
- loop values? (hint: how to get the values from dictionary?)
- loop items? (hint: how to get the items from dictionary?)
worcester = {'state':'MA',
'population':206518,
'gov_type':'council_manager'
}
## get key
# for i in worcester:
# print(i)
# ## get values
# for value_dic in worcester.values():
# print(value_dic)
## get items
for item_dic in worcester.items() :
print(item_dic)
('state', 'MA') ('population', 206518) ('gov_type', '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():
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():
if city == "Boston":
print(pop)
653833
2.1 elif add the second contion in for loop¶
for city, pop in cities.items():
if pop < 200000:
print('{} is a small city'.format(city))
elif pop > 200000:
print('{} is a large city'.format(city))
else:
print("No results")
Boston is a large city Worcester is a large city Springfield is a small city 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():
if pop > 200000:
print('{} is a large city, population is {}'.format(city,pop))
continue
Boston is a large city, population is 653833 Worcester is a large city, population is 207621
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):
for city,pop in input_dict.items():
if pop > 200000:
return '{} is a large city, population is {}'.format(city,pop)
cities = {'Boston':653833,
'Worcester':207621,
'Springfield':153672,
'Cambridge':118214}
find_large_city(cities)
'Boston is a large city, population is 653833'
Exercise 5: 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 user input the park's name
def get_yr(parks, input_name):
for city, yr in parks.items():
if city == input_name:
return yr
parks = {
'Green hill':1875,
'Elm': 1854,
'Institute': 1887,
'Salisbury': 1887
}
get_yr(parks, "Institute")
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)
'Both numbers are positive.'
Exercise 6: User-defined function¶
Write a function to return the temperate from Celsius to Fahrenheir
Fahrenheit = (Celsius * 9/5) + 32
- Write a function
- Set up input value as '30'
def convert(c):
f = c*9/5+32
return f
convert(50)
122.0
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.
## check the built-in modules
help('modules')
Please wait a moment while I gather a list of all available modules...
e:\Anaconda\Lib\site-packages\paramiko\transport.py:219: CryptographyDeprecationWarning: Blowfish has been deprecated and will be removed in a future release "class": algorithms.Blowfish, e:\Anaconda\Lib\site-packages\nltk\twitter\__init__.py:20: UserWarning: The twython library has not been installed. Some functionality from the twitter package will not be available. warnings.warn( e:\Anaconda\Lib\pkgutil.py:78: UserWarning: The numpy.array_api submodule is still experimental. See NEP 47. __import__(info.name) No QCoreApplication instance found. Application patches not applied. You have to call load_stylesheet function after instantiation of QApplication to take effect.
7f0197f6d050da244d93__mypyc colorsys menuinst sndhdr IPython comm mimetypes sniffio OpenSSL commctrl mistune snowballstemmer PIL compileall mkl socket PyQt5 concurrent mkl_fft socketserver __future__ conda mmap socks __hello__ conda_build mmapfile sockshandler __phello__ conda_content_trust mmsystem sortedcontainers _abc conda_env modulefinder soupsieve _aix_support conda_index more_itertools sphinx _argon2_cffi_bindings conda_libmamba_solver mpmath spyder _ast conda_pack msgpack spyder_kernels _asyncio conda_package_handling msilib sqlalchemy _bisect conda_package_streaming msvcrt sqlite3 _black_version conda_token multidict sre_compile _blake2 configparser multipledispatch sre_constants _brotli constantly multiprocessing sre_parse _bz2 contextlib mypy ssl _cffi_backend contextvars mypy_extensions sspi _codecs contourpy mypyc sspicon _codecs_cn cookiecutter nacl stack_data _codecs_hk copy navigator_updater stat _codecs_iso2022 copyreg nbclient statistics _codecs_jp cpuinfo nbconvert statsmodels _codecs_kr crypt nbformat streamlit _codecs_tw cryptography nest_asyncio string _collections cssselect netbios stringprep _collections_abc csv netrc struct _compat_pickle ctypes networkx subprocess _compression curl nltk sunau _contextvars curses nntplib sympy _csv cwp notebook symtable _ctypes cycler notebook_shim sys _ctypes_test cytoolz nt sysconfig _datetime dask ntpath tables _decimal dask_expr ntsecuritycon tabnanny _distutils_hack dataclasses nturl2path tabulate _elementtree datashader numba tarfile _functools datetime numbergen tblib _hashlib dateutil numbers telnetlib _heapq dbi numexpr tempfile _imp dbm numpy tenacity _io dde numpydoc terminado _json debugpy odbc test _locale decimal opcode test_pycosat _lsprof decorator openpyxl text_unidecode _lzma defusedxml operator textdistance _markupbase diff_match_patch optparse textwrap _md5 difflib os this _msi dill overrides threading _multibytecodec dis packaging threadpoolctl _multiprocessing distributed pandas three_merge _nsis distro pandocfilters tifffile _opcode docstring_to_markdown panel time _operator doctest param timeit _osx_support docutils paramiko timer _overlapped dotenv parsel tinycss2 _pickle email parso tkinter _plotly_future_ encodings partd tldextract _plotly_utils ensurepip pathlib tlz _py_abc entrypoints pathspec token _pydatetime enum patsy tokenize _pydecimal erfa pdb toml _pyio errno perfmon tomli _pylong et_xmlfile pexpect tomlkit _pytest executing pickle tomllib _queue fastjsonschema pickleshare toolz _random faulthandler pickletools tornado _sha1 filecmp pip tqdm _sha2 fileinput pipes trace _sha3 filelock pkce traceback _signal flake8 pkg_resources tracemalloc _sitebuiltins flask pkginfo traitlets _socket fnmatch pkgutil truststore _sqlite3 fontTools platform tty _sre fractions platformdirs turtle _ssl frozendict plistlib turtledemo _stat frozenlist plotly twisted _statistics fsspec pluggy types _string ftplib ply typing _strptime functools poplib typing_extensions _struct gc posixpath tzdata _symtable genericpath pprint uc_micro _system_path gensim profile ujson _testbuffer getopt prometheus_client unicodedata _testcapi getpass prompt_toolkit unicodedata2 _testclinic gettext protego unidecode _testconsole git pstats unittest _testimportmultiple gitdb psutil urllib _testinternalcapi glob pty urllib3 _testmultiphase graphlib ptyprocess uu _testsinglephase greenlet pure_eval uuid _thread gzip py venv _threading_local h5py py_compile w3lib _tkinter hashlib pyarrow warnings _tokenize heapdict pyasn1 watchdog _tracemalloc heapq pyasn1_modules wave _typing hmac pyclbr wcwidth _uuid holoviews pycodestyle weakref _warnings html pycosat webbrowser _weakref http pycparser webencodings _weakrefset hvplot pyct websocket _win32sysloader hyperlink pycurl werkzeug _winapi idlelib pydantic whatthepatch _winxptheme idna pydantic_core wheel _wmi imagecodecs pydeck widgetsnbextension _xxinterpchannels imageio pydispatch win2kras _xxsubinterpreters imagesize pydoc win32api _yaml imaplib pydoc_data win32clipboard _zoneinfo imblearn pydocstyle win32com abc imghdr pyexpat win32con adodbapi importlib pyflakes win32console afxres importlib_metadata pygments win32cred aifc incremental pylab win32crypt aiobotocore inflection pylint win32cryptcon aiohttp iniconfig pylint_venv win32ctypes aioitertools inspect pyls_spyder win32event aiosignal intake pylsp win32evtlog alabaster intervaltree pylsp_black win32evtlogutil altair io pylsp_jsonrpc win32file anaconda_anon_usage ipaddress pyodbc win32gui anaconda_catalogs ipykernel pyparsing win32gui_struct anaconda_cloud_auth ipykernel_launcher pytest win32help anaconda_navigator ipython_genutils pythoncom win32inet anaconda_project ipywidgets pythonjsonlogger win32inetcon annotated_types isapi pytoolconfig win32job antigravity isort pytz win32lz anyio isympy pyviz_comms win32net appdirs itemadapter pywin win32netcon archspec itemloaders pywin32_bootstrap win32pdh argon2 itertools pywin32_testutil win32pdhquery argparse itsdangerous pywintypes win32pdhutil array jedi pywt win32pipe arrow jellyfish qdarkstyle win32print ast jinja2 qstylizer win32process astroid jmespath qtawesome win32profile astropy joblib qtconsole win32ras astropy_iers_data json qtpy win32rcparser asttokens json5 queue win32security async_lru jsonpatch queuelib win32service asyncio jsonpointer quopri win32serviceutil atexit jsonschema random win32timezone atomicwrites jsonschema_specifications rasutil win32trace attr jupyter re win32traceutil attrs jupyter_client referencing win32transaction audioop jupyter_console regcheck win32ts automat jupyter_core regex win32ui autopep8 jupyter_events regutil win32uiole babel jupyter_lsp repo_cli win32verstamp base64 jupyter_server reprlib win32wnet bcrypt jupyter_server_terminals requests win_inet_pton bdb jupyterlab requests_file winerror binaryornot jupyterlab_plotly requests_toolbelt winioctlcon binascii jupyterlab_pygments rfc3339_validator winnt binstar_client jupyterlab_server rfc3986_validator winperf bisect jupyterlab_widgets rich winpty black jwt rlcompleter winreg blackd keyring rope winsound bleach keyword rpds winxpgui blib2to3 kiwisolver rtree winxptheme blinker lazy_loader ruamel_yaml wrapt bokeh lazy_object_proxy runpy wsgiref boltons lckr_jupyterlab_variableinspector s3fs xarray botocore lib2to3 sched xdrlib bottleneck libarchive scipy xlwings brotli libmambapy scrapy xlwingsjs bs4 lief seaborn xml builtins linecache secrets xmlrpc bz2 linkify_it select xxlimited cProfile llvmlite selectors xxlimited_35 cachetools lmdb semver xxsubtype calendar locale send2trash xyzservices certifi locket service_identity yaml cffi logging servicemanager yapf cgi lxml setuptools yapf_third_party cgitb lz4 shelve yapftests chardet lzma shlex yarl charset_normalizer mailbox shutil zict chunk mailcap signal zipapp click markdown sipbuild zipfile cloudpickle markdown_it site zipimport cmath markupsafe six zipp cmd marshal skimage zlib code math sklearn zmq codecs matplotlib slugify zoneinfo codeop matplotlib_inline smart_open zope collections mccabe smmap zstandard colorama mdit_py_plugins smtplib colorcet mdurl snappy Enter any module name to get more help. Or, type "modules spam" to search for modules whose name or summary contain the string "spam".
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)
8
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)
7
Exercise : Get the sine of a number from math module¶
- import
math
module - use
sin()
function in math module to calculatesin(3)
from math import sin
sin(3)
0.1411200080598672
5. 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
- 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 5
6.1 input and if¶
get_num = int(input("Please input a number"))
if get_num <= 5:
print('smaller than 5')
else:
print('larger than 5')
Exercise 7: 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
# 2. print a message that tell user the guess range
# 3. Initialize the value of guess number as None
# 4. use a while loop to keep asking the user for guesses
# 5. After each incorrect guess, tell the user whether their guess was too high or too low: using if condition
# 6. When the user guesses correctly, print a congratulatory messag and stop the loop
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')
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[3], line 4 2 rst = num/3 3 print(rst) ----> 4 calculate('str') Cell In[3], 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("End")
rst_num = calculate('str')
print(rst_num)
# print(calculate(6))
Please input a valid number End None