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.
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.'''
1: string_one = "This is Bitmuncher's "
2: string_two = "Python Cheatsheet."
3: string_three = string_one + string_two
1: my_string = "Bitmuncher " * 5
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.
1: name = input("What's your name? ")
2: print("Nice to meet you " + name + "!")
1: my_string = ("I hope you enjoy this cheatsheet!")
2: print("The length of this string is " + str(len(my_string)) + " characters.")
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)
1: bit_list = ["bitmuncher", "theoten", "theton"]
2: bit_list.append("kathus")
1: bit_list = ["bitmuncher", "theoten", "theton"]
2: bit_list.insert(2, "kathus")
This results in the following list: ['bitmuncher', 'theoten', 'kathus', 'theton']
1: bit_list = ["bitmuncher", "theoten", "theton"]
2: bit_list.remove("bitmuncher")
Results in this list: ['theoten', 'theton']
1: bit_list = ["bitmuncher", "theoten", "theton"]
2: bit_list.pop()
Results in this list: ['bitmuncher, 'theoten']
del
keyword to remove a specific item.
1: bit_list = ["bitmuncher", "theoten", "theton"]
2: del bit_list[1]
Results in this list: ['bitmuncher', 'theton']
del
to the entire list to scrap it.
1: bit_list = ["bitmuncher", "theoten", "theton"]
2: bit_list[1] = "ArguZ"
Results in this list: ['bitmuncher', 'ArguZ', 'theton']
+
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']
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']]
1: ages = [42, 18, 7, 6, 23, 3]
2: ages.sort()
Results in: ages = [3, 6, 7, 18, 23, 42]
1: ages = [3, 6, 7, 18, 23, 42]
2: ages_subset = ages[0:4]
Results in: ages_subset = [3, 6, 7, 18]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.
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.
1: bit_tuple = ("bitmuncher", "theoten", "theton")
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.
bit_dict_1 = {}
bit_dict_2 = dict()
bit_dict_1 = {
"nickname": "Bitmuncher",
"first_name": "Frank",
"year": 1979
}
bit_dict_1 = {
"nickname": "Bitmuncher",
"first_name": "Frank",
"year": 1979
}
my_nickname = bit_dict_1["nickname"]
my_keys = bit_dict_1.keys()
my_keys = bit_dict_1.values()
my_keys = bit_dict_1.items()
# 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])
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.
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 |
a = 1
b = 2
if a < b:
print("This is true.")
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.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.
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.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
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 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.
a = 1
while a < 4:
print(a)
a += 1
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).
def function_name(parameters):
function_body
return return_value
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.
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.
hello_world()
print_value("Hello World again!")
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.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
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.
class
.
class BitClass:
nickname = "bitmuncher"
Here we create a class with a single property called nickname
.__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.
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.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()
.
bitclass_object = BitClass("bitmuncher", "Frank", 1979)
__init__()
method. The method would then look like this:
def __init__(self, nickname="bit", realname="Frank", year=1979):
...
bitclass_object.getInfo()
bitclass_object.year
bitclass_object.setNickname("theoten")
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.
class BitClassNew(BitClass):
def printInfo(self):
print("Nickname: " + str(self.nickname))
print("Realname: " + str(self.realname))
print("Born in : " + str(self.year))
#!/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. |
try:
# here is the code that can cause an exception
except ExceptionName:
# here is the code to handle the exception of type ExceptionName
bit_dict_1 = {
"nickname": "Bitmuncher",
"first_name": "Frank",
"year": 1979
}
try:
myval = bit_dict_1["realname"]
except KeyError:
print("That key does not exist!")
try:
myval = bit_dict_1["realname"]
except KeyError:
print("That key does not exist!")
except IndexError:
print("That index does not exist!")
try:
myval = bit_dict_1["realname"]
except (KeyError, IndexError):
print("An 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!")
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.")
try:
myval = bit_dict_1["realname"]
except:
print("An unknown error occurred!")
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))
Design based on Dracula UI