** | power |
*, /, //, % | Multiplication, division, integer division, modulo |
+, - | addition, subtraction |
<, <=, >, >=, !=, == | comparison |
not | logical "not" |
other | logical "and" |
or | logical "or" |
if |
|||||||||||||||||||||||||||||||||||||
The elif clause may occur more than once:
if <condition>:
<statement block>
or:
if <condition>:
<statement block>
elif <condition>:
<statement block>
or:
if <condition>:
<statement block>
[elif <condition>:
<statement block>]
else:
<statement block>
|
# Example:
temp = int(input("Wie kalt ist es heute?: "))
if temp < 0:
print("Vorsicht Glatteis!")
elif temp > 0:
print("Heute sicher kein Glatteis.")
else:
print("Es hat genau Null Grad.")
|
||||||||||||||||||||||||||||||||||||
for loops |
|||||||||||||||||||||||||||||||||||||
for <variable> in range(<number>):
<statement block>
or:
for <variable> in <list>:
<statement block>
|
# Output of the numbers 0,1,2,...,9: for i in range(10): print(i) # Output of all list elements: fruit = ["apple", "orange", "banana"] for element in fruits: print(element)
|
||||||||||||||||||||||||||||||||||||
while loops |
|||||||||||||||||||||||||||||||||||||
while <condition>: <statement block>
|
# Example: i = 0 while i < 10: # Loop condition print(i) i=i+1 # Important for termination condition # Endless loop: while True: print(".", end="")
|
||||||||||||||||||||||||||||||||||||
break |
|||||||||||||||||||||||||||||||||||||
A break statement exits an active loop and continues beyond the loop. If the execution is in a nested loop, only the inner loop is exited.
|
# The program sums the entered numbers sum = 0 while True: input_text = input("Please enter an integer ('q' for end): ") if input_text == "q": break sum = sum + int (input_text) print("sum:", sum)
|
||||||||||||||||||||||||||||||||||||
lists |
|||||||||||||||||||||||||||||||||||||
Lists are an important higher data type
List literal: [<item list>]
Access to items via index.Warning: the first element has index 0.
The last element can be addressed with index -1, the penultimate with -2, ...
The length of the list can be determined with the built-in function len().
list.append(x)
Adds an item to the end of the list.
list.insert(i, x)
Adds an element at position i.
For example insert(0, x) adds in the first position.
list.remove(x)
Removes the item with value x from the list.
Causes error if this element is not present
list.pop(i)
Remove the element at position i and return it.
Without i, the method refers to the last element.
list.index(x)
Returns the position of the element with the value x.
Causes error if this element does not exist list.
count(x)
Returns how often the element with the value x occurs in the list.
list.sort(cmp=None, key=None, reverse=False)
Sorts the list.
list.reverse()
Reverses the list.
Mixed lists are allowed: ["abc", 3, 3.14, True]
In particular nested lists: [[1,3], [2,4,1], [5]]
|
pets = ["cat","dog","hamster","goldfish","bunny"] print(pets[2]) for pet in pets: print(pet) print(len(pets)) pets.append( "rabbit") pets.insert(0, "turtle") print(pets) pets.remove("turtle") print(pets) pets.pop() print(pets) print(pets.index("hamster")) print(pets.count("hamster")) pets.sort() print(pets) pets.reverse() print(pets)
Output:
>>> hamster cat dog hamster goldfish rabbit 5 ['turtle', 'cat', 'dog', 'hamster', 'goldfish', 'bunny', 'rabbit'] ['cat', 'dog', 'hamster ', 'goldfish', 'bunny', 'rabbit'] ['cat', 'dog', 'hamster', 'goldfish', 'bunny'] 2 1 ['goldfish', 'hamster', 'bunny', 'dog', 'cat'] ['cat', 'dog', 'bunny', 'hamster', 'goldfish'] >>>
|
||||||||||||||||||||||||||||||||||||
functions |
|||||||||||||||||||||||||||||||||||||
A distinction is made between functions with or without transfer parameters and between functions with or without a return value. Return-value functions contain a return statement. def <function name>(<parameter list>): <statement block>
|
def squared(x): return x * x
|
||||||||||||||||||||||||||||||||||||
module import |
|||||||||||||||||||||||||||||||||||||
There are essentially 2 types of module import. In the first case, the module name does not have to be prefixed when using the method. This shortens the program code a bit. In the second case, the module name must be prefixed when using the method. This prevents name collisions (with your own code or other modules).
|
# '*' imports all methods, but you can also # import methods selectively (names separated by commas) from random import * print(randrange(0, 10)) # Returns a number from 0 to 9
or
import random print(random.randrange(0, 10)) # Returns a number from 0 to 9
|
||||||||||||||||||||||||||||||||||||
random numbers |
|||||||||||||||||||||||||||||||||||||
The random module provides functionality for random numbers: random.randrange(stop) Returns a random number between 0 (inclusive) and stop (exclusive). random.randrange(start, stop) Returns a random number between start (inclusive) and stop (exclusive). somewhat obsolete: random.randint(x, y) same as random.randrange(x, y + 1) random.random() Returns a floating point number in the range [0.0, 1.0). (incl. 0 excl. 1) random.uniform(a, b) Returns a floating point number from the range [a, b). (incl. a excl. b) random.choice(seq) Returns a random element from the non-empty sequence "seq". Passing an empty sequence results in an error. ...
|
from random import * print(random()) # Returns a floating point number x, 0.0 <= x < 1.0 print(uniform(1, 10)) # Returns a floating point number x, 1.0 <= x < 10.0 print(randint(1, 10 )) # Returns an integer from 1 to 10 inclusive print(randrange(0, 10)) # Returns a number from 0 to 9 print(randrange(0, 101, 2)) # Returns an even number from 1 to 100 print (choice('abcdefghij')) # Returns a random item items = [1, 2, 3, 4, 5, 6, 7] shuffle(items) # Shuffles the list print(items)
output
>>> 0.8737058464500848 7.585665303116635 4 7 0 c [2, 3, 5, 1, 4, 7, 6] >>>
|
||||||||||||||||||||||||||||||||||||
Time, time modules |
|||||||||||||||||||||||||||||||||||||
See also: http://strftime.org/ https://docs.python.org/2/library/datetime.html time.gmtime() Returns the current time based on Greenwich Mean Time. For output, this time must first be converted into a character string with strftime(). time.localtime() Same as gmtime() but the time corresponds to the local time zone and also takes into account daylight saving time. time.strftime(format[, t])¶ Converts a time t (as returned by gmtime() or localtime()) to a string (according to the supplied string format). If t is not passed, the local system time is used.
|
from time import strftime, gmtime, localtime # selective import # GMT, 24-hour format print("current time:", strftime("%d.%m.%Y %H:%M", gmtime())) # Local time, 24-hour format print("current time:", strftime("%d.%m.%Y %H:%M", localtime())) # Local time, 12-hour format print ("current time:", strftime("%d.%m.%Y %I:%M", localtime()))
output
>>> current time: 11.10.2018 17:35 current time: 11.10.2018 19:35 current time: 11.10.2018 07:35 >>>
|
||||||||||||||||||||||||||||||||||||
math module |
|||||||||||||||||||||||||||||||||||||
Here you will find a number of useful mathematical functions and constants. Square root of x: math.sqrt(x) Conversion: radians(), degrees() pi, Euler's number e sin(), cos(), tan(), asin(), acos(), atan(), log (), log10(), pow(), ...
|
from math import * print(sqrt(9)) print(pi) print(sin(pi/2)) print(sin(radians(90)))
Output:
>>> 3.0 3.141592653589793 1.0 1.0 >>>
|
||||||||||||||||||||||||||||||||||||
Turtle programming |
|||||||||||||||||||||||||||||||||||||
The most important Turtle commands:
|
from turtle import * setup(400,400) # create a window of this size shape('turtle') # show the turtle fd(50) # forward 50 units lt(90) # rotate left 90 degrees pencolor('red' ) # pen color is now "red" fd(70) lt(90) fd(110) pencolor('blue') # pen color is now "blue" rt(90) # rotates 90 degrees to the right bk(100) # Go back 100 units pu() # pen up: raise the pen lt(45) bk(50) pd() # pen down: lower the pen pensize(5) # change the pen size to 5 bk(70) pensize( 1) home() # Go to the origin
|