unit_4_prog_1
unit_4_prog_1
1 / 47
Outline
1. Programming tools
2. Requirements
3. Variables
4. Integers and Floats
5. Strings
6. Casting, Printing, Commenting, None-Keyword
7. Boolean variables and operators
8. Conditions (if-Statements)
9. Exercise
2 / 47
Programming tools
3 / 47
How does “text” become an executable program?
4 / 47
Compiler
5 / 47
Interpreter
Similar to the compiler
The program gets executed using computer instructions, but:
Each command (e.g. print(“Hi”)) gets translated on its execution
No additional binary file (executable) is created
Source code gets translated on each execution
This process is called “interpretation”
Compilers can lead to drastic performance advantages
6 / 47
Basic terms in programming languages
Programming language
Formal language with fixed rules
Syntax
Fix rules on how to write in a programming language
Fix rules for all language elements
Semantics
Meaning of the language elements
What is exectued?
Program logic, program flow, program structure
Execution sequence and interplay between different program parts
7 / 47
Requirements
8 / 47
Requirements
9 / 47
Python (www.python.org)
10 / 47
Jupyter (www.jupyter.org)
11 / 47
Python3
12 / 47
Variables
13 / 47
Variables
number = 123
message = 'Hello World!'
number2 = number
14 / 47
Variables
15 / 47
Variables and data types
Data type Function Examples
int Natural numbers x = 3
float Floating point numbers x = 3.0
bool Booleans x = True
x = False
str Strings x = 'Test'
x = "Test"
tuple Tuples x = (1, 2, 3)
list Lists x = [1, 2, 3]
dict Dictionaries x = {1: 'blue', 2:
'red'}
io.TextIOWrappe Files x = open('readme.txt')
r
... ... ...
16 / 47
Integers and Floats
17 / 47
Integers and floating point numbers
Integers:
1, -13, 15, -42, 12345, ...
Floats:
1.3, 3.14159, -42.123, …
Arithemtic operations:
Adding (+), Subtracting (-), Multiplying (*), Dividing (/)
Exponantiating (**)
Modulo Operator (%)
number = 5 + 13
number_2 = number + 5
18 / 47
Extended operators
number = 42 number = 42
number += 8 # => 50 number = number + 8
number -= 10 # => 40 number = number - 10
number /= 4 # => 10 number = number / 4
number *= 2 # => 20 number = number * 2
19 / 47
Some special cases
20 / 47
Strings
21 / 47
Strings
22 / 47
Strings
Accessing
Individual characters: [] and an index (0-based!)
First character = index 0
Last character = length of the string – 1
Multiple characters with slicing: [], : and indices
Length: len(string)
23 / 47
String slicing
Slicing
Retreive the i-th character:
string[i]
Retrieve a substring with characters from start (inxlusive) until end (exclusive):
string[start:end]
Retrieve a substring with characters from start (inxlusive) until end (exclusive)
in steps of the given size:
string[start:end:stepsize]
24 / 47
String slicing
Advanced slicing
Retreive the i-th last character:
string[-i]
Retrieve everything from the i-th last character (inclusive):
string[-i:]
Retrieve everything until the i-th last character (exclusive):
string[:-i]
Reversed string:
string[::-1]
25 / 47
String slicing: example
text = 'Vienna'
text[0] 'V'
text[:2] 'Vi'
text[0:2]
text[6] IndexError
text[5] 'a'
text[-1]
text[2:] 'enna'
text[2:6]
text[::2] 'Ven'
text[::-1] 'anneiV'
26 / 47
String methods
Notebook examples
27 / 47
Casting, Printing, Commenting,
None-Keyword
28 / 47
Conversion between data types
num1 = 123
Casting: converting between data types num2 = '15'
num3 = num1 + num2
int(), str(), float(),
bool()… Output:
Examples: TypeError
int('5') 1 num1 = 123
=> 5
2 num2 = '15'
float('5.23') => 5.23 --> 3 num3 = num1 + num2
str(5) => '5' TypeError: unsupported
int(True) => 1 operand type(s) for +:
'int' and 'str'
bool(0) =>
False Solution:
num1 = 123
num2 = '15'
num3 = num1 + int(num2)
29 / 47
Formatting output
print() function
Prints also a new line at the end
Parameters separated with ,
Space character as a whitespace
We can also print and format variables
f before the string to print
Variables in brackets {}
name = 'Max'
age = 20
print(f'My name is {name} and I am {age} years old')
30 / 47
Formatting output
Sequence Result
\n New line
\t Tabulator
\' ' character in strings
\" " character in strings
\\ \ character (backslash)
31 / 47
Comments
Syntax
# single-line comment
""" multi line
comment """
''' multi line
documentation '''
Explanations to program flow and structure
Supports understanding of the program
Useful for group projects, longer lasting projects, etc.
32 / 47
None-Keyword
None
No value, Null value
Placeholder when the variable value is still not assigned
x = None is different than:
0
False
''
Notebook examples
33 / 47
Boolean variables and operators
34 / 47
Boolean variables
35 / 47
Comparison operators
36 / 47
Logical operators
37 / 47
Operator precedence
Operator precedence If not sure: ()
(from low to high)
Notebook examples
or
and
not
in, not in, is, is not, <, <=, >, >=, !=, ==
|
^
&
<<, >>
+, -
*, @, /, //, %
+x, -x, ~x
**
38 / 47
Conditions (if-Statements)
39 / 47
Branching: if statements
if condition: if x > 2:
print('Do something') print('In if')
print('Not in if')
Indented 4 spaces
40 / 47
Branching: if-else statements
if condition:
print('Do something')
else:
print('Do something else')
if x > 2:
print('In if')
else:
print('In else')
41 / 47
Branching: if-elif-else statements
42 / 47
Branching: if-elif-else statements
Syntax:
if condition:
print('Do something')
elif condition2:
print('Do something else')
elif condition3:
print('Do something different')
# there could be more elifs below this
else: # optional
print('Do something completely different')
43 / 47
Branching: if-elif-else statements
Examples:
if x < 5: if x < 5:
print('Small') print('Small')
elif x < 15: if x < 15:
print('Medium') print('Medium')
elif x < 20:
print('Big') ≠ if x < 20:
print('Big')
else: else:
print('Huge') print('Huge')
44 / 47
Indentation rules
45 / 47
Nested indentation
Code blocks can be arbitrarly nested at multiple levels
age_max = 35
age_peter = 42
age_berta = 37
Notebook examples
46 / 47
Exercise
47 / 47
Student task
Task 1: Install python3 and jupyter lab. You can follow these installation instructions.
After installation is complete start the jupyter lab and implement following tasks in
separate cells:
1. Initialize variables radius and side with positive values. Compute the area of a
circle with a given radius and the area of a square with a given side. Compute the
difference of the larger area to the smaller area of the two.
2. Initialize an integer variable x. Write a code to decide wheather x is divisible by
both 2 and 3, by either only 2 or 3, or by neither 2 nor 3.
3. The volume of a sphere with radius r is . Write a cell to compute the volume of a
sphere. What is the volume of a sphere with radius 5?
4. Suppose the cover price of a book is €24.95, but bookstores get a 40% discount.
Shipping costs €3 for the first copy and €0.75 for each additional copy. What is the
total wholesale cost for 60 copies? Write a cell to compute this cost.
48 / 47