Python Basics I

Image source: https://indianpythonista.wordpress.com/2018/01/04/how-python-runs/

Hello world!

The obligatory “Hello world!” program. As you can see, it is very short in Python:

print("Hello world!")
Hello world!

The string "Hello world!" is passed to the method print() which prints the given argument to the output stream. This is normally the console. In this case, however, the output stream is redirected to this browser window (below the cell).

Task

  1. Start the interactive python shell
  2. Print your name to the console

Solution

  1. print("My Name")
    

Comments

# This is a comment and it is not interpreted by the compiler.
print("Hello world!") # This line of code prints the string "Hello world!". The part behind the hastag is a comment
Hello world!

Variables & datatypes

In the following snippet, the string "Hello world!" is assigned to the variable x (using =). This means, that the string object "Hello world!" is stored in the PC’s working memory and that the variable x points to this string object. x is then printed.

x = "Hello world!"
print(x)
Hello world!

Variables can also point to numbers:

x = 42
print(x)
42

In Python, there are basically 2 types of numbers: Integers (3,4,5,…) and floats (3.1415, 7.904532, …):

x = 3.1415
print(type(x)) # The function "type()" returns the datatype of the variable that was passed to it
print(x)
<class 'float'>
3.1415

Floats can also be written in scientific notation:

x = 4.08E+10
print(x)
40800000000.0

Python automatically converts between these types, if necessary, so you don’t have to worry too much about it (for now). The differences between these datatypes will be explained in later sections. Important to know, is that integers generally take much less memory space than floats (which gets critical as soon as we work with big data (satellite data))

Variable assignments can be done “simultaneously” on more than one variable :

x, y, z = 1, 4.78, "Geographie"
print(x,y,z)      # The function "print()" accepts multiple arguments and prints them out separated by a " " (blank space)
1 4.78 Geographie

Variables can also be assigned to each other. When one variable is assigned to another variable, that means that it points to the same space in memory.

x = 42 # x points to the object 42 in memory
y = 10 # y points to the object 10 in memory

x = y  # x now also points to the object 10 in memory
print(x, y)
10 10

When one variable is changed, other variables are not affected:

x = 42 # x points to the object 42 in memory
y = 10 # y points to the object 10 in memory

x = y  # x now also points to the object 10 in memory
y = 99 # y now points to the object 99 in memory, x is not affected
print(x, y)
10 99

Another simple datatype is the boolean datatype. It can only store two values: True and False. It is used reasonably, when a variable can only take two states, e.g. to model the state of a light switch (on and off).

x = True
print(x)
True

Also important is the None value of the built-in NoneType:

x = None
print(x)
None

This value is frequently used to represent the absence of a value, e.g. missing data points.

Naming conventions: Variable names can consist of more than just one character. The following rules apply:

  • They must begin with a letter (a - z, A - Z) or underscore (_)
  • Other characters can be letters, numbers or an underscore
  • They are case sensitive
  • You cannot use some reserved words as a variable name because Python uses them for other things (e.g. def, str, print, …)
  • Words are normally separated by an underscore
first_name = "Marie"
last_name = "Curie"

print(first_name,last_name)
Marie Curie

Now you know the basic datatypes of Python (string, int, float, bool). There are more complex datatypes which will be covered later.

Task

  1. Create two variables called Vorname and Nachname and assign your first/last name to them as strings.
  2. Create another variable called Lieblingszahl and assign it your favourite number.
  3. Print all three variables in one call.

Solution

  1. Vorname = "Peter"
    Nachname = "Zwegat"
    
  2. Lieblingszahl = 42
    
  3. print(Vorname, Nachname, Lieblingszahl)
    

Operators

Arithmetic operators

Most statements (logical lines) that you write will contain expressions. A simple example of an expression is 5 + 9. An expression can be broken down into operators and operands.

In Python, you can use four basic arithmetic operators: +, -, * and /. There are many more operators, which will be covered later.

Operators perform a specific computation. They require data to operate on. Such data is called operands, in this case, 5 and 9 are the operands.

5 + 9 # This is an expression. It's return value is the result of the expression (=14 in this case)
14

You can also use + between strings, which just appends the first to the second:

a = "Py"
b = "thon"

a+b
'Python'

However, if you mix strings and numbers using the + operator, be careful:

a+b+3

    ---------------------------------------------------------------------------

    TypeError                                 Traceback (most recent call last)

    <ipython-input-3-1760fa2bf485> in <module>()
    ----> 1 a+b+3
    

    TypeError: can only concatenate str (not "int") to str


If you want to concatenate strings and numbers, you have to convert the numbers to strings using the str() method:

a+b+str(3)
'Python3'

Normally expressions are assigned to variables:

