Python - Getting Started

TensorFlow's best API is a Python-API. So I wanted to learn Python.

A good Python introduction tutorial is available at the Python documentation page.

A perhaps even more compact introduction to Python+NumPy with the goal to be able to work with TensorFlow is Justin Johnson's Python Numpy Tutorial.

Below you can find a short Python script I wrote to work myself into the syntax of Python.


What I learned while working into Python

Among others, I learned while writing this script ...


Python example script

# Small python script to be started with:
#   python3 python_intro.py
#
# Meant as a fast introduction to Python
# for students with prior knowledge of programming
#
# By Prof. Dr. Juergen Brauer, www.juergenbrauer.org

# Comments in python are written by the '#' symbol

# Python is a language that is normally interpreted
# and not pre-compiled. So the following instructions
# will be translated to machine instructions line by line.

# clear screen
import os
os.system('cls' if os.name == 'nt' else 'clear')

print("\n")
print("-----------------------------------------")
print("small python introduction script started.")
print("-----------------------------------------")
print("\n")

# 1. Python determines the type of a variable during runtime
#    (dynamic typing)
#    in contrast to C and C++ which determine the type of a
#    variable during compile time (static typing)
#    For a list of Pyhton's built in types see
#    https://en.wikipedia.org/wiki/Python_(programming_language)#Typing 
print("\n1. Python is dynamically typed:")
a = 2
b = 3.1
c = 'd'
d = "a string"
e = [1,22,333]
f = (4,55,666)
print("data type of a is : ", type(a))
print("data type of b is : ", type(b))
print("data type of c is : ", type(c))
print("data type of d is : ", type(d))
print("data type of e is : ", type(e))
print("data type of f is : ", type(f))



# 2. Some operations (with the variables)
print("\n2. Python operations are quite handy!")

# result of a division
g = 13/2
print("13/2 =",g) # in Python2 the result will be an int with value 6,
         # in Python3 the result will be an float with value 6.5
print("data type of g is : ", type(g))

# concatenating strings
d2 = d + " is " + d + " of characters"
print("d2 =",d2)

# accessing list and tuple elements
print("2nd element of", type(e), "e is :", e[1])
print("3rd element of", type(f), "f is :", f[2])



# 3. User console input
print("\n3. User console input")
input_as_str = input("Enter a number: ")
print("You entered : ", input_as_str, " which has data type ", type(input_as_str))

input_as_int = int(input("Enter a number: "),10)
print("You entered : ", input_as_int, " which has data type ", type(input_as_int))



# 4. if statement in Python
print("\n4. if statement")
i = input_as_int
if i == 0:
	print("Your number is zero")
elif i < 0:
	print("Your number is negative")
else:
	print("Your number is positive")



# 5. Iterating over list elements
print("\n5. Iterating over list elements")
l = [1,22.2,333,4444,55555,'hello world']
nr = 0
for k in l:        
	print("element #",nr,"of list l is ", k, "and has type", type(k) )
	nr=nr+1



# 6. Counting for-loops
print("\n6. Counting for-loops")
for i in range(5):
	print("i=",i)
for j in range(15,20):
	print("j=",j)
for k in range(0,50,5):
	print("k=",k)



# 7. A loop can have an else branch!
#    that will be executed if the loop has finished
print("\n7. A loop can have an else branch!")
for i in range(1,10):
	print("i=",i)
else:
	print("Loop over i finished!")

for j in range(1,10):
	print("j=",j)
	if j % 5 == 0:
		break
else:
	print("Loop over j finished!")



# 8. Example of a while loop
print("\n8. Example of a while loop")
k = 1
while (k<10) and (k%5!=0):	
	print("k=",k)
	k=k+1



# 9. Example of a function definition
print("\n9. Example of a function definition")

def foo1(x):
	result = x*x
	return result

def foo2(x):
	result = 2*x
	return result

print("foo1(3)=",foo1(3))
print("foo2(3)=",foo2(3))



# 10. Example of a class definition & creating objects
print("\n10. Example of a class definition & creating objects")

# the following is already a class definition!
# note, that compared to C++, we do not need to declare the members
# due to the dynamic typing property of Python

class vehicle:
	def __init__(self, name, max_speed, nr_wheels):
		self.name      = name
		self.max_speed = max_speed
		self.nr_wheels = nr_wheels

		# new car, no miles driven so far...
		self.mileage = 0

	def drive_with_max_speed(self, time_to_drive_in_hours):		
		self.mileage = self.mileage + time_to_drive_in_hours * self.max_speed
		print("new mileage of", self.name, "is", self.mileage)

# now let's create two objects of the vehicle class:
v1 = vehicle("old car",    110,4)
v2 = vehicle("sports car", 190,6)

v1.drive_with_max_speed(1)
v2.drive_with_max_speed(1)

v1.drive_with_max_speed(1)
v2.drive_with_max_speed(1)

# 11. Example of derived classes
print("\n11. Example of derived classes")

