German / English

Python Cheat Sheet

General useful things for text files (not only in Python)

Some of the tips are Windows-specific, but the same applies to all other operating systems

The following keyboard shortcuts will help you at work:

clamp grip
Possible hand position

Ctrl+c  Copy
Ctrl+v  Paste
Ctrl+x  Cut

Ctrl+z  Undo last step

In most program editors but also in other applications the following applies:
Ctrl+s  Save
Ctrl+f  Search
Ctrl+c or Ctrl+q  are sometimes used to cancel an operation.

In Windows, Alt+Tab can be used to switch between windows.

With the arrow keysyou can navigate in text files, but there must be a line first.
You cannot switch to a non-existent line.
It may have to be created beforehand with the Enter key.

The Home, End keys jump to the beginning or end of the line.

Page up, page down
help scroll through a larger file quickly.

Ctrl+Arrow right
Ctrl+Arrow left
Skip forward one word at a time.

keyboard

The following shortcuts are also highly recommended:
Window+e  opens a file explorer.
Window+r  opens the Run dialog and after entering "cmd" and Enter the Windows command line opens.
Str++and Ctrl +-  Zoom in and out in the web browser.

Insert still:
Highlight text with the mouse.
Highlight text with arrow keys and Shift (Shift) key and Ctrl key.
Select text by double-clicking (word or line).
Insertion point: delete left or right.

basics

Python program files end with ".py"
The Python standard development environment (IDE) is called IDLE.
In IDLE you start a program with F5.

If you open and start a Python program, there are 3 windows
  1. the source code
  2. the application window: this is where the program runs
  3. a Python shell where all print() output and any error messages are displayed
Use Alt+tab to switch between windows. You can close it under Windows with Alt+F4 or with the "x" at the top right .
(For other operating systems there are equivalent shortcuts)

Warning! Python programs must not be given the same names as Python modules used.
For example, a self-created program file "turtle.py" leads to an error.
Unfortunately, you will not get an error message in this case.

The most important features of Python in brief

Basic data types

operators

The most important operators in descending "operator order" (priority).

** power
*, /, //, % Multiplication, division, integer division, modulo
+, - addition, subtraction
<, <=, >, >=, !=, == comparison
not logical "not"
other logical "and"
or logical "or"

Attention! Operator overloading :
Operators can have different meanings for different data types.
Examples:
+: addition for numbers, chaining (concatenation) for character strings and lists
*: multiplication for numbers, duplication for character strings
<: numeric comparison for numbers, alphabetical comparison for character strings

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:
setup(width,height) Creates a window of this size
fd(distance) (forward) The turtle moves "distance" forward.
bk(route) (back) The turtle moves backwards by "distance".
lt(angle) (left) The turtle turns "angle" to the left.
rt(angle) (right) The turtle turns "angles" to the right.
pu() (pen up) The turtle picks up the pen (and stops writing).
pd() (pen down) The turtle lowers the pen (and writes again).
pensize(width) sets the pen thickness to "Width".
pencolor(color) sets the pen color to "color".
shape sets the shape of the turtle ('arrow','classic','turtle','circle').
home() Turtle returns to (0,0) (center of drawing sheet).
clear() Delete drawing, turtle does not change state.
reset() Erase the drawing, the turtle returns to its initial state.
setup(width, height) Create window with "Width", "Height".
heading() In which direction is the turtle facing? (3 o'clock position = 0)
setheading(angle) Rotate the turtle towards "Angle" (3 o'clock position=0).
goto(x, y) Move the turtle to position x, y.
(If pen=down is also drawn. Does not change the orientation.)
dots(size, color) Draws a circle of size "size" and color "color"
at the current position.
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