Python Flashcards

1
Q

What is an integer and float?

What does this mean:
a = 4
b = 3.142
c = 5.

A

Basic integer (int) types represent whole numbers, and are useful to act as programming counters, indices, and for basic integer arithmetic. They are made with a variable name, an equals sign = and the value of the integer.

Float datatypes in Python represent decimal numbers, and follow a similar construction pattern to integers, the main difference is that the number has a decimal point after the =

a = 4 as an integer
b = 3.142 as a float
c = 5.0 as a float

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

If:
a = 5
b = 6.
c = 4
d = 2

What is:
1. print(a - b)
2. print(a + c)
3. print(a/c)
4. print(b/c)
5. print(c**d)

A
  1. -1.0
  2. 9
  3. 1
  4. 1.5
  5. 16
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are strings?

Define:
a = ‘You’
b = “Yeah”
print(b, a)

print( a + ‘smell’)

A

A string (str) represents text as a sequence of characters, and is used for various tasks such as file input/output processes or printing messages to the user. Strings are defined in Python using either single ‘ or double “
marks around the characters

Yeah you

You smell

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

What are three data containers and are they for order or unordered data structures?

A
  • Two of the most commonly used containers for sequences of data where the order of the items matter are:
    - List: a mutable container that allows adding, removing, and editing of
    items.
    - Tuple: an immutable container that cannot be modified once created.

-For unordered data, we can use a dict (dictionary), which is very efficient for looking up entries in large datasets.

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

Explain what a the list function is in python

A
  • Python lists are flexible data containers that can hold a sequence of any type of Python objects.
  • They can be easily modified after creation, allowing for actions such as adding, editing, removing, and sorting items.
  • Lists are created by typing the sequence of items within square brackets and separated by commas, such as [a, b, c, …].
  • Lists can store any type of data, including other lists, and do not need to have homogeneous data types for each item.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What does this script mean?

a = [ 3, 5, 6, 8]

b = [ 7, 8, 9 ]

c = [ 5, 2, 8]

a. append(3)

b. extend(c)

print(a)

print(b)

A

[3, 5, 6, 8, 3]

[7, 8, 9, 5, 2, 8]

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

What does this script mean?

a = [ ‘one’, ‘up’, ‘one’, ‘down’]
a[3] = ‘Smash’
print(a)
print(a[1])
print(a[-2])

A

[‘one’, ‘up’, ‘one’, ‘Smash’]

up

one

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

b = [ ‘I’, ‘dont’, ‘actually’, ‘get’, ‘very’, ‘nervous’ ]
b. remove( ‘actually’)
del b[3]
print(b)

c = [ ‘im’, ‘to’, ‘get’, ‘shaky’ ]
c. insert(1, ‘starting’)
print(c)

A

[‘I’, ‘dont’, ‘get’, ‘nervous’]

[‘im’, ‘starting’, ‘to’, ‘get’, ‘shaky’]

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

What are Tuples?

A
  • Tuples are similar to lists, but are read-only.
  • They cannot be modified once created, unlike lists.
  • They are created by a sequence of datatypes separated by commas, such as a, b, c, but it’s commonly enclosed in parentheses (a, b, c).
  • Many of the manipulations that can be done with lists can also be done with tuples, except for those that involve changing the data in the tuple sequence.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are Dictionaries?

A
  • Dictionaries map unique keys to specific values, and are created using curly brackets {} (e.g. a={} for an empty dictionary).
  • Dictionaries are one of the most powerful and important data containers in Python.
  • They are very efficient for storing and retrieving data in a organized and fast manner.
  • Dict keys are usually an int or a str, while values can be any datatype in Python, including other dict objects.
  • Dictionaries can be constructed by using a colon : between the key and value, and a comma between each entry.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What does this script mean?

Food = {
‘burgers’ : 1,
‘pizza’ : 2,
‘cheese’ : 300,
}
Food[‘paella’] = 4
Food[‘burgers’] = 7

print(Food)
print(list(Food.keys()))
print(list(Food.values()))
print(list(Food.items()))

A

{‘burgers’: 7, ‘pizza’: 2, ‘cheese’: 300, ‘paella’: 4}

[‘burgers’, ‘pizza’, ‘cheese’, ‘paella’]

[7, 2, 300, 4]

[(‘burgers’, 7), (‘pizza’, 2), (‘cheese’, 300), (‘paella’, 4)]

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

What is slicing?

A
  • Slicing is a way to extract a sub-sequence of an object such as a list, string, or tuple.
  • It is done by specifying the start point (inclusive) and endpoint (exclusive) of the slice using a colon :, such as A[start:end].
  • The start point is 0-indexed, meaning the first element is index 0.
  • Slicing can also be used to change more than one item at a time.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

a = [5,6,9,2,6,77,7,8,10,23,1]

print(a[1:3])
print(a[:4])
print(a[5:])
print(max(a), min(a))

b = ‘abcdefghijklmnop’

print(b[2:10:2])
print(b[ : : -2])

print(len(a))
print(len(b))

A

[6, 9]
[5, 6, 9, 2]
[77, 7, 8, 10, 23, 1]
(77, 1)

cegi
pnljhfdb

11
16

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

