
























































































Besser lernen dank der zahlreichen Ressourcen auf Docsity
Heimse Punkte ein, indem du anderen Studierenden hilfst oder erwirb Punkte mit einem Premium-Abo
Prüfungen vorbereiten
Besser lernen dank der zahlreichen Ressourcen auf Docsity
Download-Punkte bekommen.
Heimse Punkte ein, indem du anderen Studierenden hilfst oder erwirb Punkte mit einem Premium-Abo
Lots of hints to Python
Art: Zusammenfassungen
1 / 96
Diese Seite wird in der Vorschau nicht angezeigt
Lass dir nichts Wichtiges entgehen!

























































































Basic cheatsheet for Python mostly based on the book written by Al Sweigart, Automate the Boring Stuff with
Python under the Creative Commons license and many other sources.
All contributions are welcome:
Read the issues, Fork the project and do a Pull Request. Request a new topic creating a New issue with the enhancement tag. Find any kind of errors in the cheat sheet and create a New issue with the details or fork the project and do a Pull Request. Suggest a better or more pythonic way for existing examples.
Website Github PDF Jupyter Notebook
The Zen of Python Python Basics Math Operators Data Types String Concatenation and Replication Variables Comments The print() Function The input() Function The len() Function The str(), int(), and float() Functions Flow Control Comparison Operators Boolean evaluation Boolean Operators Mixing Boolean and Comparison Operators if Statements else Statements elif Statements while Loop Statements break Statements continue Statements
for Loops and the range() Function For else statement Importing Modules Ending a Program Early with sys.exit()
Functions
Return Values and return Statements The None Value Keyword Arguments and print() Local and Global Scope The global Statement
Exception Handling
Basic exception handling Final code in exception handling
Lists
Getting Individual Values in a List with Indexes Negative Indexes Getting Sublists with Slices Getting a List’s Length with len() Changing Values in a List with Indexes List Concatenation and List Replication Removing Values from Lists with del Statements Using for Loops with Lists Looping Through Multiple Lists with zip() The in and not in Operators The Multiple Assignment Trick Augmented Assignment Operators Finding a Value in a List with the index() Method Adding Values to Lists with the append() and insert() Methods Removing Values from Lists with remove() Sorting the Values in a List with the sort() Method Tuple Data Type Converting Types with the list() and tuple() Functions
Dictionaries and Structuring Data
The keys(), values(), and items() Methods Checking Whether a Key or Value Exists in a Dictionary The get() Method The setdefault() Method Pretty Printing Merge two dictionaries
sets
Initializing a set sets: unordered collections of unique elements set add() and update() set remove() and discard() set union() set intersection
Matching Regex Objects Grouping with Parentheses Matching Multiple Groups with the Pipe Optional Matching with the Question Mark Matching Zero or More with the Star Matching One or More with the Plus Matching Specific Repetitions with Curly Brackets Greedy and Nongreedy Matching The findall() Method Making Your Own Character Classes The Caret and Dollar Sign Characters The Wildcard Character Matching Everything with Dot-Star Matching Newlines with the Dot Character Review of Regex Symbols Case-Insensitive Matching Substituting Strings with the sub() Method Managing Complex Regexes
Handling File and Directory Paths
Backslash on Windows and Forward Slash on OS X and Linux The Current Working Directory Creating New Folders Absolute vs. Relative Paths Handling Absolute and Relative Paths Checking Path Validity Finding File Sizes and Folder Contents Copying Files and Folders Moving and Renaming Files and Folders Permanently Deleting Files and Folders Safe Deletes with the send2trash Module Walking a Directory Tree
Reading and Writing Files
The File Reading/Writing Process Opening and reading files with the open() function Writing to Files Saving Variables with the shelve Module Saving Variables with the pprint.pformat() Function Reading ZIP Files Extracting from ZIP Files Creating and Adding to ZIP Files
JSON, YAML and configuration files
JSON YAML Anyconfig
Debugging
Raising Exceptions
Getting the Traceback as a String Assertions Logging Logging Levels Disabling Logging Logging to a File Lambda Functions Ternary Conditional Operator args and kwargs Thinks to Remember(args) Thinks to remember(kwargs) Context Manager with statement Writing your own contextmanager using generator syntax main Top-level script environment Advantages setup.py Dataclasses Features Default values Type hints Virtual Environment virtualenv poetry pipenv anaconda
From the PEP 20 -- The Zen of Python:
Long time Pythoneer Tim Peters succinctly channels the BDFL's guiding principles for Python's design into 20 aphorisms, only 19 of which have been written down.
>>> import this The Zen of Python, by Tim Peters
Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced.
Return to the Top
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.
Strings 'a', 'aa', 'aaa', 'Hello!', '11 cats'
Return to the Top
String concatenation:
>>> 'Alice' 'Bob' 'AliceBob'
Note: Avoid + operator for string concatenation. Prefer string formatting.
String Replication:
>>> 'Alice' * 5 'AliceAliceAliceAliceAlice'
Return to the Top
You can name a variable anything as long as it obeys the following three rules:
Example:
>>> spam = 'Hello' >>> spam 'Hello'
>>> _spam = 'Hello'
_spam should not be used again in the code.
Return to the Top
Inline comment:
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 ''' """
Return to the Top
Integer to String or Float:
>>> str(29) '29'
>>> print('I am {} years old.'.format(str(29))) I am 29 years old.
>>> str(-3.14) '-3.14'
Float to Integer:
>>> int(7.7) 7
>>> int(7.7) + 1 8
Return to the Top
Operator Meaning
== Equal to
!= Not equal to
< Less than
> Greater Than
<= Less than or Equal to
>= Greater than or Equal to
These operators evaluate to True or False depending on the values you give them.
Examples:
True
False
>>> 'hello' == 'hello' True
>>> 'hello' == 'Hello' False
>>> 'dog' != 'cat' True
True
False
Never use == or != operator to evaluate boolean operation. Use the is or is not operators, or use implicit
boolean evaluation.
NO (even if they are valid Python):
>>> True == True True
>>> True != False True
Expression Evaluates to
True or True True
True or False True
False or True True
False or False False
The not Operator’s Truth Table:
Expression Evaluates to
not True False
not False True
Return to the Top
>>> (4 < 5) and (5 < 6) True
>>> (4 < 5) and (9 < 6) False
>>> (1 == 2) or (2 == 2) True
You can also use multiple Boolean operators in an expression, along with the comparison operators:
>>> 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2 True
Return to the Top
if name == 'Alice': print('Hi, Alice.')
Return to the Top
name = 'Bob' if name == 'Alice': print('Hi, Alice.') else: print('Hello, stranger.')
Return to the Top
name = 'Bob' age = 5 if name == 'Alice': print('Hi, Alice.') elif age < 12: print('You are not Alice, kiddo.')
name = 'Bob' age = 30 if name == 'Alice': print('Hi, Alice.') elif age < 12: print('You are not Alice, kiddo.') else: print('You are neither Alice nor a little kid.')
Return to the Top
spam = 0 while spam < 5: print('Hello, world.') spam = spam + 1
Return to the Top
If the execution reaches a break statement, it immediately exits the while loop’s clause:
You can even use a negative number for the step argument to make the for loop count down instead of up.
>>> for i in range(5, -1, -1): >>> print(i) 5 4 3 2 1 0
This allows to specify a statement to execute in case of the full loop has been executed. Only useful when a
break condition can occur in the loop:
>>> for i in [1, 2, 3, 4, 5]: >>> if i == 3: >>> break >>> else: >>> print("only executed when no item of the list is equal to 3")
Return to the Top
import random for i in range(5): print(random.randint(1, 10))
import random, sys, os, math
from random import *.
Return to the Top
import sys
while True: print('Type exit to exit.') response = input() if response == 'exit': sys.exit() print('You typed {}.'.format(response))
Return to the Top
>>> def hello(name): >>> print('Hello {}'.format(name)) >>> >>> hello('Alice') >>> hello('Bob') Hello Alice Hello Bob
Return to the Top
When creating a function using the def statement, you can specify what the return value should be with a
return statement. A return statement consists of the following:
The return keyword.
The value or expression that the function should return.
import random def getAnswer(answerNumber): if answerNumber == 1: return 'It is certain' elif answerNumber == 2: return 'It is decidedly so' elif answerNumber == 3: return 'Yes' elif answerNumber == 4: return 'Reply hazy try again' elif answerNumber == 5: return 'Ask again later' elif answerNumber == 6: return 'Concentrate and ask again'
Code in the global scope cannot use any local variables.
However, a local scope can access global variables.
Code in a function’s local scope cannot use variables in any other local scope.
You can use the same name for different variables if they are in different scopes. That is, there can be a local variable named spam and a global variable also named spam.
Return to the Top
If you need to modify a global variable from within a function, use the global statement:
>>> def spam(): >>> global eggs >>> eggs = 'spam' >>> >>> eggs = 'global' >>> spam() >>> print(eggs) spam
There are four rules to tell whether a variable is in a local scope or global scope:
Return to the Top
>>> def spam(divideBy): >>> try: >>> return 42 / divideBy >>> except ZeroDivisionError as e: >>> print('Error: Invalid argument: {}'.format(e)) >>> >>> print(spam(2)) >>> print(spam(12)) >>> print(spam(0)) >>> print(spam(1))
Error: Invalid argument: division by zero None
Return to the Top
Code inside the finally section is always executed, no matter if an exception has been raised or not, and
even if an exception is not caught.
>>> def spam(divideBy): >>> try: >>> return 42 / divideBy >>> except ZeroDivisionError as e: >>> print('Error: Invalid argument: {}'.format(e)) >>> finally: >>> print("-- division finished --") >>> print(spam(12)) >>> print(spam(0))
-- division finished --
-- division finished -- Error: Invalid argument: division by zero -- division finished -- None -- division finished --
-- division finished --
Return to the Top
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam ['cat', 'bat', 'rat', 'elephant']
Return to the Top