print("Hello World!") # Single & double quotes are both legal
Hello World!
print('tab_before\ttab_after')
tab_before tab_after
print('line 1\nline 2')
line 1
line 2
a = 1 # integer
b = 1.0 # float
c = 'str' # string
print('Printing an integer: {}, a floating point number: {}, and a string: {}'.format(a, b, c))
Printing an integer: 1, a floating point number: 1.0, and a string: str
a = 1 # integer
b = 1.0 # float
c = 'str' # string
print("{}\n{}\n{}".format(type(a), type(b), type(c)))
<class 'int'>
<class 'float'>
<class 'str'>
int1 = int('300')
int2 = int(30.7)
fl1 = float(1)
fl2 = float('1')
str1 = str(123)
print('int1 = {}\tint2 = {}\nfl1 = {}\tfl2 = {}\nstr1 = {}'.format(int1, int2, fl1, fl2, str1))
int1 = 300 int2 = 30
fl1 = 1.0 fl2 = 1.0
str1 = 123
range()
Functionrange(start, stop, step)
Commonly used in for loop:
for i in range(3): # range(3) == range(0, 3)
print(i)
0
1
2
for i in range(0, 10, 2): # range(10) == range(0, 10)
print(i)
0
2
4
6
8
input()
>>> name = input('Please enter your name:\n')
Please enter your name:
>? Liao
>>> name
Liao
math
Libraryimport math
inf = math.inf # Infinity
print(2018 / inf)
0.0
Other math attributes include math.pi
, math.e
, math.nan
, and some useful functions: math.ceil()
, math.floor()
, math.cos()
.
x = -10
print(abs(x))
10
a1 = 10
a2 = 10
b = 1
a1 += b
a2 = a2 + b # Eqivalent to a2 += b
print('a1 = {}\na2 = {}'.format(a1, a2))
a1 = 11
a2 = 11
-=
, *=
, /=
are equivalent forms for substraction, multipilcation, and division, respectively.
%
: modulus//
: floor divisionTrue
False
==
, !=
>
, >=
, <
, <=
and
or
Note that a < x and x < b
can be simplified as a < x < b
:
x = 5
if 0 < x < 10:
print(True)
True
if <condition>:
<commands>
elif <condition>:
<commands>
else:
<commands>
while <condition>:
<commands>
a = 1
if 2 <= a:
print('2 <= {}'.format(a))
else:
print('2 > {}'.format(a))
2 > 1
str1 = 'A' + '' + 'string'
str2 = 'Text '*4
print(str1)
Astring
print(str2)
Text Text Text Text
A function that calls itself in its definition.
def countdown(n):
if n <= 0:
print('Blastoff!')
else:
print(n)
countdown(n-1)
countdown(5)
5
4
3
2
1
Blastoff!