What is Control Flow and what are three types?

A
  • Control flow in programming is about directing code to execute in a non-sequential manner, run multiple times, or not run at all.
  • Key concepts for control flow in Python include:
    -for and while loops with break and continue
    -if-else-elif statements
    -try-except

-Python uses indentation of code with 4 spaces to indicate control flow structure, most text editors will automatically add 4 spaces when TAB key is pressed.

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

What does this script mean?

a = 6

if (a > 0) and ( a % 2 == 0):
print( ‘ Postive and even’)

b = -7

if (b < 0) and ( a % 2 != 0):
print( ‘negative and odd’)

A

Positive and even

Negative and odd

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

What does this script mean?

a = -5
if a > 0:

print(‘Variable is positive’)

elif a == 0:

print(‘Variable is zero’)

else:

print(‘Variable is negative’)

A

Variable is negative

17
Q

What are for and while loops?

A
  • Loops are used to execute a block of code multiple times, with the ability to iterate over an iterable object such as a list, tuple, or range, using an iterating variable.
  • Two main types: for and while loops, can be controlled using break and continue commands.
  • Loops help to avoid repeating identical or similar code, making the code more concise, reliable, and easy to read and maintain.
  • for loops are the most commonly used, which iterate over an iterable object using an iterating variable, often i, j, and k, using the range() function to specify the range of numbers to iterate over.
18
Q

for i in range(100, 300, 50):

j = i + 10

print(‘Iterating variable is {0} and i + 10 = {1}’.format(i, j))

A

Iterating variable is 100 and i + 10 = 110
Iterating variable is 150 and i + 10 = 160
Iterating variable is 200 and i + 10 = 210
Iterating variable is 250 and i + 10 = 260

19
Q

What does this script mean?

D = {
‘Connor’: ‘a tiny willy’,
‘Sam’: ‘no soul’,
‘Joe’: ‘a really interesting diss’,
}
for key, value in D.items():

print(key, ‘has’, value)

A

(‘Connor’, ‘has’, ‘a tiny willy’)
(‘Sam’, ‘has’, ‘no soul’)
(‘Joe’, ‘has’, ‘a really interesting diss’)

20
Q

counter = 12

while counter >= 0
print(counter)
counter -= 2

A

12
10
8
6
4
2
0

21
Q

What are breaks and continues in a loop?

A
  • Break and continue commands provide more control on how loop statements behave.
  • Break command exits the current loop when a certain condition is fulfilled, ignoring any code after the break and further iterations in the loop will be skipped.
  • Continue statement skips the rest of the code block and moves onto the next item in the iterable when a certain condition is fulfilled.
  • These commands can be used to control the flow of the loop and make the code more efficient and reliable.
22
Q

Using break in a for loop

What does this script mean
for i in range(10):
if i == 5:
break
print(i)

Using continue in a for loop
for i in range(10):
if i % 2 == 0:
continue
print(i)

A

Output: 0 1 2 3 4 - The break stops the loop when i = 5

Output: 1 3 5 7 9 - the code skips the number if it is even

23
Q

How would you find what pi is using a python script?

A

import math
pi = math.pi
print(pi)
This imports the entire maths module the find what pi is

or

from math import pi
print(pi)
This only import pi from the math module

24
Q

What do the math function ceil, floor and how it it different to the round function ?

A

round goes to the closest integer
ceil rounds up
floor rounds down

25
Q

What does the define function do?

A
  • Functions are defined using the def keyword, followed by the function name and a set of arguments within parentheses.
  • The function code is indented after a colon, usually 4 spaces.
  • Functions can perform a specific task and can be reusable, it can also contain a documentation comment (docstring) to explain what the function does.
26
Q

What would the script look like to define the length of the hypotenuse for a right angled triangle solution?

A

from math import sqrt

def length(a, b):
“””
finding the length of the hypotenuse with lengths or a and b
“””
H = sqrt(a2 + b2)
print(H)

length(3,5)

27
Q

What would the script look like, using the return function, to find the 2 solutions of a quadratic equation?

A

import math

def quadratic_solution(a, b, c):
“””
This function calculates the solutions of a quadratic equation using the quadratic formula.
The input parameters are the coefficients of the equation: ax^2 + bx + c = 0
“””
discriminant = math.sqrt(b2 - 4ac)
solution_1 = (-b + discriminant) / (2a)
solution_2 = (-b - discriminant) / (2
a)
return solution_1, solution_2

x1, x2 = quadratic_solution(1, -3, 2)
print(“First solution:”, x1)
print(“Second solution:”, x2)

Output:
2.0
1.0

28
Q

What is the return function?

A
  • Return statement is used to return a value or multiple values from a function.
  • The execution of the function is terminated as soon as the return statement is encountered.
  • If no return statement is provided, the function returns None by default.
    You can return any Python object from a function, making it very flexible.
29
Q

What are required and default arguments?

A
  • Required arguments are mandatory parameters that must be provided when calling the function and appear first in the argument list.
  • Default arguments are optional parameters with a default value, they use an equals sign and come after the required arguments in the argument list.
  • Default arguments are used when the user does not provide a value for them.
  • Default arguments make the function more flexible and easier to use.