Topics in this lesson: - Basic numerical data types and conversion - Chars and strings - Arrays and how to use them - Dictionaries and how to use them - Queues and how to use them
Basic Data Types: Numbers, Chars, Strings
Note:
Python does have several data types, but you don´t have to specify them. Python knows by itself what data type you would like to store. It´s not necessary to declare a data type when creating a variable.
# There are serveral possibilities how to store a number: my_integer =10my_float_1 =3.1415my_float_2 =1/3my_exp_number_pos =4e+3my_exp_number_neg =4e-3print(my_integer)print(my_float_1)print(my_float_2)print(my_exp_number_pos)print(my_exp_number_neg)
# Numers also can be casted into an other data types my_integer =10print(type(my_integer))my_integer =float(my_integer)print(type(my_integer))print(my_integer)my_float_1 =int (my_float_1) # WARNING: Data loss because of conversion from float to int! print(type(my_float_1)) print(my_float_1)
# Short introductino of bools# Can be True or False # True or False always beginn with a upper case letter!flag =Trueif flag isTrue: print("I am true!")else: print("I am false!")
I am true!
Chars And Strings
A single character such as “a”, “B” or “!” are called char(s). Chars can be letters (a…z, A…Z), numbers (0…9) or special characters (!,$,&,?,…)
A array of chars is called a string. A string is also a data type!
my_char_a ="a"my_char_B ="B"my_char_questionmark ="?"# A string can be created by adding single chars...my_string = my_char_a + my_char_B + my_char_questionmark# To print variables inside of a string, use "f" for format at the beginning of a # string and put the variable to print in curved brackets "{}"print(f"My new string ist: {my_string}")# ... or by just writing them in quotation marks... my_string_option_1 ="Double qoutation marks"my_string_option_2 ='Single qoutation marks'my_string_option_3 ="""Single qoutation marks"""# They are equal in representation: print(type(my_string_option_1))print(type(my_string_option_2))print(my_string_option_1)print(my_string_option_2)
My new string ist: aB?
<class 'str'>
<class 'str'>
Double qoutation marks
Single qoutation marks
Single qoutation marks
Working With Chars and Strings
# Up to a certain point it´s useful to use mathematic with chars/stringsmy_char_1 ="a"print(my_char_a *10)print(my_char_1 + my_char_1 + my_char_1 + my_char_1 + my_char_1)print(my_char_1,my_char_1,my_char_1,my_char_1,my_char_1)print("a", "a", "a", "a", "a")print("Strings don´t need variables to be printed! "*3)# You can get the length of any string by simply print the string with "len()"my_string_abc ="abcdefghijklmnopqrstuvwxyz"print(f"The alphabet is {len(my_string_abc)} characters long.")
aaaaaaaaaa
aaaaa
a a a a a
a a a a a
Strings don´t need variables to be printed! Strings don´t need variables to be printed! Strings don´t need variables to be printed!
The alphabet is 26 characters long.
Arrays (Lists) And Tuples
Arrays are also known as lists. I refer to them always as array, feel free to use the term “list” if you please. We already heared, that Strings are arrays (or lists) of chars. A single Char is also an array, but just with the length of one! Arrays can be created out of neary every data type: int, float, char, string and even other arrays. That construct is called a matrix. To create an array use rectangular brackets: [1,2,3,4,5]
Tupels are a special form of lists. The are created by using regular brackets, instead of the rectengular ones. (1,2,3,4,5). The special property of these is, that they CAN´T be altered after they get created.
# A single Char is a string with the length of one. my_short_string ="1"print(f"Array len of a single char is: {len(my_short_string)}")# Creating an array/ a list of integer: my_int_array = [0,1,2,3,4,5,6,7,8,9]print(type(my_int_array))print(my_int_array)# Creating a tuple of int: my_int_tuple = (0,1,2,3,4,5,6,7,8,9)print(type(my_int_tuple))print(my_int_tuple)# Every element of an array or tuple can be accessed by a index. # NOTE: Every array or tuple start with the index 0!print(f"The first an last element of the array are: {my_int_array[0]} and {my_int_array[9]}")print(f"The first an last element of the tuple are: {my_int_tuple[0]} and {my_int_tuple[9]}")
Array len of a single char is: 1
<class 'list'>
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
<class 'tuple'>
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
The first an last element of the array are: 0 and 9
The first an last element of the tuple are: 0 and 9
Working With Array And Tuples
There are quite a few ways to manipulate, add or delete data from an array/list. It´s easy to extract the location of stored values, rewrite or remove them.
# Every array works with an so called index. It represents the position of data inside the array. # The index of every array starts at 0! my_string_array = ["Working", "with", "index", "can", "be", "fun", "(not really)"]print(my_string_array[2]) # Accessing the THIRD element of the array, not the second!# Entries of an array can be changed or deleted, but not thoose of a tuple! my_string_array[3] ="is"my_string_array.remove("be")my_string_array[5] ="yes, really!"print(my_string_array)# Trying to manipulate data in a tuple will result in a "TypeError"!#my_int_tuple[0] = 1 # Get the index of stored data in an array: my_string_array = ["Where", "is", "my", "needed", "data?"]my_array_index = my_string_array.index("data?")print(f"{my_string_array[my_array_index]} found on index {my_array_index}")# It doesn´t work for multiple data with the same value: my_string_array = ["Banana", "Apple", "Orange", "Apple", "Pear", "Apple"]my_array_index = my_string_array.index("Apple")print(my_array_index)# We can use the magic of loops for this situation: my_array_index = [] # Create an empty array/listfor value inrange(0, len(my_string_array)): if my_string_array[value] =="Apple": my_array_index.append(value) # Use the "append" function to add values to an array print(f"Apple is found on index: {my_array_index}")
index
['Working', 'with', 'index', 'is', 'fun', 'yes, really!']
data? found on index 4
1
Apple is found on index: [1, 3, 5]
Multidimensional Arrays
# Arrays can also be written as arrays of arrays, called matrixmy_3x3_matrix = [[1,2,3], [4,5,6], [7,8,9]]# It´s always accessed by first entering the index of the row and then the index of the columprint(my_3x3_matrix[1][1]) # Accessing the second element of the second rowprint(my_3x3_matrix[2][0]) # Accessing the first element of the third row# A matrix can be also written as 3x3x3my_3x3x3_matrix = [[[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9]], [[10,11,12], [13,14,15], [16,17,18]], [[19,20,21], [22,23,24], [25,26,27]]]print(my_3x3x3_matrix[2][0][2]) # Accessing the third layer, the first row and the third element print("_________________________")print(" 1, 2, 3")print(" 4, 5, 6 -- First layer")print(" 7, 8, 9")print(" 10, 11, 12")print(" 13, 14, 15 -- Second layer")print("16, 17, 18")print(" 19, 20, 21 -- 1st row")print(" 22, 23, 24 -- 2nd row")print("25, 26, 27 -- 3rd row")print(" | | |")print(" | | --- 3rd Colum")print(" | ------- 2nd Colum")print(" ------------ 1st Colum")
Dicts are also a usefull tool to store and manage data. Dicts working with the key-value principle. Dicts are created by using curved brackets including the key-value parametes as strings, seperated by a colon.
my_dict = {"key" : "value", "Ying" : "Yang", "Hotel?" : "Trivago"}print(my_dict)print(my_dict["Hotel?"]) # Accessing a value via key. # Dicts can contain all kind of data types, even other dicts: my_dict_in_dict = {"Key1": "Value1", "Key2" : "Value2"}my_diverse_dict = {"Age" : 25, "Grades" : [1,2,3,2,1], "DictDict": my_dict_in_dict}print(my_diverse_dict["DictDict"]["Key2"]) # Accessing a dict in a dictprint(my_diverse_dict["Grades"][0]) # Accessing a list in a dictprint(my_diverse_dict["Grades"])
Queues can also be a usefull way of storing data. You can store data as long as the queue is not full. Is the queue full however, the oldest data will be removed and the newest data will be lined up. Refer a queue to a tube full of tennis balls. If the tube is full and you add another tennis ball, the first one will pop out of the other side of the tube. “Pop” is a nice reference to the usage of queue, as you are able to tell the queue on which side you want to add or remove data. It´s even possible to inject data in the middle of a queue. But now step for step, lets start with creating one in the first place…
# Here we imported a class we needd, as it is not available by default. # What a class is and what it is used for will be discussed later. from collections import dequemy_queue = deque()# Adding data to a queue my_queue.append(1)my_queue.append(2)my_queue.append(3)my_queue.append(4)my_queue.append(5)print(my_queue)# Now lets remove some data. print(my_queue.popleft()) # Remove first added data# Pop will not just remove the data, it will return it. my_poped_value = my_queue.pop()print(my_poped_value) # Remove last added data my_queue.remove(3) # Remove data "3" out of the queue print(my_queue)my_queue.append("a")my_queue.append("b")my_queue.append("c")my_queue.append("a")print(my_queue)# Only the first added data will be deleted by this command. # The "remove" commands searches from left to right and stops, when it found a matching value. my_queue.remove("a") #my_queue.remove("?") # Will throw a ValueError, as "?" is not included in the data. print(my_queue)