PythonCheatsheet.Org Flashcards
Studying https://www.pythoncheatsheet.org/cheatsheet/basics
Math Operators
From highest to lowest precedence:
Augmented Assignment Operators
Walrus Operator
The Walrus Operator allows assignment of variables within an expression while returning the value of the variable
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
Concatenation and Replication
Variable naming rules
- it can only be on word
- it can only use letters, numbers, and the underscore (
_
) character - It can’t begin with a number
- variables starting with an underscore (
_
) are considered as “unuseful”
Comments
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:
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:
The sep
keyword
The keyword sep
specify how to separate the objects, if there is more than one
The input()
Function
- This function takes the input from the user and converts it into a string:
-
input()
can also set a default message without usingprint()
: - It is also possible to use formatted strings to avoid using
.format
:
The len()
Function
Evaluates to the integer value of the number of characters in a string, list, dictionary, etc.
*don’t use it to test emptiness
Should you use len()
to test emptiness?
No, Test of emptiness of strings, lists, dictionaries, etc., should not use len, but prefer direct boolean evaluation.
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. Or from a string to an integer or float.
abs()
Return the absolute value of a number.
aiter()
Return an asynchronous iterator for an asynchronous iterable.
all()
Return True
if all elements of the iterable are true.
any()
Return True
if any element of the iterable is true.
ascii()
Return a string
with a printable representation of an object.
bin()
Convert an integer number to a binary string.
bool()
Return a Boolean value.
breakpoint()
Drops you into the debugger at the call site.
bytearray()
Return a new array of bytes.
bytes()
Return a new “bytes” object.
callable()
Return True
if the object argument is callable, False if not.
chr()
Return the string representing a character.
classmethod()
Transform a method into a class method.
compile()
Compile the source into a code or AST object.
complex()
Return a complex number with the value real + imag*1j
.
delattr()
Deletes the named attribute, provided the object allows it.
dict()
Create a new dictionary
dir()
Return the list of names in the current local scope
divmod()
Return a pair of numbers consisting of their quotient and remainder.
enumerate()
Return an enumerate object.
eval()
Evaluates and executes an expression.
exec()
This function supports dynamic execution of Python code.
filter()
Construct an iterator from an iterable and returns true.
float()
Return a floating point number from a number or string
format()
Convert a value to a “formatted” representation
frozenset()
Return a new frozenset object
getattr()
Return the value of the named attribute of the object
globals()
return the dictionary implementing the current module namespace.
hasattr()
True
if the string is the name of one of the object’s attributes.
hash()
Return the hash value of the object
help()
Invoke the built-in help system
hex()
Convert an integer number to a lowercase hexadecimal string
id()
Return the “identity” of an object
input()
This function takes an input and converts it into a string
int()
Return an integer object constructed from a number or string
isinstance()
Return True
if the object argument is an instance of an object
issubclass()
Return True
if the class is a subclass of classinfo
iter()
Return an iterator object
len()
Return the length (the number of items) of an object.
list()
Rather than being a function, list is a mutable sequence type
locals()
Update and return a dictionary with the current local symbol table
map()
Return an iterator that applies function to every item of iterable
max()
Return the largest item in an iterable
min()
Return the smallest item in an iterable
next()
Retrieve the next item from the iterator.
object()
Return a new featureless object
oct()
Convert an integer to an octal string
open()
Open and file and return a corresponding file object
ord()
Return an integer representing the Unicode code point of a character
pow()
Return base to the power exp.
print()
Print objects to the text stream file
property()
Return a property attribute
repr()
Return a string containing a printable representation of an object
reversed()
Return a reverse iterator
round()
Return number rounded to ndigits precisions after the decimal point.
set()
Return an new set
object
setattr()
This is the counterpart of getattr()
slice()
Return a sliced object representing a set of indices
sorted()
Return a new sorted list from the items in iterable
staticmethod()
Transform a method into a static method
str()
Return a str version of object
sum()
Sums start and the items of an iterable
super()
Return a proxy object that delegates method calls to a parent or sibling
tuple()
Rather than being a function, is actually an immutable sequence type
vars()
Return the dict
attribute for any other object with a dict attribute
zip()
Iterate over several iterables in parallel
import()
This function is invoked by the import statement
Comparison Operators
evaluate to True
or False
depending on the values you give them.
Boolean operators
there are 3: and
, or
, and not
The order of precedence, highest to lowest are not
, and
, and or
The and
Operators Truth table
The or
Operators Truth table
The not
Operators Truth table
Can you mix boolean and comparison operators?
yes.
>>> 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2 True """ In the statement below 3 < 4 and 5 > 5 gets executed first evaluating to False Then 5 > 4 returns True so the results after True or False is True """ >>> 5 > 4 or 3 < 4 and 5 > 5 True """ Now the statement within parentheses gets executed first so True and False returns False. """ >>> (5 > 4 or 3 < 4) and 5 > 5 False
if
, elif
, else
The if
statement evaluates an expression, and if that expression is True
, it then executes the following indented code.
The else
statement executes only if the evaluation of the if
and all the elif
expressions are False
.
Only after the if
statement expression is False
, the elif
statement is evaluated and executed.
the elif
and else
parts are optional.
Ternary Conditional Operator
Many programming languages have a ternary operator, which define a conditional expression. The most common usage is to make a terse, simple conditional assignment statement. In other words, it offers one-line code to evaluate the first expression if the condition is true, and otherwise it evaluates the second expression.
*Ternary operators can be chained.
Switch-Case Statement
In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map.
The Switch-Case statements, or Structural Pattern Matching, was firstly introduced in 2020 via PEP 622, and then officially released with Python 3.10 in September 2022.
Matching single values
Matching with the or Pattern
Matching by the length of an Iterable
Matching default value:
Matching Builtin Classes
Guarding Match-Case Statements
while
Loop Statements
The while
statement is used for repeated execution as long as an expression is True
:
break
Statements
If the execution reaches a break
statement, it immediately exits the while
loop’s clause:
continue
Statements
When the program execution reaches a continue
statement, the program execution immediately jumps back to the start of the loop.
For loop
The for
loop iterates over a list
, tuple
, dictionary
, set
or string
:
The range()
function
The range()
function returns a sequence of numbers. It starts from 0, increments by 1
, and stops before a specified number.
The range()
function can also modify its 3 defaults arguments. The first two will be the start
and stop
values, and the third will be the step
argument. The step is the amount that the variable is increased by after each iteration.
You can even use a negative number for the step
argument to make the for loop
count down instead of up.
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:
Ending a Program with sys.exit()
exit()
function allows exiting Python.
Function Arguments
A function can take arguments
and return values
:
In the following example, the function say_hello receives the argument “name” and prints a greeting:
Keyword Arguments
To improve code readability, we should be as explicit as possible. We can achieve this in our functions by using Keyword Arguments:
Return Values
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.