"Python is an interpreted high-level programming language for general-purpose programming" - wikipedia.org
python3 my_python_script.py
def helloworld(name): # function
print("Hello world!") # call of print function
print("your name is " + name)
helloworld("Chuck Norris") # call of helloworld function
print()
prints text on the standard output
In Python3 print("text")
is a function call
In Python2 print "text"
is just an instruction and is not available in Python3
print("Hello World") # a simple print
# format the character string
print("{0} is the answer".format(42)) # inserts the value of .format into the string
print("{0} has {1} {2}, because of reasons".format("Chuck Norris", 12, "cats")) # multiple inserts
Variable assignments by using the "=" operator
variable = 1 # character string
# variable identifier cannot start with a number
1variable = 3 # throws error
number1 = 1 # integer
print(type(number1))
number2 = 0.5 # floating point number
print(type(number2))
# addition
print(1 + 2)
# subtraction
print(2 - 1)
# multiplication
print(3 * 2)
# division
print(3 / 2) # floating point division
print(3 // 2) # integer division
# power
print(2 ** 3)
print(pow(2,3))
# modulo
print(18 % 10)
print(28 % 10)
# assignment
a = 1 # integer
print(a)
b = "text" # string
print(b)
c = 1.0 # float
print()
# incrementation
a = 1
a += 1 # is the same as a = a + 1
print(a)
This works also with this operations:
a -= 2
a *= 2
a /= 2
a //= 2
if 1 == 2:
print("this is correct")
else:
print("this is not correct")
if 1 == 1 and 2 != 1:
print("this is also correct")
Comparison
Operator | Meaning |
---|---|
== | equal |
!= | not equal |
< | strictly less than |
<= | less than or equal |
> | strictly greater than |
>= | greater than or equal |
Bitwise Operators
Operator | Meaning |
---|---|
& | binary AND |
| | binary OR |
^ | binary XOR |
<< | binary left shift |
>> | binary right shift |
~ | complement/not |
Boolean Operators
Operator | Meaning |
---|---|
and | logical AND |
or | logical OR |
not | logical NOT |
text = "This is a character string"
print(text)
print("This is another character string")
# Quotes indicate strings
text = "This is a string"
text = 'This is another string'
# You can use quotes inside strings
text = "This is a 'new' string"
print(text)
text = 'This is another "new" string'
print(text)
text = "This is \"another\" string" # escaping the quotes
print(text)
text = 'This is \'another\' string' # escaping the quotes
print(text)
Python uses an indexing starting at position 0
my_list = [1,2,3,4,5] # integer list
print(my_list)
my_list = [1,2,3,4,5]
print(my_list[0]) # first list element
print(my_list[1]) # second list element
print(my_list[-1]) # last list element
print(my_list[:3]) # first three list elements
print(my_list[1:3]) # get list elements starting at the second element end stopping before the fourth
#append element to list
my_list = [1,2,3,4,5]
my_list.append(42) # append a 42 at the end
print(my_list)
# insert element in list a a position
my_list.insert(0,16) # insert 16 at position 0
print(my_list)
my_list.insert(3, 32) # insert 32 at position 3
print(my_list)
# remove element from list
my_list = [1,2,3,4,5]
my_list.pop() # remove last element
print(my_list)
my_list.pop(0) # remove element at position 0
print(my_list)
my_list.pop(2) # remove element at position 2
print(my_list)
# list functions
my_list = [1,2,3,4,5]
print(max(my_list)) # max gives the highest value of a list
print(min(my_list)) # min gives the lowest value of a list
print(len(my_list)) # len gives the length of a list
# checks (elements in the list have to be of same type)
print(5 in my_list) # check if an element is in a list
print(42 not in my_list) # check if an element is not in a list
# shallow copy vs deep copy
a = [1,2,3,4,5]
b = a # shallow copy
b.append(42)
print(a)
print(b)
from copy import deepcopy
a = [1,2,3,4,5]
b = deepcopy(a)
b.append(42)
print(a)
print(b)
# Multidimensional List
matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
print(matrix)
print()
print(matrix[0][1]) # get the the element at row 0 and column 1
print()
#print(matrix[0]) # get all elements at index 0 of all rows
#print()
print(matrix[0]) # get all elements of row 0
print(matrix[:2]) # get all row until row 2
more list information can be found at python documentation
A tuple is an ordered immutable list of mixed types
# tuple is indicated with: ()
t = ("Chuck", "Norris", 42)
print(t)
t = ("Chuck", "Norris", 42)
# get value of a tuple element
print(t[0])
# no assignment possible
t[0] = "Peter"
# tuple has to be unpacked first
t = ("Chuck", "Norris", 42)
firstname, lastname, answer = t
print(firstname)
print(lastname)
print(answer)
Unordered list of key - value pairs
The key has to be unique
d = {"cat": 5, "dog": 6, "bird": 12}
print(d)
print(d["cat"]) # get value for key "cat"
d["cat"] = 42 # set value for key "cat"
print(d)
# sorting dictionary by key
d = {"cat": 5, "dog": 6, "bird": 12}
print(d)
print(sorted(d))
more dictionary information can be found at python documentation
# for loop over list elements
my_list = ["a", "b", "c"]
for character in my_list:
print(character)
for name in ["Chuck Norris", "Arnold Schwarzenegger", "Bruce Willis"]:
print(name)
# for loop over a range of integers
for i in range(10):
print(i)
# for loop over characters in a string
for c in "Hello World":
print(c)
# while loop - looping until a clause is fulfilled
a = 0
while a < 10:
print(a)
a += 1
# cast int to float
my_float = float(10)
print(my_float)
print(type(my_float))
# cast int to string
my_string = str(10)
print(my_string)
print(type(my_string))
# cast float to int
my_int = int(10.0)
print(my_int)
print(type(my_int))
Define a function
# example function
def add(val1, val2): # head
return val1 + val2 # body
print(add(1, 2)) # function call
# function with no return value
def do_something(my_value):
"""
This is a docstring of do_something
It adds 15 to my_value and prints the result
"""
result = add(my_value, 15)
print(result)
do_something(1)
# you can call the explanation of the function
print(do_something.__doc__)
# example class
class Car:
"""
A class for cars
"""
def __init__(self, manifacturer, doors): # constructor of the class
self.manifacturer = manifacturer # set the class member manifacturer
self.doors = doors
def print_doors(self):
print(self.doors)
def get_values(self):
return self.manifacturer, self.doors
# create an instance of the class
my_car = Car("Audi", 4)
print(my_car.manifacturer)
my_car.print_doors()
# read a file
filename = "file.txt"
# open the file in read only mode
fin = open(filename)
# read the complete file
text = fin.read()
print(text)
print(type(text))
# close the file
fin.close()
filename = "file.txt"
fin = open(filename)
# get all lines of the file
lines = fin.readlines()
print(lines)
print(type(lines))
# you can also use the scope variant
with open("file.txt") as fin: # opens the file
text = fin.read()
# the file is opend to this point
# here it is closed
print(text)
# write to a file
fout = open("writefile.txt", "w") # the "w" argument opens the file in "write" mode
fout.write("test") # due to the write mode - the file will be overwritten
fout.close()
with open("writefile.txt") as f:
print(f.read())
print()
with open("writefile.txt", "a") as f: # the "a" argument opens the file in "append" mode
f.write("\nanother line")
with open("writefile.txt") as f:
print(f.read())
Modules bundle python code together to enable easy access for other scipts
import
provides the content of a module
Standard Python libraries and other external libraries can be imported
import sys # import of the module sys
sys.argv[0] # gives the first command line argument
# an element of the module can also be imported
from sys import argv
argv[0]
# some standard modules
import math # math functions
print(math.log(16,2)) # gives the binary logarithm of 10
print(math.pi)
import random # functions to generate random values
print(random.randrange(100)) # gives a random number in the range 0-99
import os # system functions
print(os.listdir(".")) # print a list of the files of the current directory
Numpy is a scientific library for python
It provides powerful functions to work with linear algebra such as arrays, vectors and matrices
import numpy as np # import numpy with an alias
matrix = np.matrix([[1,2],[1,2]]) # create a 2x2 matrix
print(matrix)
my_array = np.array([1,2,3]) # create an array / vector
print(my_array)
my_range = np.arange(15) # create an numpy array containing values from 0-14
print(my_range)
# reshape the range to a matrix
my_matrix = my_range.reshape(3,5) # reshape into matrix with 3 rows and 5 columns
print(my_matrix)
# create a matrix with only 0 values
zero_matrix = np.zeros((3,4)) # 3x4 matrix
print(zero_matrix)
# create a matrix with only 1 values
one_matrix = np.ones((3,4)) # 3x4 matrix
print(one_matrix)
# get the shape of a matrix
print(one_matrix.shape)
# get the size of a matrix
print(one_matrix.size)
# addition
a = np.arange(4)
b = np.arange(4)
print(a)
print(b)
c = a + b # add b to a
print(c)
# subtraction
a = np.array([20,30,40,50])
b = np.arange(4)
print(a)
print(b)
c = a-b # subtract b from a
print(c)
# multiplication
a = np.arange(4)
print(a)
c = a * 2
print(c)
# exponentiation
b = np.arange(4)
print(b)
c = b**2
print(c)
# division
a = np.arange(4)
print(a)
c = a / 2
print(c)
a = np.arange(10)**3
print(a)
print(a[2]) # get the element at index 2
print(a[2:5]) # get the elements from index 2 to intex 4
print(a[: : -1]) # reverse a
# multidimensional arrays
a = np.arange(20).reshape(5,4)
print(a)
print()
print(a[:, 1]) # get for each row element at index 1 - namely get the second column
#### a = np.arange(20).reshape(5,4)
print(a)
print()
first,second = np.hsplit(a,2) # horizontal split into 2 arrays
print(first)
print(second)
#print(a,b,c,d)
#print(b)
help()
calls the python help system
example: help(min)
shows what the function min()
does as long as the function has a docstring
# Python2 print
#print "Hello World"
# Python3 print
print("Hello World")
How to install Python3 with Anaconda on Windows
How to install Python3 with Anaconda on Ubuntu
For Linux user it is more easy (eg. Ubuntu with pip):
sudo apt install python3
Follow the instructions here
Follow the instructions on this tutorial
execute python script:
python3 scriptname.py
with arguments:
python3 scriptname.py param1 param2