Math Operators
From highest to lowest precedence:
Operators | Operation | Example |
---|---|---|
** | Exponent | 2 ** 3 = 8 |
% | Modulus/Remainder | 22 % 8 = 6 |
// | Integer division | 22 // 8 = 2 |
/ | Division | 22 / 8 = 2.75 |
* | Multiplication | 3 * 3 = 9 |
- | Subtraction | 5 - 2 = 3 |
+ | Addition | 2 + 2 = 4 |
Examples of expressions:
print(2 + 3 * 16)
print((2 + 3) * 16)
print(2 ** 18)
print(23 // 7)
print(23 % 7)
print((5 - 1) * ((7 + 1) / (3 - 1)))
Augmented Assignment Operators
Operator | Equivalent |
---|---|
var += 1 |
var = var + 1 |
var -= 1 |
var = var - 1 |
var *= 1 |
var = var * 1 |
var /= 1 |
var = var / 1 |
var %= 1 |
var = var % 1 |
Examples:
greeting = 'Hello' greeting += ' world!' print(greeting)
number = 1 number += 1 print(number)
my_list = ['item'] my_list *= 3 print(my_list)
Walrus Operator
The Walrus Operator allows assignment of variables within an expression while returning the value of the variable
Example:
print(my_var:=c"Hello World!") my_var="Yes" print(my_var) print(my_var:="Hello")
The Walrus Operator, or Assignment Expression Operator was firstly introduced in 2018 via PEP 572, and then officially released with Python 3.8 in October 2019.
Data Types
Data Type | Examples |
---|---|
Integers | -2, -1, 0, 1, 2, 3, 4, 5 |
Floating-point numbers | -1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25 |
Strings | 'a', 'aa', 'aaa', 'Hello!', '11 cats' |
Concatenation and Replication
String concatenation:
>>> 'Alice' 'Bob'
# 'AliceBob'
String replication:
>>> 'Alice' * 5
# 'AliceAliceAliceAliceAlice'
Variables
You can name a variable anything as long as it obeys the following rules:
- It can be only one word.
>>> # bad
>>> my variable = 'Hello'
>>> # good
>>> var = 'Hello'
- It can use only letters, numbers, and the underscore (
_
) character.
>>> # bad
>>> %$@variable = 'Hello'
>>> # good
>>> my_var = 'Hello'
>>> # good
>>> my_var_2 = 'Hello'
- It can’t begin with a number.
>>> # this wont work
>>> 23_var = 'hello'
- Variable name starting with an underscore (
_
) are considered as "unuseful".
>>> # _spam should not be used again in the code
>>> _spam = 'Hello'
Comments
Inline comment:
# This is a comment
Multiline comment:
# This is a
# multiline comment
Code with a comment:
a = 1 # initialization
Please note the two spaces in front of the comment.
Function docstring:
def foo():
"""
This is a function docstring
You can also use:
''' Function Docstring '''
"""
The print() Function
The print()
function writes the value of the argument(s) it is given. [...] it handles multiple arguments, floating point-quantities, and strings. Strings are printed without quotes, and a space is inserted between items, so you can format things nicely:
>>> print('Hello world!')
# Hello world!
>>> a = 1
>>> print('Hello world!', a)
# Hello world! 1
The end keyword
The keyword argument end
can be used to avoid the newline after the output, or end the output with a different string:
phrase = ['printed', 'with', 'a', 'dash', 'in', 'between']
>>> for word in phrase:
... print(word, end='-')
...
# printed-with-a-dash-in-between-
The sep keyword
The keyword sep
specify how to separate the objects, if there is more than one:
print('cats', 'dogs', 'mice', sep=',')
# cats,dogs,mice
The input() Function
This function takes the input from the user and converts it into a string:
>>> print('What is your name?') # ask for their name
>>> my_name = input()
>>> print('Hi, {}'.format(my_name))
# What is your name?
# Martha
# Hi, Martha
input()
can also set a default message without using print()
:
>>> my_name = input('What is your name? ') # default message
>>> print('Hi, {}'.format(my_name))
# What is your name? Martha
# Hi, Martha
It is also possible to use formatted strings to avoid using .format:
>>> my_name = input('What is your name? ') # default message
>>> print(f'Hi, {my_name}')
# What is your name? Martha
# Hi, Martha
The len() Function
Evaluates to the integer value of the number of characters in a string, list, dictionary, etc.:
>>> len('hello')
# 5
>>> len(['cat', 3, 'dog'])
# 3
len
, but prefer direct boolean evaluation.
Test of emptiness example:
>>> a = [1, 2, 3]
# bad
>>> if len(a) > 0: # evaluates to True
... print("the list is not empty!")
...
# the list is not empty!
# good
>>> if a: # evaluates to True
... print("the list is not empty!")
...
# the list is not empty!
The str(), int(), and float() Functions
These functions allow you to change the type of variable. For example, you can transform from an integer
or float
to a string
:
>>> str(29)
# '29'
>>> str(-3.14)
# '-3.14'
Or from a string
to an integer
or float
:
>>> int('11')
# 11
>>> float('3.14')
# 3.14
Langversion
Operator | Name | Erklärung | Beispiele |
---|---|---|---|
+ | Plus | Addiert bzw. verkettet die beiden Objekte |
3 + 5 ergibt 8 .
'a' + 'b' ergibt 'ab' .
|
- | Minus | Ergibt entweder eine negative Zahl, oder das Ergebnis einer Subtraktion zweier Zahlen |
-5.2 ergibt eine negative Zahl.
50 - 24 ergibt 26 .
|
* | Multiplikation | Multipliziert zwei Zahlen miteinander oder gibt eine mehrfache Wiederholung eines Strings (einer Sequenz) zurück. |
2 * 3 ergibt 6 .
'la' * 3 ergibt 'lalala' .
|
** | Potenz | Gibt die Potenzierung x hoch y zurück |
3 ** 4 ergibt 81
(d.h. 3 * 3 * 3 * 3 )
|
/ | Division | Dividiere x durch y |
4/3 ergibt 1.3333333333333333 (die Division
von Ganzzahlen ergibt eine Gleitkommazahlzahl -- floating object).
|
// | Ganzzahlige Division | Liefert das Ergebnis der ganzzahligen Division zurück |
4 // 3.0 ergibt 1
|
% | Modulo | Liefert den Rest bei einer ganzzahligen Division zurück |
8%3 ergibt 2 .
-25.5%2.25 ergibt 1.5 .
|
<< | Bitweises Linksschieben | Verschiebt das Bitmuster des linken Operanden um die angegebene Anzahl von Bit-Positionen nach links (jede Zahl wird im Speicher durch Bits, d.h. die Binärzeichen 0 und 1 repräsentiert). |
2 << 2 ergibt
8 .
- 2 wird durch das Bitmuster
10 repräsentiert. Eine Verschiebung um 2 Bits
nach links ergibt 1000 , was wiederum der
Dezimalzahl 8 entspricht.
|
>> | Bitweises Rechtsschieben | Verschiebt das Bitmuster des linken Operanden um die angegebene Anzahl von Bit-Positionen nach rechts. |
11 >> 1 ergibt
5 -
11 wird durch das Bitmuster
1011 repräsentiert. Eine Verschiebung um 1 Bit
nach rechts ergibt 101 , was wiederum der
Dezimalzahl 5 entspricht.
|
& | Bitweises UND | Die Bitmuster der beiden Zahlen werden mit UND verknüpft. |
5 & 3 ergibt
1 .
|
| | Bitweises ODER | Die Bitmuster der beiden Zahlen werden mit ODER verknüpft |
5 | 3 ergibt 7
|
^ | Bitweises XOR | Die Bitmuster der beiden Zahlen werden mit XOR (exklusivem ODER) verknüpft |
5 ^ 3 ergibt 6
|
~ | Bitweises NICHT | Ergibt die bitweise Negation des Operanden. Dies wird auch als das Einerkomplement bezeichnet. Das Einerkomplement einer Zahl x ist gleich -(x+1). |
~5 ergibt -6 .
|
< | Kleiner als |
Das Ergebnis zeigt an, ob x kleiner als y ist.
Alle Vergleichsoperatoren liefern als Rückgabewert 1 für wahr und 0 für falsch.
Diese Werte entsprechen den speziellen logischen Konstanten
True bzw. False .
Beachten Sie die Großschreibung dieser Konstanten.
|
5 < 3 ergibt
0 (d.h. False ) und
3 < 5 ergibt
1 (d.h. True ).
Vergleiche können beliebig hintereinander geschaltet werden:
3 < 5 < 7 ergibt True .
|
> | Größer als | Das Ergebnis zeigt an, ob x größer als y ist |
5 > 3 ist wahr, ergibt also
True . Falls beide Operanden Zahlen sind,
werden sie vor dem Vergleich zuerst in einen gemeinsamen Datentyp
umgewandelt. Andernfalls erhält man immer False .
|
<= | Kleiner gleich | Das Ergebnis zeigt an, ob x kleiner als oder gleich y ist |
x = 3; y = 6; x <= y
ergibt True .
|
>= | Größer gleich | Das Ergebnis zeigt an, ob x größer als oder gleich y ist |
x = 4; y = 3; x >= 3 ergibt True .
|
== | Gleichheit | Prüft die beiden Objekte auf Gleichheit |
x = 2; y = 2; x == y ergibt True .
x = 'str'; y = 'stR'; x == y ergibt False .
x = 'str'; y = 'str'; x == y ergibt True .
|
!= | Ungleichheit | Prüft die beiden Objekte auf Ungleichheit |
x = 2; y = 3; x != y ergibt True .
|
not | Logisches NICHT |
Bewirkt eine Invertierung des Wahrheitswertes: Wenn x True
ist, ist das Ergebnis False . Wenn x False
ist, ist das Ergebnis True .
|
x = True; not x ergibt False .
|
and | Logisches UND |
x and y ergibt x , wenn
x als Wahrheitswert interpretiert gleich False ist.
Andernfalls ist das Ergebnis der Wert von of y .
Das Ergebnis entspricht daher einer logischen UND-Verknüpfung.
|
x = False; y = True; x and y ergibt
False , da x False ist.
In diesem Fall wird der Python-Interpreter die Variable y
gar nicht erst in die Auswertung mit einbeziehen, da der Ausdruck
bereits falsch ist (da x False ist).
Dies wird eine "Kurzschlussauswertung" genannt: Sie liefert das
richtige Ergebnis, ohne dass y ausgewertet werden muss
(bedenken Sie, dass an der Stelle von y auch ein sehr komplizierter
Ausdruck stehen kann, dessen Berechnung lange Zeit in Anspruch nehmen würde oder
zu einem Fehler führen könnte - durch die verkürzte Auswertung wird dies vermieden).
So liefert z.B. 0 and 1/0 den Wert 0 zurück, da die Zahl 0
dem Wahrheitswert False entspricht. Der Ausdruck
1/0 wird in diesem Fall nicht ausgewertet und führt daher
auch nicht zu einer Fehlermeldung.
|
or | Logisches ODER |
x or y ergibt x , wenn
x als Wahrheitswert interpretiert gleich True ist.
Andernfalls ist das Ergebnis der Wert von y .
Das Ergebnis entspricht daher einer logischen ODER-Verknüpfung.
|
x = True; y = False; x or y ergibt True .
Hier wird ebenfalls das Prinzip der Kurzschlussauswertung verwendet.
So liefert z.B. 3 and 1/0 ohne Fehlermeldung den Wert 123
zurück, da die Zahl 3 dem Wahrheitswert True entspricht.
Die Auswertung von 3/4 and 1/0 führt jedoch zu einer Fehlermeldung,
da die Division der Ganzzahlen den Wert 0 ergibt, was logisch gleich False ist.
|
Nächste Kurseinheit: 02 Fallunterscheidungen