from IPython.core.display import HTML
HTML(open("custom.html", "r").read())
n = int(input("please enter n: "))
i = 0
acc = 0
for x in range(n):
i = i + 1
acc = acc + i
print("the sum is", acc)
We learned that variables can be conceived of being names for cells in your computers memory. There are a few rules for valid variable names in Python:
a
to z
, A
to Z
or an under score _
. a
to z
, A
to Z
, digits form 0
to 9
and under scores _
.This means: you must not use umlauts or special characters in a variable name !
Some examples for valid variable names: i
, j0
, my_name
, _my_name
, _
, HiYou
, __0
, this_is_a_long_name
and ThisIsALongName
.
The case of the characters of a variable name matter !, so SPAM
is a different variable than sPaM
, spam
or sPAM
...
You must not use built in statements as variable names. For example for
is not allowed:
for = 3
In order to communicate with the user we used above
x = int(input("please give me a number and press the return key: "))
This is what happens if the Python interpreter executes the previous line:
"
is displayed, x
.We explain later why we write the input statement this way (especially what the int
is good for).
The so called print function
is used for showing values. You can separate text and variables to print with commas ,
.
Now we complete the previous example:
x = int(input("please enter a number: "))
print("you gave me", x, "and the square of this value is", x * x)
It is important that you provide text for input and output delimited with "
. The text between those marks is called string (as a "string of pearls", here: string of single characters). The Python interpreter needs those delimiters to distinguish Python commands from the plain text.
To warm up with Python we translate the salary calculation example from the last session to Python:
hours = float(input("number of hours worked:"))
salary_per_hour = float(input("salary per hour:"))
if hours <= 40:
salary = hours * salary_per_hour
else:
salary_40 = 40 * salary_per_hour
over_hours = hours - 40
over_hours_salary = 2 * over_hours * salary_per_hour
salary = salary_40 + over_hours_salary
print("the calculated salary is", salary)
Enter the program above in PyCharm or at https://repl.it/languages/python3 and run it for different input values. DO NOT USE COPY AND PASTE. Be accurate, typing errors will result in error messages if you run the program.
In Python standard algebraic operations addition, subtraction, multiplication and division are written as +
, -
, *
and /
. For computing powers we use **
. So $2^{20}$ is written as
print(2 ** 20)
Further the order of evaluation for such operations is as we know from mathematics: *
and /
have higher precedence than +
and -
, but we can use parenthesis to change evaluation order:
x = 2 * (3 + 7)
print(x)
In contrast to math as we know it we always have to provide a *
. In math we can write $2 ( x + 3)$ which is not valid in Python:
x = 3
y = 2 (x + 3)
Above you see an example for an error messages in Python. Understanding the full output of this message is beyond this course, but you should recognize which line causes the problem.
The correct version works:
y = 2 * (x + 3)
print(y)
So called integer division in Python is expressed with //
, it rounds the division result down to the next integer number:
print(13 / 3, 13 // 3)
print(-13 / 3, -13 // 3)
The division remainder is the "left over" if we divide two integer numbers. For example the division reminder of 7 / 2
is 1
and the remainder of 7 / 5
is 2
.
To compute the division remainder Python programmers use %
. So to compute the remainder of 20 / 3
we write
print(20 % 3)
We use this later to detect if a given number is even or odd. n % 2
is 0
for even number and 1
for odd numbers.
In general this can be used to detect if a number is a multiple of another number. For example 200
is a multiple of 8
because the remainder is zero:
print(200 % 8)
Further we can use scientific notation: the expression 1.2e3
is the same as $1.2 \times 10^3$ which is 1200
. Or 3.4e-3
is $3.4 \times 10^{-3}$ which equals 0.0034
.
So to express $\frac{2.21 \times 10^{17}}{1.1 \times 10^{-3}}$ we can write
print(2.21e17 / 1.1e-3)
Repeat the examples above in PyCharm or at https://repl.it/languages/python3
If you put a grain of rice to the first field of a chess board and double the number of grains from field to field (so you put 1, 2, 4, 8, ... $2^{63}$ grains to the field), you have $2^{64} - 1$ grains in total. Assume a grain of rice has a weight of $25$ mg, which is $25 \times 10^{-3}$ g. What is the overall weight of the rice on the check-board in tons ? How many percent is this in relation to the weight of the earth which has $5.972 \times 10^{21}$ tons ? Use Python to compute this !
Python ships with so called $modules$ which extend the capabilities of Python.
So for example to compute mathematical functions as $\sin$ you have to use such a module. Before you can access such functions you have to "import" the module first.
Another name for "module" is "library".
To compute the $\sin$ function you first must instruct
import math
You have to include this statement in every script which wants to use functions from this module. It is not that you run this command once and then math
is available on your computer forever.
After this import math
, the "content" of this module can be accessed as attributes of the module, which means you write math.
followed by the function of interest:
print(math.sin(2.0))
You see terms like x.y
often in Python and we say y
is an attribute of x
.
Some of the attributes of the math
module are plain numbers, for example:
print(math.pi, math.e)
So to compute $\cos(\pi)$ you can write
print(math.cos(math.pi))
And to compute $\log e$
print(math.log(math.e))
math.sqrt
computes the square root of a given number. Use the Pythagorean theorem to compute the length of the hypotenuse of right triangle with catheti having lengths 1.0
and 2.0
.We know that $\sin(\pi)$ is zero. But Python tells a different number:
print(math.sin(math.pi))
Don't panic, your computer is not broken, but this is a consequence of the fact that every computer has limited memory. So real numbers with an infinite number of digits after the decimal point (as $\pi$) have to be truncated at a given point to fit into the computers memory.
So math.pi
does not provide the exact value of $\pi$ but a (quite good) approximation:
print(math.pi)
So if you see such effects, keep in mind that many numerical computations with numbers on a computer only give you an approximate result, but usually this is an approximation with high accuracy.
The value 1.2246467991473532e-16
we've seen above is the same as 0.00000000000000012246467991473532
, so pretty close to 0.0
Final message: if you see strange effects as above or in the following example keep calm, neither Python nor your computer is broken :)
print(.8 - 1)
When we said that you can imagine a variable as a name for a cell in your computers memory we simplified the situation a bit.
If a computer handles data as, every piece of data has a so called type
. So every cell in your computers memory not only holds a value, but also knows the type of the value. Up to now we know two types: So called int
numbers which represent natural numbers (without a decimal point), and float
values which describe real numbers (decimal point allowed).
To find out what the type of a value is we can use the so called type
function:
print(type(3))
print(type(3.0))
The concrete type of a value has three impacts:
0
and 1
values.So a int
can only hold integer values without digits after the decimal point, but a float
can. In contrast an int
is more precise for representing large integer numbers.
For the types we know up to far, point 2 is not obvious, we will can show this more clearly for other types later in the script.
Discussing point 3 is beyond the scope of this course.
Computers not only process numbers but pieces of text (we say "sequences of characters") as well. Some examples are:
To represent this kind of data computers use so called strings. In general a string is a finite sequence of characters.
As every program is a sequence of characters we have to indicate in our programs which characters are instructions and which characters belong to a string. We use "
characters as delimiters for this. So in our example
x = int(input("please enter a number: "))
print("x is", x, "and the square of x is", x * x)
the sections delimited by quotes is data (as a numbers are data), the rest consists of instructions.
Some comments:
""
and ''
represent the empty string." "
is a string with one "space" character.We used strings above but did not process them. To do so, we can store strings in variables and we can use them for computing:
greeting = 'hi'
name = "jo"
formula = greeting + " " + name
print(formula)
Again our variables have types. To check this we execute:
print(type(greeting))
The len
function computes the length of a string:
print(len(" "), len("abc"), len(""))
And as we said above the type defines the kind of data as well as how to operate on the data. So for int
and float
values the +
means addition as we know it, but for str
values the +
(as we did see above) means concatenation !
Take care to distinguish strings which look like numbers and actual numbers. The string "123"
looks like the number 123
but is a sequence of three characters. You see the difference below:
print("123" + "456", 123 + 456)
x = "1" + 1
? Does y = "1" * "2"
work ? You can use the #
symbol to mark comments in Python code, the #
and the rest of the line after this marker will be ignored by Python:
# this is a full line comment
x = 1 # and this is a comment at the end of the line
For multi line comments you can use """
or '''
as delimiters:
"""
this is the first line of a multi line comment
and this is the second line. In a real program we might says something about x:
"""
x = 1
Mathematical functions transform values. A function has an argument and "computes something". So $\sin x$ takes an argument $x$ and computes a new value.
In Python and other programming languages functions are more general: some of them accept an arbitrary number of arguments, may "perform some action" and finally compute something.
An example for a mathematical functions we did see above was math.sin
.
type
is a function as well, it takes a value and returns a description of the type of the value:
print(type(1))
We say: we call the function type
with the argument 1
.
The print
function accepts an arbitrary number of arguments of different types:
print(1, 2, 3)
print("1 + 2 is", 1 + 2)
Another Python function is input
: the argument of input
is a string, and when this function is called
name = input("your name ? ")
print("name is", name, "and the type of name is", type(name))
If we call a function as math.cos(0)
Python computes the return value which is 1.0
and replaces the full term math.cos(0)
with this value. So
x = math.cos(0)
is "transformed" to
x = 1.0
And
print("cos(0) is ", math.cos(0))
is transformed to
print("cos(0) is ", 1.0)
This works for nested calls in the same way, we always evaluate from the inside to the outside:
Because of $sin(0) = 0$
x = math.cos(math.sin(0)) * 2
is first transformed to
x = math.cos(0) * 2
and then to
x = 1.0 * 2
Two other functions we did see in the examples above are int
and float
.
=== Before you read on look above where and how we used them !!! ===
The argument of the int
function is a string of digits and the return value is the according natural number:
one_two_three = "123"
print(one_two_three, type(one_two_three))
x = int(one_two_three)
print(x, type(x))
print("123" + "456")
print(int("123") + int("456"))
print(int("123") + int("456"))
is a nested function call again:
int("123")
and ìnt("456")
are evaluated and return integers 123
and 456
.123 + 456
is computed which is 579
.print
with the argument 579
which displays this valueThe float
function works like int
but for real numbers:
approx_pi = float("3.141")
print(approx_pi, type(approx_pi))
This is why we used
hours = float(input("number of hours worked: "))
Here the call of input
returns the string "12.5"
, so the previous example is "transformed" to
hours = float("12.5")
which results in
hours = 12.5
int("one")
or float("pi")
?This script includes so called "repetition exercises". Most exercises before asked you to repeat or modify Python code, here the goal is to consolidate your programming knowledge by solving a problem starting with a blank Python script.
You can find the solution (or a very similar solution) of such an repetition exercise in the preceding examples or in the homework solution proposals, but the idea is to look up the solution only if you need more than 15 minutes.
If you have to look up the solution:
The more you automate basic programming procedures the easier it gets to solve larger problems.
These exercises are also called Code Katas which exist on different skill levels. The name is based on Kata from martial arts.
n
and then computes and displays the sum of the first n
natural numbers.