Feng Li
School of Statistics and Mathematics
Central University of Finance and Economics
help(abs)
to see the function help.abs() aiter() all() any() anext() ascii() bin() bool() breakpoint() bytearray() bytes() callable() chr() classmethod() compile() complex() delattr() dict() dir() divmod() enumerate() eval() exec() filter() float() format() frozenset() getattr() globals() hasattr() hash() help() hex() id() input() int() isinstance() issubclass() iter() len() list() locals() map() max() memoryview() min() next() object() oct() open() ord() pow() print() property() range() repr() reversed() round() set() setattr() slice() sorted() staticmethod() str() sum() super() tuple() type() vars() zip() __import__()
To import a module (like math
) that is not in Python's default module, use
import math
Then you can use all the mathematical functions inside math
module as:
math.exp(0)
1.0
import math as mt
mt.exp(1)
2.718281828459045
from math import exp
exp(3)
20.085536923187668
from math import exp as myexp
myexp(1)
2.718281828459045
pip
in a terminal to install a Python module from PyPi (https://pypi.org) on your user directory.pip install numpy --user
pip install numpy --user -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install pandas -U
pip uninstall numpy
You could issue the above commands within the Jupyter notebook. Just place the !
in front of the command
! pip3 install pandas -U
Looking in indexes: https://mirrors.163.com/pypi/simple/ Requirement already satisfied: pandas in /usr/local/lib/python3.9/dist-packages (1.3.4) Collecting pandas Using cached https://mirrors.163.com/pypi/packages/48/b4/1081d66b71c4dfc1bc1e19d6f2abbf93ed42f69df7703eb323742d45423e/pandas-1.3.4-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (11.5 MB) Using cached https://mirrors.163.com/pypi/packages/03/ea/98d488a4047b3fd8075b5c1e00469ad42d715e2c1e4fd15fa1ffaef8d635/pandas-1.3.3-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (11.5 MB) Requirement already satisfied: python-dateutil>=2.7.3 in /usr/lib/python3/dist-packages (from pandas) (2.8.1) Requirement already satisfied: numpy>=1.17.3 in /usr/local/lib/python3.9/dist-packages (from pandas) (1.21.2) Requirement already satisfied: pytz>=2017.3 in /usr/lib/python3/dist-packages (from pandas) (2021.3)
x = 0
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
Cell In[4], line 6 elif x == 0: ^ SyntaxError: invalid syntax
Note
if
, elif
and else
statement.indentation
is very important. The first non-blank line after the first line of the string determines the amount of indentation for the entire documentation string.for
Statements¶words = ['cat', 'window', 'defenestrate']
for w in words:
print(w, len(w))
cat 3 window 6 defenestrate 12
a = [3,5,0]
b = [1, 9, 7]
c = [2, 4, 4]
for i in [0,1,2]:
a1 = a[i]
b1 = b[i]
c1 = ???
d = ???
if d > 0:
print("two")
elif d == 0:
print???
else
???
x = [1900, 2000, 2004, 2011, 2022]
for year in x:
if (year % 400 == 0) or (year % 100 != 0 and year % 4 == 0):
print(year, "is a leap year")
else:
print(year, "is not a leap year")
1900 is not a leap year 2000 is a leap year 2004 is a leap year 2011 is not a leap year 2022 is not a leap year
We can create a function that writes the Fibonacci series to an arbitrary boundary.
The function should also include a proper help with the docstring
The first line should always be a short, concise summary of the object's purpose.
If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description.
The following lines should be one or more paragraphs describing the object's calling conventions, its side effects, etc.
# 0, 1, 1, 2, 3, 5,
def fib(n): # write Fibonacci series up to n
"""Print a Fibonacci series up to n.
par n: integer
out : list
""" # the function help
a, b = 0, 1
while a < n:
print(a, end=' ')
# better than print(a), why?
a, b = b, a+b
help(fib)
Help on function fib in module __main__: fib(n) Print a Fibonacci series up to n. par n: integer out : list
fib(20000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
while True:
ok = input(prompt)
if ok in ('y', 'ye', 'yes'):
return True
if ok in ('n', 'no', 'nop', 'nope'):
return False
retries = retries - 1
if retries < 0:
raise IOError('too many tries')
print(complaint)
ask_ok("Do you really want to go, dear?", retries=2)
lambda
keyword.Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope. The example uses a lambda expression to return a function
def make_incrementor(n):
return lambda x: x + n
f = make_incrementor(42)
f(0)
42
f(1)
43
The anonymous function is very useful in manipulating the list
and Python DataFrame (pandas
)
mycollections.py
, we could import the function as follows>>> import mycollections
>>> mycollections.fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
>>> from mycollections import fib
>>> fib(2000)
import mycollections
mycollections.fib
<function mycollections.fib(n)>
mycollections.fib(100)
0 1 1 2 3 5 8 13 21 34 55 89
from mycollections import fib
import os
os.getcwd()
'/home/fli/carbon/teaching/python/python-slides/P01-Python-from-Scratch'
def fib(n): # write Fibonacci series up to n
"""Print a Fibonacci series up to n.
argument
n: numeric number
vaule
return Fibonacci series
"""
a, b = 0, 1
while a < n:
print(a, end=' ')
# better than print(a), why?
a, b = b, a+b
fib(10)
0 1 1 2 3 5 8
import feng
feng.fib(100)
0 1 1 2 3 5 8 13 21 34 55 89