🐍 Bitmuncher's Python Stuff 🐍



Python Cheatsheet



Strings
Math Operators
Builtin Functions
Lists
Tuples
Dictionaries
Type Casting
Conditional Statements
Loops
Functions
Object Orientation
Exceptions and Errors

Basic Python Strings


Strings in Python are basically a sequence of multiple characters.

Note: To check if a string variable contains the expected string, you can output its value to the console window with the print() function.

Creating a String


1: my_string = "Let's create a string object!"
2: another_string = 'This is another string!'
3: a_multiline_string = '''This is a string
4: that consist of
5: multiple lines.'''


Note: Whichever option you use, you should stick to it and use it consistently within your script.

String Concatenation


You can add two strings together with the + operator.
1: string_one = "This is Bitmuncher's "
2: string_two = "Python Cheatsheet."
3: string_three = string_one + string_two

Note: You can't apply the + operator to two different data types (for example string and integer). If you try to do that, you'll get a TypeError.

String Replication


You can repeat a string multiple times with the * operator.
1: my_string = "Bitmuncher " * 5

Math Operators


Operator Operation Example
** Exponent 2 ** 3 = 8
% Modulus / Remainder 22 % 8 = 6
// Integer Division 22 // 8 = 2
/ Division 22 // 8 = 2.75
* Multiplication 4 * 2 = 8
- Substraction 4 - 2 = 2
+ Addition 4 + 2 = 6
** to the power x ** y

Built-in Functions


Here are some useful built-in functions in Python.

input()


The input() function is a simple way to prompt the user for some input. All user input is stored as a string.
1: name = input("What's your name? ")
2: print("Nice to meet you " + name + "!")

len()


The len() function helps you to find the length of any string or another data type.
1: my_string = ("I hope you enjoy this cheatsheet!")
2: print("The length of this string is " + str(len(my_string)) + " characters.")

filter()


You can use the filter() function to exclude items in iterable objects like lists, tuples or dictionaries.
1: ages = [3, 6, 7, 18, 23, 42]
2:
3: def under18(x):
4:   if x < 18:
5:     return False
6:   else:
7:     return True
8:
9: adults = filter(under18, ages)

Lists


Add items to a list


You can use the append() function to add an item to the end of a list.
1: bit_list = ["bitmuncher", "theoten", "theton"]
2: bit_list.append("kathus")

You can also use the insert() function to insert an item at a specific position in a list.
1: bit_list = ["bitmuncher", "theoten", "theton"]
2: bit_list.insert(2, "kathus")
This results in the following list: ['bitmuncher', 'theoten', 'kathus', 'theton']

Remove items from a list


If you know the item to remove, you can use the remove() function.
1: bit_list = ["bitmuncher", "theoten", "theton"]
2: bit_list.remove("bitmuncher")
Results in this list: ['theoten', 'theton']