meine_lieblingszahl = 9 - 5 + 4 - 10 * 4 / 8 + 39
meine_lieblingszahl
42.0

You can also use brackets:

x = (4 + 5) * 2
print(x)

x = 4 + 5 * 2
print(x)
18
14

Of course, you can also use variables within expressions:

a = 4
b = 3
y = a * (b + 12)
print(y)
60

And you can use one variable on the left- and righthand side of an expression. The right side gets evaluated (as always) and the result is written to the variable on the left side (as always):

x = 10
x = x + 5
print(x)
15

Task

  1. Print the variables from above (Vorname, Nachname, Lieblingszahl) in the following manner:

Die Lieblingszahl von Benjamin Rösner ist 42.

  1. Let Python calculate the sum of 44 and 124 and divide the result by 76 (all in one line). What is your result?
  2. Let Python calculate the product of 0.3 and 3. Is the result what you expected?

Solution

  1. print("Die Lieblingszahl von " + Vorname + " " + Nachname + " ist " + str(Lieblingszahl) + "."
    
  2. (44+124)/76
    
  3. 0.3*3
    

The result is not 0.9 because of the floating point number conversion problem between decimal and binary system.

Comparison operators

Another operator is the double ==. It is used to compare two variables and it returns True, if both variables have the same value, otherwise False:

x = 4
y = 3

x == y
False

You can also compare two variables/expressions using the > or < operators (and many more).

x = 10
y = 5

x > y
True

Logical operators

There are also logical operators, like and, or and not. (Again, there are some more operators but we will not cover all of them)

  • and returns True, if the left and right operands both result in True, otherwise False
  • or returns True, if either the left or the right or both operands result in True, otherwise False
  • not returns True, if the right operand results in Flase, otherwise True
sun_is_shining = True
my_friends_are_here = True

i_am_happy = sun_is_shining and my_friends_are_here
print(i_am_happy)

my_friends_are_here = False
i_am_happy = sun_is_shining and my_friends_are_here
print(i_am_happy)
True
False

A good overview over all standard operators in Python is given here.

Task

  1. What is the result of the following expressions? (Try to get the correct results before checking with Python)
    • Python False and False
    • Python True and False
    • Python True or False
    • Python not True
  2. Why does the following code block return False? Python a = 1.8 b = 0.6 + 0.6 + 0.6 a == b

Solution

  1. False
    False
    True
    False
    
  2. The code block returns false because b doesn’t evaluate to 1.8 due to the floating point number conversion problem between decimal and binary system.

Formatted printing

Often, you want to print stuff to the console in a specific format. For example, you are not interested in the 10th decimal of a floating point number when you are calculating with euros and cents. For that, you can use formatted printing:

x = 321.14159265359
y = 0.489

print(x)                       # prints the raw value 321.14159265359

print("{0:6.2f}€".format(x))   # prints x as floating point number with min. 6 digits printed in total and max. 2 digits after the "."
print("{0:6.2f}€".format(y))   # prints x as floating point number with min. 6 digits printed in total and max. 2 digits after the "."

print("{0:10.2f}".format(x))  # prints x as floating point number with min. 10 digits printed in total and max. 2 digits after the ".". Leading zeros are not shown, only blanks.

z = 5678
print("{0:15d}".format(z))    # prints z as integer with min. 15 digits printed in total. Leading zeros are not shown, only blanks.
321.14159265359
321.14€
  0.49€
    321.14
           5678

You can also pass multiple arguments to the format-function. The digit before the : references the index of the argument. Only text within { and } is interpreted:

res = 3000.00
unit = "meters"
gen  = 2
name   = "Meteosat"

print("{3} satellites of generation {2:1d} have a resolution of {0:5.2f} {1}.".format(res,unit,gen,name))
Meteosat satellites of generation 2 have a resolution of 3000.00 meters.

For more information about formatting and its possibilities, have a look at https://pyformat.info/

Input

If the input(prompt)-function is called during a program run, the program sequence is stopped until the user makes an entry via the keyboard and closes it with the Return key. The string of the parameter “prompt” is displayed if it is passed. In this way you can show the user what he is expected to enter.

x = input("What is your name? ")
print("Hello " + x + "!")
What is your name? Benjamin
Hello Benjamin!

Task

  1. Write a script that asks the user to input her/his age.
  2. Ask the user what year it is.
  3. Tell the user how old she/he was in the year 2000.

Solution

  1. age = int(input("Please enter your age: "))
    
  2. year = int(input("What year is it? "))
    
  3. age_in_2000 = age-(year-2000)
    print("In the year 2000 you were {0:01d} years old.".format(age_in_2000))
    

Exercise 1

  • Complete the first assignment and push your results until tuesday 14:00 next week: https://classroom.github.com/a/FtbnHqzA