Python Cheat Sheet for beginners/pros, Zusammenfassungen von Informatik

Lots of hints to Python

Art: Zusammenfassungen

2019/2020

Hochgeladen am 23.05.2020

Franz1234
Franz1234 🇩🇪

1 dokument

1 / 96

Toggle sidebar

Diese Seite wird in der Vorschau nicht angezeigt

Lass dir nichts Wichtiges entgehen!

bg1
README.md 11/27/2018
1 / 96
About
launch
launch binder
binder
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.
Contribute
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.
Read It
Website
Github
PDF
Jupyter Notebook
Python Cheatsheet
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
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60

Unvollständige Textvorschau

Nur auf Docsity: Lade Python Cheat Sheet for beginners/pros und mehr Zusammenfassungen als PDF für Informatik herunter!

About launchlaunch^ binderbinder

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.

Contribute

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.

Read It

Website Github PDF Jupyter Notebook

Python Cheatsheet

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

The Zen of Python

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 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.

Strings 'a', 'aa', 'aaa', 'Hello!', '11 cats'

Return to the Top

String Concatenation and Replication

String concatenation:

>>> 'Alice' 'Bob' 'AliceBob'

Note: Avoid + operator for string concatenation. Prefer string formatting.

String Replication:

>>> 'Alice' * 5 'AliceAliceAliceAliceAlice'

Return to the Top

Variables

You can name a variable anything as long as it obeys the following three rules:

  1. It can be only one word.
  2. It can use only letters, numbers, and the underscore (_) character.
  3. It can’t begin with a number.
  1. Variable name starting with an underscore (_) are considered as "unuseful`.

Example:

>>> spam = 'Hello' >>> spam 'Hello'

>>> _spam = 'Hello'

_spam should not be used again in the code.

Return to the Top

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 ''' """

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

Flow Control

Comparison Operators

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

Boolean evaluation

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

Mixing Boolean and Comparison Operators

>>> (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 Statements

if name == 'Alice': print('Hi, Alice.')

Return to the Top

else Statements

name = 'Bob' if name == 'Alice': print('Hi, Alice.') else: print('Hello, stranger.')

Return to the Top

elif Statements

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

while Loop Statements

spam = 0 while spam < 5: print('Hello, world.') spam = spam + 1

Return to the Top

break Statements

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

For else statement

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

Importing Modules

import random for i in range(5): print(random.randint(1, 10))

import random, sys, os, math

from random import *.

Return to the Top

Ending a Program Early with sys.exit()

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

Functions

>>> def hello(name): >>> print('Hello {}'.format(name)) >>> >>> hello('Alice') >>> hello('Bob') Hello Alice Hello Bob

Return to the Top

Return Values and return Statements

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

The global Statement

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:

  1. If a variable is being used in the global scope (that is, outside of all functions), then it is always a global variable.
  2. If there is a global statement for that variable in a function, it is a global variable.
  3. Otherwise, if the variable is used in an assignment statement in the function, it is a local variable.
  4. But if the variable is not used in an assignment statement, it is a global variable.

Return to the Top

Exception Handling

Basic exception handling

>>> 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

Final code in exception handling

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

Lists

>>> spam = ['cat', 'bat', 'rat', 'elephant']

>>> spam ['cat', 'bat', 'rat', 'elephant']

Return to the Top

Getting Individual Values in a List with Indexes