You can also use the pop() function to remove an item with a specified index from a list. If no index is specified, it will remove the last item.
1: bit_list = ["bitmuncher", "theoten", "theton"]
2: bit_list.pop()
Results in this list: ['bitmuncher, 'theoten']

And you can use the del keyword to remove a specific item.
1: bit_list = ["bitmuncher", "theoten", "theton"]
2: del bit_list[1]
Results in this list: ['bitmuncher', 'theton']
Note: You can also apply del to the entire list to scrap it.

Replace item in a list


To replace an item in your list, you can simply give a specific list index a new value.
1: bit_list = ["bitmuncher", "theoten", "theton"]
2: bit_list[1] = "ArguZ"
Results in this list: ['bitmuncher', 'ArguZ', 'theton']

Combine two lists


Combining two lists can be done with the + operator.
1: bit_list_1 = ["bitmuncher", "theoten", "theton"]
2: bit_list_2 = ["kathus", "ArguZ", "KTS"]
3: bit_list_combined = bit_list_1 + bit_list_2
Results in this list: ['bitmuncher', 'theoten', 'theton', 'kathus', 'ArguZ', 'KTS']
But be careful, a typical mistake is to try to merge the lists into one list instead of using the + operator. This results is a nested list, as the following shows.

Create nested lists


If you put two lists into one new list, you get a nested list.
1: bit_list_1 = ["bitmuncher", "theoten", "theton"]
2: bit_list_2 = ["kathus", "ArguZ", "KTS"]
3: bit_list_nested = [bit_list_1, bit_list_2]
Results in this list of lists: [['bitmuncher', 'theoten', 'theton'], ['kathus', 'ArguZ', 'KTS']]

Sort lists


List objects provide a sort() function to sort all items in them.
1: ages = [42, 18, 7, 6, 23, 3]
2: ages.sort()
Results in: ages = [3, 6, 7, 18, 23, 42]

Slice lists


If you need only a specific subset of values from your list, you can get it by defining an index range in the format [Initial:End:IndexJump]. If IndexJump is not given it has a default value of 1.
1: ages = [3, 6, 7, 18, 23, 42]
2: ages_subset = ages[0:4]
Results in: ages_subset = [3, 6, 7, 18]

Create nested lists


Sometimes you need a copy of a list. If you use an assignment like bit_list_2 = bit_list_1 the value of bit_list_2 will change when bit_list_1 is changing. To get a real copy, you can use the copy() method of list objects.
1: bit_list_1 = ["bitmuncher", "theoten", "theton"]
2: bit_list_2 = bit_list_1.copy()
By that bit_list_2 is a copy of bit_list_1 and not an assignment anymore.

As an alternative way you can use the list() method.
1: bit_list_1 = ["bitmuncher", "theoten", "theton"]
2: bit_list_2 = list(bit_list_1)

Tuples


Tuples are very similar to lists. The main difference is that tuples are immutable, which means you cannot change the values stored in them. The big advantage of tuples over lists is that they can be processed much faster. So if you have lists of static values, you can optimize your code by using tuples instead.

Create tuples


To create a tuple you use () instead of [] around the list of values.
1: bit_tuple = ("bitmuncher", "theoten", "theton")

Convert a tuple to a list


Since tuples are immutable, you cannot change values in them. However, there may be rare situations where you need to replace a particular value in a tuple, but don't want to lose the fast processing for code optimization. To accomplish this, you can convert a tuple to a list, substitute the value, and then make the list a tuple again.
1: bit_tuple = ("bitmuncher", "theoten", "theton")
2: bit_list = list(bit_tuple)
3: bit_list[1] = "ArguZ"
4: bit_tuple = tuple(bit_list)
The conversion from one data type to another is called type casting. More about it later in section type casting.

Dictionaries


Dictionaries hold key-value pairs, where the key is the index that can be used to access a specific value. The key must always be unique within a dictionary.

Creating a dictionary


To create a dictionary you can either use curly brackets {} or the dict() method.
bit_dict_1 = {}
bit_dict_2 = dict()

Add values to a dictionary


To add values to a dictionary you define their keys and their values. Multiple key-value pairs are separated with comma.
bit_dict_1 = {
  "nickname": "Bitmuncher",
  "first_name": "Frank",
  "year": 1979
}

Access values in a dictionary


There are multiple ways to access values in a dictionary. The easiest way is to get the value via its key.
bit_dict_1 = {
  "nickname": "Bitmuncher",
  "first_name": "Frank",
  "year": 1979
}
my_nickname = bit_dict_1["nickname"]

But if you don't know the available keys, you can also get a list of the keys via the keys() method of dictionary objects:
my_keys = bit_dict_1.keys()

The same works for values with the values() method of dictionary objects:
my_keys = bit_dict_1.values()

And you can get a list of tuples with the key-value pairs with the items() method:
my_keys = bit_dict_1.items()

In addition you can also access values by looping through the dictionary.
# print all key names in the dictionary
for x in bit_dict_1:
  print(x)

# print all values in the dictionary
for x in bit_dict_1:
  print(bit_dict_1[x])

# print all keys and values in a dictionary via items() function
for x, y in bit_dict_1.items():
  print(x, y)

# print all keys and values without items() function
for x in bit_dict_1:
  print(x, bit_dict_1[x])

Change values in a dictionary


To change one of the items in a dictionary, you need to refer to it by its key.
bit_dict_1 = {
  "nickname": "Bitmuncher",
  "first_name": "Frank",
  "year": 1979
}
bit_dict_1["nickname"] = "Theoten"

Sets


Sets are used to store multiple items/values in a single variable. They are unchangeable but you can remove items and add new items to them. Besides they are unordered and unindexed. This means, you cannot be sure in which order the items will appear. Set items can appear in a different order every time you use them and cannot be referred to by an index or key.

Type casting


Even though Python is not a strongly typed language, there are several data types. Some of them - like lists, tuples, dictionaries and strings - have already been mentioned in this document. And sometimes it is necessary to convert values from one data type to another so that they can be processed in a certain way. For example, if you want to change or add a value in a tuple, you have to convert it to a list and then make it a tuple again after the modifications are done.

Since Python is an object-oriented language, it uses classes to define the data types, including its primitive types. Therefore, type casting is often done via constructor functions of the data type classes. But Python knows two types of type conversion.

Implicit type casting / UpCasting


Implicit type casting is done automatically by the interpreter, which converts one data type to another without having to call a specific function or anything like that in the code. However, this can only be done for the conversion of lower data types to higher data types to avoid data loss. Therefore it is also called UpCasting. For example, if you add a floating point number to an integer, the result is automatically a floating point number because integer is a lower data type than a floating point number.

Explicit type casting


For explicit type casting the constructor functions of the data type classes are used. The most commonly used type casting functions are:

Function Usage Parameters
int(value, base) converts the specified value into an integer number value - number or a string that can be converted into an integer number
base - number representing the number format. Default: 10
float(value) converts the specified value into a floating point number number or string that can be converted into a floating point number
str(object, encoding=encoding, errors=errors) converts the specified value into a string object - any object to convert into a string
encoding - optional, encoding of the object. Default: UTF-8
errors - optional, what to do if the decoding fails
ord(character) returns the number representing the unicode code of a specified character any character as a string
hex(number) converts the specified number into a hexadecimal value an integer
oct(int) converts an integer into an octal string an integer number
tuple(iterable) creates a tuple object optional, a sequence, collection or iterator object
set(iterable) creates a set object optional, a sequence, collection or iterator object
list(iterable) creates a list object optional, a sequence, collection or iterator object
dict() creates a dictionary Optional. As many keyword arguments you like, separated by comma: key=value, key=value

Conditional statements (if statements)


Like most other programming languages, Python supports logical conditions.

Condition Syntax
Equals
a == b
Not equals
a != b
Less than
a < b
Less than or equal to
a <= b
Greater than
a > b
Greater than or equal to
a >= b
Object identity
is
Negated object identity
is not

You can use these conditions in various ways, but in most cases you'll use them in if-statements and loops.

if, elif and else


There are multiple ways to check if a condition is true or not. The simplest way is an if-statement.
a = 1
b = 2
if a < b:
  print("This is true.")

You can also nest multiple if-statements.
a = 2
b = 3
if a > 1:
  print("This is true.")
  if b < 4:
    print("This is also true.")
Remember that the second condition in this example is only checked if the first one is true.

If you want to check the second condition even if the first is not true, you can use an elif-statement. (elif stands for "else if".)
a = 1
b = 3
if a > 1:
  print("The first condition is true.")
elif a < b:
  print("The second condition is true.")
In this example only the second print() will be executed. However, an elif-statement is only executed if the former if- and elif-statements are not true. As soon as one of the conditions is true, the code execution continues after the conditional statement.
Note: You can add as many elif-statements as you want.

If you want to execute some code in a conditional statement even if none of the conditions are true, you can use the else-statement.
a = 1
b = 3
if a > 1:
  print("The first condition is true.")
elif a > b:
  print("The second condition is true.")
else:
  print("None of the conditions is true.")
Remember that the else-statement is executed only if none of the previously checked conditions is true.

If-Not-Statements


Python provides the keyword not to check if a condition is not true.
bit_list = ["bitmuncher", "theoten", "ArguZ"]
nickname = "kathus"
if nickname not in bit_list:
  print("'nickname' is not in the list, so this is true.")

Pass-Statements


Sometimes you don't want to execute anything inside the conditional statement. However, since conditional statements cannot be empty, Python provides the pass statement. pass does nothing but only continues the script execution.
a = 1
b = 3
if a < b:
  pass

Loops


Python provides two simple loop types:
  • for-loops
  • while-loops

For-Loops


For-loops are mainly used when you need to iterate over a sequence of items, such as lists, tuples, strings or dictionaries.
Note: Since strings in Python are just a sequence of characters you can iterate over them.
for x in "bitmuncher":
  print(x)

bit_list = ["bitmuncher", "theoten", "ArguZ"]
for x in bit_list:
  print(x)
In this example the first loop will print every single character of the string, the second loop will print each item in bit_list.

While-Loops


While-loops are used to repeatedly execute a code as long as a given condition is met. But be careful, while-loops can lead to infinite loops if the condition never becomes false!
a = 1
while a < 4:
  print(a)
  a += 1

Break Loops


You can break a loop at any time by using the break-statement. It can be used in for-loops and in while-loops. In while-loops this is often used to implement a counter that avoids invinite loops.
a = 1
cnt = 1
while a < 8:
  print(a)
  if cnt > 4:
    break
  cnt += 1
  a += 1
The loop in this example is terminated as soon as cnt reaches the value 5, even if a is still smaller than 8.

Functions


A function is a block of code that is only executed when its called. Functions are mostly used for code blocks that must be executed multiple times during the script execution (often with different values in some variables), to structure the code and to make algorithms reusable. Furthermore functions are used as methods in classes (see the section Object orientation below).

Syntax of a function


The basic syntax of a function looks like this:
def function_name(parameters):
  function_body
  return return_value

The keyword def indicates the start of a function's definition. It's followed by the name of the function and an optional list of parameters in brackets. Leave the brackets empty if the function does not take any parameters. The colon indicates the start of the function body, similar to loops and conditional statements. The return statement is optional and can be omitted if you don't need a return value (more about return values later). A return statement can occur at any position within the function's body and will always terminate the execution of the function.

Examples:
def hello_world():
  print("Hello World!")

def print_value(myval):
  print(str(myval))
The first function doesn't need any parameter and simply prints the message "Hello World!" to the standard output (STDOUT), usually the terminal where the script is executed. The second function takes a single value as a parameter and prints it to the standard output. To avoid type errors it converts the parameter to a string before it's printed.

Calling a function


To call our example functions from above you use:
hello_world()
print_value("Hello World again!")

Function parameters


Of course, you can also use a list of parameters:
def my_sum(number1=3, number2=4):
  if isinstance(number1, int) and isinstance(number2, int):
    return number1 + number2
  else:
    if not isinstance(number1, int):
      print("number1 is not an integer")
      return
    elif not isinstance(number2, int):
      print("number2 is not an integer")
      return
    else:
      print("Unknown error!")
      return
This function takes 2 parameters, checks if both of them are integers and if yes, it adds them together and returns the sum. If one of the parameters is not an integer, it prints a message and returns None. Since we have assigned default values to the parameters, they can also be omitted when calling the function. This makes it even possible to define only one of the parameters, while the default value for the not specified parameter is taken.

Return values


As you can see, the result of the my_sum() function is not printed but returned instead with the return statement. A value returned by a function with the return statement is also called the 'return value' of the function. To get the result, you must assign the function call to a variable. By that the return value is assigned to the variable and you can use it in the further execution of your code.
a = 1
b = 2
result0 = my_sum() # 3+4
result1 = my_sum(a, b) # 1+2
result2 = my_sum(123, 456) # 123+456
result3 = my_sum(result1, result2) # 3+579
result4 = my_sum(number2=3) # 3+3

Of course, you can also process the return value directly without storing it in a variable before.
print(str(my_sum()))

Object orientation


Even though you can write procedural code with Python, it is still an object-oriented language where almost every element is an object with its own properties and methods.

Creating classes


Classes are blueprints for objects with specific properties and methods. To create a class you use the keyword class.
class BitClass:
  nickname = "bitmuncher"
Here we create a class with a single property called nickname.

However, usually you will not only define one property but also methods of the class, for example to manipulate the values of the properties. In addition a class has always a method __init__(), the so-called constructor, that is mostly used to initialize properties of an object that is created from this class. Defining __init__() is not necessary if you don't need to initialize anything during object creation.

Let's have a look at a more complex example:
class BitClass(object):
  """docstring"""
  def __init__(self, nickname, realname, year):
    """Constructor"""
    self.nickname = nickname
    self.realname = realname
    self.year = year

  def getInfo(self):
    print(self.nickname)

  def setNickname(self, new_nickname)
    self.nickname = new_nickname
This code defines the class BitClass that expects 3 values on initialization.
Note: The keyword self refers to the class itself. All methods in a class must reference their own class as a parameter but you don't have to define it while calling the method. If you want to access a property or a method within the class, you must always use self.propertyname or self.methodname().

Creating objects from a class


To create an object of this class you must define the 3 expected values as parameters.
bitclass_object = BitClass("bitmuncher", "Frank", 1979)

If you want to make the definition of the initial values for the properties optional, you can define default values for them in the __init__() method. The method would then look like this:
def __init__(self, nickname="bit", realname="Frank", year=1979):
  ...

Working with objects


To call the function getInfo() you must call it from the object.
bitclass_object.getInfo()

In the same way you can access properties (class variables) of a class.
bitclass_object.year

And you can use methods to set/change properties after creating the object from the class.
bitclass_object.setNickname("theoten")

Note: It is good coding style to query the properties of classes using so-called getter methods and to be able to change them using setter methods.
A better version of BitClass would look like this:
class BitClass(object):
  def __init__(self, nickname, realname, year):
    """Constructor"""
    self.nickname = nickname
    self.realname = realname
    self.year = year

  # getter methods
  def getNickname(self):
    return self.nickname
  def getRealname(self):
    return self.realname
  def getYear(self):
    return self.year

  # setter methods
  def setNickname(self, nickname):
    self.nickname = nickname
  def setRealname(self, realname):
    self.realname = realname
  def setYear(self, year):
    self.year = year

  def printInfo(self):
    print(self.nickname)
Setter methods for certain properties can of course be omitted if you want to ensure that these properties cannot be changed after the object has been created.

Extending and changing classes / Inheritance


Classes in Python can be derived from other classes. This is called inheritance. In this way it is possible to extend a class (adding properties and methods) or change its behavior. If we want to overwrite the printInfo() function from BitClass, we can do it by creating a new class that is derived from BitClass. The new class has all properties and methods of the parent class, but can add new properties and methods or modify existing ones.
class BitClassNew(BitClass):
  def printInfo(self):
    print("Nickname: " + str(self.nickname))
    print("Realname: " + str(self.realname))
    print("Born in : " + str(self.year))


Putting this all together looks like this:
#!/usr/bin/env python

class BitClass(object):
  def __init__(self, nickname, realname, year):
    """Constructor"""
    self.nickname = nickname
    self.realname = realname
    self.year = year

  # getter methods
  def getNickname(self):
    return self.nickname
  def getRealname(self):
    return self.realname
  def getYear(self):
    return self.year

  # setter methods
  def setNickname(self, nickname):
    self.nickname = nickname
  def setRealname(self, realname):
    self.realname = realname
  def setYear(self, year):
    self.year = year

  # other methods
  def printInfo(self):
    print("Nickname: " + str(self.nickname))

class BitClassExtended(BitClass):
  def printInfo(self):
    print("Nickname: " + str(self.nickname))
    print("Realname: " + str(self.realname))
    print("Born in : " + str(self.year))

if __name__ == "__main__":
  # create an object from BitClass
  bit_object = BitClass("bitmuncher", "Frank", 1979)

  # print value of a property by accessing it directly
  print("Value of self.year is: " + str(bit_object.year))

  # print value of a property using the getter method
  print("Value of self.nickname is: " + str(bit_object.getNickname()))

  # call printInfo() method from the class
  bit_object.printInfo()

  # create object from BitClassExtended
  bit_object_extended = BitClassExtended("bitmuncher", "Frank", 1979)

  # change the nickname property via setter method
  bit_object_extended.setNickname("theoten")

  # call the overwritten printInfo() method
  bit_object_extended.printInfo()

Exceptions and Errors


Python has a list of built-in exceptions that are thrown whenever the execution of your code raises an error situation. In the following you find a list of the most common exceptions in Python.

Exception Description
AttributeError Error that is raised when an attribute reference or assignment fails
ImportError Raised when the import statement has troubles trying to load a module. Also raised when the "from list" in from ... import has a name that cannot be found.
IndexError Raised when a sequence subscript is out of range
KeyError Raised when a mapping (dictionary) key is not found in the set of existing keys.
KeyboardInterrupt Raised when the user hits the interrupt key (normally Control+C).
NameError Raised when a local or global name is not found.
OSError This exception is raised when a system function returns a system-related error, including I/O failures such as "file not found" or "disk full".
SyntaxError Raised when the parser encounters a syntax error.
TypeError Raised when an operation or function is applied to an object of inappropriate type.
ValueError Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.
ZeroDivisionError Raised when the second argument of a division or modulo operation is zero.
See also the list of exceptions in the official Python documentation for further informations.

Exception Handling


Python provides the try/except-statement to catch and handle exceptions. It has the following syntax.
try:
  # here is the code that can cause an exception
except ExceptionName:
  # here is the code to handle the exception of type ExceptionName

Note: Unhandled exceptions usually interrupt the script execution. Execution then stops with a corresponding error message. Using exception handling allows the script to continue executing even if an exception situation has occurred.

Example (for a KeyError):
bit_dict_1 = {
  "nickname": "Bitmuncher",
  "first_name": "Frank",
  "year": 1979
}
try:
  myval = bit_dict_1["realname"]
except KeyError:
  print("That key does not exist!")

You can also handle several exceptions with a single statement.
try:
  myval = bit_dict_1["realname"]
except KeyError:
  print("That key does not exist!")
except IndexError:
  print("That index does not exist!")

Or you put it together in one except-statement if it doesn't matter what type of exception occured.
try:
  myval = bit_dict_1["realname"]
except (KeyError, IndexError):
  print("An exception was raised!")

And you can add an else-statement that is executed if no exception was raised.
try:
  myval = bit_dict_1["realname"]
except KeyError:
  print("That key does not exist!")
except IndexError:
  print("That index does not exist!")
else:
  print("No error occurred!")

If you want to execute code regardless of the result of the try- and except-blocks, you can use the finally-statement.
try:
  myval = bit_dict_1["realname"]
except KeyError:
  print("That key does not exist!")
except IndexError:
  print("That index does not exist!")
finally:
  print("The try-except is finished.")

If you don't know what type of exception can occur in a particular situation, you can simply omit the type.
try:
  myval = bit_dict_1["realname"]
except:
  print("An unknown error occurred!")

If you don't know what type of exception can occur, but you want to know what it was, you can store the Exception object in a variable and use it to get some details about the exception.
try:
  myval = bit_dict_1["realname"]
except Exception as e:
  print("Exception type: " + type(e).__name__)
  print("Arguments: " + str(e.args))

Other typical errors


In addition to exceptions, you may encounter other errors while testing your code.

Since Python code depends on clean indentation of code blocks, you should take special care when doing this. Incorrect indentation can lead to logic errors in the code that are sometimes hard to find, especially if the code is very nested. Finding such errors is often easier if you use an editor that is able to collapse blocks of code.

You should also take care that indentation of code is always done in the same way. If you indent sometimes using tabs and sometimes using spaces, your code will not work. To avoid such situations, you should make your editor display the "invisible characters", which allows you to see if tabs or spaces are being used.


  
Design based on Dracula UI