1/130
Looks like no tags are added yet.
What is a Python script, and how is it different from the IPython Shell?
A Python script is a file containing Python instructions, usually ending in .py.
The IPython Shell lets you execute commands interactively and immediately see their results.
Write Python code that displays Hello World.
print("Hello World")
Strings need quotation marks, and functions such as print() use parentheses.
What is a variable in Python? Create one called age containing 19.
age = 19
A variable is a name referring to a stored value. You can then use a variable later on in calculations:
age = variable name
= = assignment
19 = assigned value
Question: Are age, Age, and AGE the same variable?
No. Python is case-sensitive.
Explain what an integer is and give three examples.
An integer is a whole number without a fractional part - whole number.
age = 19
temperature = -5
savings = 100
What is a float, and how does it differ from an integer?
A float is used for decimal numbers.
age = 19 # int
height = 1.75 # float
price = 5.0 # float
What is a string, and how do you write one?
A string represents text, written inside single or double quotation marks.
name = "Diana"
message = 'Hello'
number = "123"
What is a Boolean? Create a variable called is_good with the value True.
A Boolean is a data type with two possible values: True and False.
Boolean values do not need quotation marks.
is_good = True
What does the type() function do?
It identifies the data type of a value or variable.
print(type(19))
print(type(1.75))
print(type("Hello"))
print(type(True))
Output:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>What is the difference between 100 and "100"?
100 # Integer
"100"# String100 is a number that can be used in mathematical calculations.
"100" is text.
Predict both outputs:
print(5 + 3)
print("5" + "3")
8
53Why?
Integers are added mathematically.
Strings are joined together - Joining strings is called concatenation.
What does this code print?
print("Hello" + "World")
And how would you code it, if you wanted space inbetween?
HelloWorldprint("Hello" + " " + "World")
Output: Hello World
What happens when you convert True and False to integers?
print(int(True))
print(int(False))
1
0
True converts to 1, and False converts to 0.
What do int(), float(), str(), and bool() do?
They convert values between data types when conversion is possible.
int("12") # 12
float(5) # 5.0
str(25) # "25"
bool(0) # False
Why doesn't this code print 100?
savings = 100
print("savings")
"savings" is a string, so Python prints the word instead of retrieving the variable's value.
Correct code:
savings = 100
print(savings)Output: 100
Write code that adds savings = 100 and new_savings = 40, stores the result in total_savings, and prints it.
savings = 100
new_savings = 40
total_savings = savings + new_savings
print(total_savings)
Output:
140What does None mean in Python?
None represents the absence of a value.
For example:
result = NoneThe variable exists, but its current value is None.
Important: None is different from 0, False, and an empty string "".
What is a list, and how do you create one?
A list stores multiple values together in a particular order.
Lists use square brackets [].
Elements are separated by commas.
Lists can contain different data types.
numbers = [10, 20, 30]
Can one Python list contain integers, floats, strings, and Booleans?
Answer: Yes.
my_list = ["Diana", 19, 1.75, True]
What is the difference between a list and a set?
A list: Keeps order and allows duplicates.
numbers = [1, 2, 2, 3]A set: Contains only unique values: 1, 2, and 3.
numbers = {1, 2, 2, 3}Lists use []; set displays use {}.
Can sets contain values of different data types?
Yes, provided the elements are hashable (unchanging hash value).
my_set = {"Hello", 5, 2.5, True}
What is a nested list? Create one containing two rooms and their areas.
hallway - 11.25
kitchen - 18.0
Answer: A nested list is a list containing other lists.
[[], []] represents a list containing two inner lists.
house = [
["hallway", 11.25],
["kitchen", 18.0]
]
Explain the difference:
a = ["hallway", 11.25, "kitchen", 18.0]
b = [["hallway", 11.25], ["kitchen", 18.0]]
a contains four separate elements.
b contains two elements, and each element is itself a list.
What is indexing in Python, and where does counting begin?
fruits = ["apple", "banana", "orange"]
Indexing means accessing an element using its position.
Python starts counting at 0.
Index 0 = "apple"
Index 1 = "banana"
Index 2 = "orange"
Write code to print "banana" using indexing.
fruits = ["apple", "banana", "orange"]
print(fruits[1])
Use square brackets for indexing!
What does index -1 mean?
numbers = [10, 20, 30, 40]
print(numbers[-1])
It selects the LAST item.
Output: 40
Other examples:
[-2] = second from the end
[-3] = third from the end
Predict the outputs:
numbers = [10, 20, 30, 40]
print(numbers[0])
print(numbers[2])
print(numbers[-2])
Python counts forward from 0 and backward from -1.
10
30
30What is list slicing, and what is its syntax?
Slicing selects a range of elements.
my_list[start:end]start is included.
end is excluded.
What does this print?
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])
[20, 30, 40]Write code to select the first six elements of areas.
areas[:6]
This selects indexes: 0, 1, 2, 3, 4, 5
How do you select the last four elements of a list?
areas
areas[-4:]
-4 begins four elements from the end.
No ending index means continue to the end.
How do you select indexes 100 through 110, including index 110?
numbers[100:111]
What does this expression select?
numbers[:]
It selects all elements from beginning to end.
What does house[0][1] mean?
house = [
["hallway", 11.25],
["kitchen", 18.0]
]
It selects 11.25.
Step by step:
[0] selects the first inner list.
[1] selects the second element inside that list.
What does this print?
animals = [["cat", 2], ["dog", 5]]
print(animals[1][0])
dog[1] selects ["dog", 5].
[0] selects "dog".
How do you replace an existing list element?
numbers = [10, 20, 30]
You want to replace 20 with 99.
Select the element using its index and assign a new value.
list[index] = new_value
numbers[1] = 99
Output: [10, 99, 30]
Why is this incorrect?
areas[-1 = 10.50]The assignment must happen after the closing square bracket.
Correct:
areas[-1] = 10.50This changes the final element to 10.50.
How can you replace several list elements at once?
numbers = [10, 20, 30, 40]
You want to exchange the numbers 22 and 30 with 99 and 88.
Use slice assignment.
numbers[1:3] = [99, 88]
Result: [10, 99, 88, 40]
What happens when you use + between two Python lists?
a = [1, 2]
b = [3, 4]
print(a + b)
Python joins the lists into one new list = concatenation. + joins lists without changing the original list.
[1, 2, 3, 4]Add a poolhouse and its area of 24.5 to an existing list called areas, storing the result in areas_1.
areas_1 = areas + ["poolhouse", 24.5]
How do you delete an element from a list?
numbers = [10, 20, 30]
You want to delete 20 from the list.
del numbers[1]
[10, 30]
What happens here?
numbers = [10, 20, 30, 40, 50]
del numbers[1:3]
[10, 40, 50]
What happens to list indexes when you delete an element?
numbers = [10, 20, 30, 40]
del numbers[1]
Elements after the deleted element shift left by one position.
Now the list is [10, 30, 40].
The number 30, previously at index 2, is now at index 1.
How do you add one element to the end of a list?
numbers = [10, 20, 30]
You want to add 40 at the end of the list.
Use .append() it changes the original list.
numbers.append(40)
print(numbers)
[10, 20, 30, 40]What is the difference between .append() and + when working with lists?
a = [1, 2]
a.append(3)
b = [1, 2]
c = b + [3]
Changes a to [1, 2, 3].
Creates c = [1, 2, 3], while b remains [1, 2].
.append() changes the original list; + creates a new list.
What does the .remove() list method do?
numbers = [10, 20, 20, 30]
You want to get rid of the number 20.
It removes the first element whose value matches the argument.
numbers.remove(20)
Result: [10, 20, 30]
What is the difference between .remove() and del?
numbers = [10, 20, 30]
You want to get rid of the number 20.
numbers.remove(20) removes the element with value 20.
del numbers[1] removes the element at index 1.
Merke: .remove() uses a value; del uses an index or slice.
What happens when you call .reverse() on a list?
numbers = [10, 20, 30]It reverses the order of the existing list and changes the original list.
numbers.reverse()
print(numbers)
[30, 20, 10]What happens here?
x = [10, 20, 30]
y = x
y[0] = 99
print(x)
[99, 20, 30]Both x and y refer to the same list in memory.
Changing the list through y also affects what you see through x.
How do you copy a list without sharing the same outer list object?
original = [10, 20, 30]
copy = list(original)
Now you can replace elements in copy without changing original.
How do you make a copy using slicing?
original = [10, 20, 30]
copy = original[:]
[:] selects all elements and creates a new outer list.
Explain the difference between these three statements.
b = a
b = list(a)
b = a[:]
b = a makes both variables refer to the same list.
b = list(a) creates a new list.
b = a[:] also creates a new list.
Assignment is not the same as copying. (?)
Why might changing an inner list affect the original after copying with [:]?
a = [[1, 2], [3, 4]]
b = a[:]
b[0][0] = 99
print(a)
Because [:] creates a shallow copy: the outer list is new, but inner mutable objects are still shared.
Output: [[99, 2], [3, 4]]
A shallow copy does not independently copy nested lists.
What is a function in Python, and why do we use functions?
A function is reusable code that performs a particular task.
For example:
print("Hello")Here, print() is a function that displays information.
How do you call a Python function?
function_name(arguments)
What is an argument in a function call?
An argument is a value you provide to a function.
print("Hello")
"Hello" is the argument.
What does the len() function do?
numbers = [10, 20, 30]
Counts the number of elements in a collection, or the number of characters in a string.
print(len(numbers))
Output: 3
How do you find the largest number in a list?
numbers = [10, 50, 20]
Use max().
print(max(numbers))
Output: 50What does round() do?
With the the number: 1.68
print(round(1.68, 1))
Output: 1.7
The first argument is the number.
The second argument specifies how many decimal places to keep.
Merke: round(number, ndigits)
What happens when you call round() without specifying the number of decimal places?
With the the number: 1.68
Python rounds to the nearest integer according to its rounding rules.
print(round(1.68))
2How can you find information about how a Python function works?
Let´s say the function pow.
help(pow)
or
?pow
What does this code calculate?
print(pow(2, 3))
23 = 8
pow(base, exp) raises the base to the exponent.
In the signature pow(base, exp, mod=None), what does mod=None tell you?
Answer: mod is optional, since it says “None”.
base is required.
exp is required.
mod can be omitted.
Predict the output:
print(pow(2, 3, 5))
323 = 8
Remainder when dividing 8 by 5.
The remainder is 3.
How do you sort numbers from smallest to largest?
numbers = [5, 2, 9, 1]
print(sorted(numbers))
By default, sorted() sorts in ascending order and returns a new list.
Output: [1, 2, 5, 9]
How do you sort a list from largest to smallest?
numbers = [5, 2, 9, 1]
print(sorted(numbers, reverse=True))
Output: [9, 5, 2, 1]
Write code to combine two lists and sort the result in descending order.
a = [5, 10]
b = [3, 20]
full = a + b
full_sorted = sorted(full, reverse=True)
print(full_sorted)
Output: [20, 10, 5, 3]
What is the difference between a function and a method?
A function is called by its name; a method is called on an object using dot notation.
print(numbers)
numbers.append(10)
What is an object in Python?
An object is a value with a type and associated behavior.
name = "Diana"
numbers = [10, 20]
The string and list are both Python objects.
Different types provide different methods.
How do you find the position of a particular value in a list?
numbers = [10, 20, 30]
You want to find 20.
print(numbers.index(20))
Output: 1
.index() returns the index of the first matching element.
How do you count how many times a value appears?
numbers = [10, 20, 20, 30]
print(numbers.count(20))
Output: 2
.count() counts occurrences, not positions.
Predict both outputs:
numbers = [5, 10, 5, 20]print(numbers.index(5))print(numbers.count(5))0
2.index(5) finds the first position of 5.
.count(5) counts its total occurrences.
What does .upper() do to a string?
place = "poolhouse"
It returns an uppercase version of the string.
print(place.upper())
Output: POOLHOUSE
The original string remains unchanged.
Predict the output:
name = "diana"
print(name.capitalize())
DianaHow do you replace text inside a string?
word = "hello"
You want to replace the ”h” with a “j”.
print(word.replace("h", "j"))
Output: jello
.replace() returns a new string rather than modifying the original string.
How many times does "o" appear in "poolhouse", and how does Python calculate it?
place = "poolhouse"
print(place.count("o"))
Output: 3
Why is this wrong?
numbers = [10, 20, 30]print(index(20)).index() is a method called on the list.
print(numbers.index(20))
Output: 1
Merke: object.method(argument)
Can you use every method on every Python data type?
No. Available methods depend on the object's type.
numbers = [1, 2]
numbers.append(3)
Works because .append() is a list method.
But "hello".append("!") raises an error because strings don't have .append().
What's the difference between installing and importing a Python package?
Installing makes the package available in your Python environment.
Importing makes it available for use in the current program.
Terminal:
python -m pip install numpyPython:
import numpyHow do you import the math module and access π?
import mathprint(math.pi)How do you import only pi from math?
from math import piprint(pi)You can now use pi directly without writing math.pi.
Merke: from module import name
What does as mean in an import statement?
You want to import numpy with the name np.
It gives the imported package or function another name. as creates an alias (when multiple variables point to the exact same object in memory.)
import numpy as npnp.array([1, 2, 3])Must you write import numpy as np instead of import numpy?
No. Both are valid.
How can you import inv from scipy.linalg and call it my_inv?
from scipy.linalg import inv as my_invMerke: from module import function as nickname
Why is this wrong?
np = import(numpy)
import is a Python statement, not a function called with parentheses.
Correct:
import numpy as npWhat is a NumPy array, and how is it different from a normal Python list?
A NumPy array is a data structure for storing values and performing efficient operations on them.
Python list: numbers = [10, 20, 30]
NumPy array: np_numbers = np.array([10, 20, 30])
Convert a Python list called baseball into a NumPy array called np_baseball.
import numpy as npbaseball = [180, 215, 210]np_baseball = np.array(baseball)np.array() creates a NumPy array.
baseball is the original list.
np_baseball refers to the new array.
What does this output mean?
<class 'numpy.ndarray'>It means the variable contains a NumPy array.
class = Python object type
numpy = package
ndarray = N-dimensional array
How do you check whether np_baseball is a NumPy array?
print(type(np_baseball))
Output: <class 'numpy.ndarray'>
What happens when you multiply a NumPy array by 2?
numbers = np.array([10, 20, 30])print(numbers * 2)
Every element is multiplied by 2.
Output: [20 40 60]
Predict the results:
a = [1, 2, 3]
b = np.array([1, 2, 3])
print(a * 2)
print(b * 2)
Output:
[1, 2, 3, 1, 2, 3]
[2 4 6]A Python list multiplied by 2 repeats its elements.
A NumPy array multiplied by 2 multiplies each number.
Predict the output:
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(a + b)
[5 7 9]1 + 4 = 5
2 + 5 = 7
3 + 6 = 9
Merke: Array addition is element-wise when the shapes are compatible.
What happens when NumPy combines Booleans and integers?
numbers = np.array([True, 2, False])
print(numbers)
In this situation, NumPy converts the Boolean values into integers. True becomes 1, and False becomes 0.
[1 2 0]
Predict the output:
a = np.array([True, 1, 2])
b = np.array([3, 4, False])
print(a + b)
Output: [4 5 2]
First, convert the Booleans:[1, 1, 2] + [3, 4, 0]
Then add matching positions: [4, 5, 2]
Can a standard NumPy array contain different data types like a normal list?
A standard NumPy array normally has one common data type.
a = np.array([1, 2.5, 3])
NumPy converts the integers to floats.
NumPy commonly converts mixed input values to a shared type.
The array becomes:
[1. 2.5 3. ]
How do you select the element at index 50 from np_weight_lb?
print(np_weight_lb[50])
NumPy uses square brackets for indexing, just like Python lists.
How do you select indexes 100 through 110, including index 110, from np_height_in?
print(np_height_in[100:111])
Slicing works the same way as with regular Python lists.
Write code to convert an entire array of heights from inches to meters.
heights: 70, 72, 74
formula from m to in: *0.0254
np_height_in = np.array([70, 72, 74])np_height_m = np_height_in * 0.0254print(np_height_m)Output:
[1.778 1.8288 1.8796]What is a two-dimensional NumPy array?
How many rows and colums does this array have:
data = np.array([
[180, 78],
[190, 85],
[175, 72]
])
A 2D NumPy array organizes data into rows and columns, similar to a table.
This array has 3 rows and 2 columns.
What does this code display?
data = np.array([
[180, 78],
[190, 85],
[175, 72]
])
print(data.shape)
(3, 2)This means:
3 rows
2 columns
Merke: .shape describes the dimensions of a NumPy array.