class motorbike(vehicle):

	def __init__(self, max_speed):
		vehicle.__init__(self, "motorbike", max_speed, 2)

class truck(vehicle):

	def __init__(self):
		vehicle.__init__(self, "truck", 95, 6)


v3 = motorbike(250)
v4 = truck()
v3.drive_with_max_speed(1)
v4.drive_with_max_speed(1)
v3.drive_with_max_speed(1)
v4.drive_with_max_speed(1)



print("\n")
print("------------------------------------------")
print("small python introduction script finished.")
print("------------------------------------------")
print("\n")
		

Output generated by the script

-----------------------------------------
small python introduction script started.
-----------------------------------------


1. Python is dynamically typed:
data type of a is :  <class 'int'>
data type of b is :  <class 'float'>
data type of c is :  <class 'str'>
data type of d is :  <class 'str'>
data type of e is :  <class 'list'>
data type of f is :  <class 'tuple'>

2. Python operations are quite handy!
13/2 = 6.5
data type of g is :  <class 'float'>
d2 = a string is a string of characters
2nd element of <class 'list'> e is : 22
3rd element of <class 'tuple'> f is : 666

3. User console input
Enter a number: -23
You entered :  -23  which has data type  <class 'str'>
Enter a number: -23
You entered :  -23  which has data type  <class 'int'>

4. if statement
Your number is negative

5. Iterating over list elements
element # 0 of list l is  1 and has type <class 'int'>
element # 1 of list l is  22.2 and has type <class 'float'>
element # 2 of list l is  333 and has type <class 'int'>
element # 3 of list l is  4444 and has type <class 'int'>
element # 4 of list l is  55555 and has type <class 'int'>
element # 5 of list l is  hello world and has type <class 'str'>

6. Counting for-loops
i= 0
i= 1
i= 2
i= 3
i= 4
j= 15
j= 16
j= 17
j= 18
j= 19
k= 0
k= 5
k= 10
k= 15
k= 20
k= 25
k= 30
k= 35
k= 40
k= 45

7. A loop can have an else branch!
i= 1
i= 2
i= 3
i= 4
i= 5
i= 6
i= 7
i= 8
i= 9
Loop over i finished!
j= 1
j= 2
j= 3
j= 4
j= 5

8. Example of a while loop
k= 1
k= 2
k= 3
k= 4

9. Example of a function definition
foo1(3)= 9
foo2(3)= 6

10. Example of a class definition & creating objects
new mileage of old car is 110
new mileage of sports car is 190
new mileage of old car is 220
new mileage of sports car is 380

11. Example of derived classes
new mileage of motorbike is 250
new mileage of truck is 95
new mileage of motorbike is 500
new mileage of truck is 190


------------------------------------------
small python introduction script finished.
------------------------------------------
	

Dictionaries

Dictionaries are associative containers in Python, i.e. key-value pairs, which allow to retrieve a value using a key:
		my_dic1 = { "car":"Auto", "bike":"Fahrrad", 911:112 }

		print (my_dic1.keys())
		print (my_dic1.values())

		print ("The word for 'car' is in German '", my_dic1["car"], "'")

		print ("Instead of 911 in the US you better call", my_dic1[911], "in Germany.")

		print ("There are ", len(my_dic1), " key-value pairs stored in the dictionary.")
	
Output generated by this script:

dict_keys(['bike', 'car', 911])
dict_values(['Fahrrad', 'Auto', 112])
The word for 'car' is in German ' Auto '
Instead of 911 in the US you better call 112 in Germany.
There are  3  key-value pairs stored in the dictionary.
	

The with statement

The best explanation for the with-statement in Python I found is by Jeff Knupp. Here is an example code snippet that shows that the with-statement will automatically call the __enter__ and __exit__ "method" for a class used in the with-statement:
    class A():

    def __init__(self, param1, param2):
        print("init()")
        self.param1 = param1
        self.param2 = param2
        

    def __enter__(self):
        print("enter()")
        return self
		

    def __exit__(self, *args):		
        print("exit()")
        
        
    def foo(self):
        print("foo()")
	
    print(">before with-statement")
        
    with A(10,20) as obj:
        print(">within with-statement")
        obj.foo()
        #f = open('foo2.txt','r')
        print(">at end of with-statement")
        
    print(">after with-statement")
    
Output generated by this script:

>before with-statement
init()
enter()
>within with-statement
foo()
>at end of with-statement
exit()
>after with-statement
    
Now observe what happens if you activate the line
f = open('foo2.txt','r')
It will cause an error if the file foo2.txt does not exist. However, the output generated by this script shows, that even an error occured, the exit() function was called, which allows to return resources allocated by the object instance of class A!
    
>before with-statement
init()
enter()
>within with-statement
foo()
exit()
Traceback (most recent call last):
  File "with_statement.py", line 26, in 
    f = open('foo2.txt','r')
FileNotFoundError: [Errno 2] No such file or directory: 'foo2.txt'