python Flashcards

(11 cards)

1
Q

what are the main control structures

A

sequence (code runs in order)
selection (if, elif, else)
iteration (for/while loops)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

how to write an if…elif…else control structure

A

age = 17
if age < 13:
print(“Child”)
elif age < 18:
print(“Teenager”)
else:
print(“Adult”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

what’s the difference between a global and local variable?

A

global: declared outside functions, accessible everywhere
local: declared inside a function, accessible only within that function

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

what are some examples of simple and structured data types

A

simple: int, float, bool, str
structured: list, tuple, dict, set

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

how to retrieve information from a dictionary

A

print(person[“name”]) # Output: Liam

print(person.get(“grade”, “Not recorded”)) # Output: Not recorded

for key in person:
print(key, “→”, person[key])

for key, value in person.items():
print(f”{key}: {value}”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

define a basic python class with attributes and a method

A

class Car:
def __init__(self, brand, year):
self.brand = brand
self.year = year

def drive(self):
    print(f"The {self.brand} is driving.")

my_car = Car(“Toyota”, 2022)
my_car.drive()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

what is self in a python class

A

self refers to the instance of the class
- it is used to access attributes and methods of the object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

what is a function and why is it used

A

a reusable block of code that performs a task
- improves code organisation, reuse and testing

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

write python code to read a file line by line

A

with open(“data.txt”, “r”) as file:
for line in file:
print(line.strip())

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

write code to append text to a file

A

with open(“log.txt”, “a”) as file:
file.write(“New log entry\n”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

what are libraries and modules, and their difference?

A
  • a module is a single python file that contains functions, variables or classes to help developers organise code into reusable files
  • a library is a collection of modules that provide related functionality to help leverage external tools and extend functionality
How well did you know this?
1
Not at all
2
3
4
5
Perfectly