Topic 2.1 - Computational Thinking/Decomposition and Abstraction Flashcards
What will happen: print(“….”)
A function to display the output of a program. Using the parenthesized version is arguably more consistent.
len()
Using len(some_object) returns the number of top-level items contained in the object being queried.
Lists
Example
> > x = [1, 2, 3, 4]
y = [‘spam’, ‘eggs’]
x
[1, 2, 3, 4]
y
[‘spam’,’eggs’]
> > y.append(‘mash’)
y
[‘spam’, ‘eggs’, ‘mash’]
> > y += [‘beans’]
y
[‘spam’, ‘eggs’, ‘mash’, ‘beans’]
Loops
> > for i in range(0, 3):
print(i*2)
0
2
4
> > m_list = [“Sir”, “Lancelot”, “Coconuts”]
for item in m_list:
print(item)
Sir
Lancelot
Coconuts
> > w_string = “Swift”
for letter in w_string:
print(letter)
S
w
i
f
t
range()
The range() function returns a list of integers, the sequence of which is defined by the arguments passed to it.
Sets
Sets are collections of unique but unordered items. It is possible to convert certain iterables to a set.
Example
> > new_set = {1, 2, 3, 4, 4, 4,’A’, ‘B’, ‘B’, ‘C’}
new_set
{‘A’, 1, ‘C’, 3, 4, 2, ‘B’}
> > dup_list = [1,1,2,2,2,3,4,55,5,5,6,7,8,8]
set_from_list = set(dup_list)
set_from_list
{1, 2, 3, 4, 5, 6, 7, 8, 55}
Slice
A Pythonic way of extracting “slices” of a list using a special bracket notation that specifies the start and end of the section of the list you wish to extract.
str()
Using the str() function allows you to represent the content of a variable as a string.
Syntax
str(object)
Example
> > # such features can be useful for concatenating stringsmy_var = 123
my_var
123
> > str(my_var)
‘123’
> > my_booking = “DB Airlines Flight “ + str(my_var)
my_booking
‘DB Airlines Flight 123
Variables
Variables are assigned values using the = operator, which is not to be confused with the == sign used for testing equality. A variable can hold almost any type of value such as lists, dictionaries, functions.
Integers
Integers are numbers without decimals. You can check if a number is an integer with the type() function. If the output is <class ‘int’>, then the number is an integer.
> > > type(1)
<class ‘int’>
> > > type(15)
<class ‘int’>
> > > type(0)
<class ‘int’>
> > > type(-46)
<class ‘int’>
Floats
Floats are numbers with decimals. You can detect them visually by locating the decimal point. If we call type() to check the data type of these values, we will see this as the output.
> > > type(4.5)
<class ‘float’>
> > > type(5.8)
<class ‘float’>
> > > type(2342423424.3)
<class ‘float’>
> > > type(4.0)
<class ‘float’>
> > > type(0.0)
<class ‘float’>
> > > type(-23.5)
<class ‘float’>