Basics

Make script directly executable with a Python interpreter

# script must have the following line as first line

#!/usr/bin/env python3
print('Hello world!')

Get all properties and methods of an object

s1 = 'this is a string'
dir(s1)

Swap values of two variables (with multiple assignment)

# while evaluating an assignment, the right-hand side is evaluated
# before the left-hand side
a = 7
b = 99
a, b = b, a
print(a, b)

Swap values of two variables (with a third variable)

a = 7
b = 99
swap = a
a = b
b = swap
print(a, b)

Check a variable is not None

if value is not None:
    pass

Ternary conditional operator

statement_if_true if condition else statement_if_false

for statement

for val in collection:
    statement

for statement example

words = ['cat', 'window', 'defenestrate']
for w in words:
    print(w, len(w))

Iterate over a sequence of numbers (range function)

# generate integers from 2 to 9 inclusive
for n in range(2, 10):
    print(n, end=' ')

# Output
2 3 4 5 6 7 8 9

Iterate over a sequence of numbers (range function)

# built-in function
range(start, stop, step)
# start Optional. Position to start. Default is 0
# stop  Required. Position to stop (not included).
# step  Optional. The increment value. Default is 1

if statements

if condition1:
    statement1
elif condition2:
    statement2
else:
    statement3

while loop

while condition:
    statement1
    statement2

while loop example

n = 0
while n < 7:
    print(n, end=' ')
    n += 1

# Output
0 1 2 3 4 5 6

Fibonacci series

# A series of numbers where the next number is found by adding up
# the two numbers before it
a, b = 0, 1
while b < 100:
    print(b, end=' ')
    a, b = b, a + b

#Output
1 1 2 3 5 8 13 21 34 55 8

break and continue statements on loops

# The break statement, breaks out of the innermost enclosing `for` or `while` loop
for val in "string":
    if val == "i":
        break
    print(val, end=' ')

# Output
s t r

# The continue statement, continues with the next iteration of the loop
for val in "string":
    if val == "i":
        continue
    print(val, end=' ')

# Output
s t r n g

Command line arguments (sys.argv)

# save the code snippet as file `argv_test.py`
# run it with one argument:
# python argv_test.py first_argument
import sys
# command line arguments are stored in the form
# of list in sys.argv
argv_list = sys.argv
print(argv_list)

# the name of file is at index 0 of the list
print(sys.argv[0])

# the first argument after the name of file
print(sys.argv[1])

# Output
['argv_test.py', 'first_argument']
argv_test.py
first_argument