Yanfei Kang
yanfeikang@buaa.edu.cn
School of Economics and Management
Beihang University
http://yanfei.site
The core philosophy of the language:
Python enables programs to be written compactly and readably:
On Linux machine, Python is usually installed by default. To install Python on other systems, check out the Python Setup and Usage section in Python help documentation.
If you are using Windows, Anaconda is a good choice.
The Python interpreter is usually installed as /usr/bin/python3
on those machines where it is available.
To start a Python interpreter, type the command in your terminal: python3
.
To terminate the Python interpreter, type an end-of-file character (Control-D
on Linux, Control-Z
on Windows) at the primary prompt. If that doesn’t work, you can exit the interpreter by typing the following command: quit()
or exit()
.
Write down your Python script and name it as hello.py
with .py
extension.
Your script contents look like this
#!/usr/bin/python3
print('Hello World')
chmod +x hello.py
../hello.py
.Note: The line #!/usr/bin/python3
should appear at the very beginning of your file.
To edit Python code, you just need a handy text editor. There are many available, check out the following pages:
Help is available in Python sessions using help(function)
.
Some functions (and modules) have very long help files. When using IPython, these can be paged using the command ?function
or function?
so that the text can be scrolled using page up and down and q
to quit
. ??function
or function??
can be used to type the entire function including both the docstring
and the code.
Python has a large standard library, commonly cited as one of Python's greatest strengths, providing tools suited to many tasks.
Modules for creating graphical user interfaces, connecting to relational databases, pseudo random number generators, arithmetic with arbitrary precision decimals, manipulating regular expressions, and doing unit testing are also included.
As of September 2020, the Python Package Index, the official repository of third-party software for Python, contains more than 261,000 packages offering a wide range of functionality, including:
3 + 2 +4
9
5 + 4*3
17
8/5.0 # int / float -> float
1.6
8//5.0 # explicit floor division discards the fractional part
1.0
5**2
25
The equal sign (=) is used to assign a value to a variable. Afterwards, no result is displayed before the next interactive prompt:
a = 3
b = 5
c = a + b
c
8
In interactive mode, the last printed expression is assigned to the variable _. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations.
100/3.0
33.333333333333336
_
33.333333333333336
LastName = "Kang"
FirstName = "Yanfei"
print("Hello\nWorld!")
Hello World!
r
before the first quote:print(r"Hello \n World!")
Hello \n World!
Strings can be concatenated (glued together) with the +
operator, and repeated with *
:
"I " + 'L' + 'o'*5 + 've' + ' you'
'I Looooove you'
n = 10
"G"+"o"*n+"gle"
'Goooooooooogle'
The built-in function len()
returns the length of a string:
len("Yanfei Kang")
11
Two or more string literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated. This feature is particularly useful when you want to break long strings:
"Yanfei" "Kang"
'YanfeiKang'
print("Hi, my name is Yanfei Kang."
" And I am from Beijing.")
Hi, my name is Yanfei Kang. And I am from Beijing.
Strings can be indexed (subscripted), with the first character having index 0. There is no separate character type; a character is simply a string of size one:
Name = "Yanfei Kang"
Name[0]
'Y'
Name[-1]
'g'
Name[-2]
'n'
In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain a substring:
Name[0:6] #Remember that [0:6] mathematically means [0, 6).
'Yanfei'
Name[6:11]
' Kang'
Name[:6]
'Yanfei'
Name[6:]
' Kang'
Name[-4:]
'Kang'
Name[6:100]
' Kang'
Name2 = "Yanfei.Kang"
Name2.lower().title().split(".")
['Yanfei', 'Kang']
values = [1,5,7,9,12]
len(values)
5
values[0]
1
values[-2:]
[9, 12]
Lists also supports operations like concatenation:
values + ["Hello","World"]*3
[1, 2, 1000, 4, 67, 22, 9999, 'Hello', 'World', 'Hello', 'World', 'Hello', 'World']
Lists are a mutable type, i.e. it is possible to change their content:
values = [1,2,3,4,67,22]
values
[1, 2, 3, 4, 67, 22]
values[2] = 1000
values
[1, 2, 1000, 4, 67, 22]
You can also add new items at the end of the list, by using the append() method
values.append(9999)
values
[1, 2, 1000, 4, 67, 22, 9999]
Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:
values[2:4] = [2,3,4]
values
[1, 2, 2, 3, 4, 67, 22]
values[:] = []
values
len(values)
0
The Python interpreter has a number of functions built into it that are always available. They are listed here in alphabetical order. Use e.g. help(abs)
to see the function help.
abs() divmod() input() open()
staticmethod() all() enumerate()
int() ord() str() any()
eval() isinstance() pow() sum()
basestring() execfile() issubclass()
print() super() bin() file()
iter() property() tuple() bool()
filter() len() range() type()
bytearray() float() list()
raw_input() unichr() callable()
format() locals() reduce() unicode()
chr() frozenset() long() reload()
vars() classmethod() getattr() map()
repr() xrange() cmp() globals()
max() reversed() zip() compile()
hasattr() memoryview() round()
__import__() complex() hash() min()
set() apply() delattr() help()
next() setattr() buffer()
dict() hex() object() slice()
coerce() dir() id() oct()
sorted() intern()
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
Alternatively, you can do the following changes
import math as mt
mt.exp(1)
2.718281828459045
If you just want to import one or two functions from a module
from math import exp
exp(3)
20.085536923187668
from math import exp as myexp
myexp(1)
2.718281828459045
Perhaps the most well-known statement type is the if statement. For example:
x = -5
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
Negative changed to zero
Note
if
, elif
and else
statement.words = ['cat', 'window', 'defenestrate']
for j in words:
print(j,len(j))
print("I am done!")
cat 3 window 6 defenestrate 12 I am done!
def fib(n = 200): # write Fibonacci series up to n
"""
Print a Fibonacci series up to n.
Usage
fib(n)
""" # the function help
a, b = 0, 1
while a < n:
print(a, end=" ")
a, b = b, a+b
We can create a function that writes the Fibonacci series to an arbitrary boundary.
The first line should always be a short, concise summary that ends with a period.
If there are more lines in the documentation string, the second line should be blank.
The first statement of the function body can optionally be a string literal; this string literal is the function’s documentation string, or docstring.
help(fib)
Help on function fib in module __main__: fib(n=200) Print a Fibonacci series up to n. Usage fib(n)
fib(200)
0 1 1 2 3 5 8 13 21 34 55 89 144
fib()
0 1 1 2 3 5 8 13 21 34 55 89 144
Write a function to find the roots of $ax^2+bx+c=0$.
The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow. For example:
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('refusenik user')
print(complaint)
ask_ok("Do you really want to go?")
Do you really want to go?hao Yes or no, please! Do you really want to go?shi Yes or no, please! Do you really want to go?yes
True
a = f(1, 2) + g(3, 4)
.self
as the name for the first method argument (see A First Look at Classes for more on classes and methods).