1 Common Functions

1.1 Printing

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

1.2 Type

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'>

Type Casting

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

1.3 The range() Function

range(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

1.4 User Input: input()

>>> name = input('Please enter your name:\n')
Please enter your name:
>? Liao
>>> name
Liao

2 Math & Arithmetic

2.1 math Library

import 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().

2.2 Built-in

x = -10
print(abs(x))
10

2.3 Arithmetic Operators

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.

Other Operators

  • %: modulus
  • //: floor division

3 Boolean & Logical

3.1 Boolean Expressions

  • True
  • False
  • ==, !=
  • >, >=, <, <=

3.2 Logical Operators

  • 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

4 Flow Control

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

5 String

5.1 String Concatenation

str1 = 'A' + '' + 'string'
str2 = 'Text '*4
print(str1)
Astring
print(str2)
Text Text Text Text 

6 Programming Concepts

6.1 Recursion

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!