Python Basics

0.0(0)
studied byStudied by 17 people
0.0(0)
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/90

encourage image

There's no tags or description

Looks like no tags are added yet.

Last updated 8:45 PM on 2/5/26
Name
Mastery
Learn
Test
Matching
Spaced
Call with Kai

No analytics yet

Send a link to your students to track their progress

91 Terms

1
New cards

#Comment

What is the syntax of a single line comment?

2
New cards

“““Comment”””

What is the syntax of a multi-line comment?

3
New cards

The variable must be cast to a string

str()

What must be done to a variable to be used in string concatenation?

4
New cards

It seemed like a good idea at the time... It seemed like a good idea at the time... It seemed like a good idea at the time... ?

The comma will provide a space between whatever is printed.

The question mark is a string.

The \n moves the cursor to next line.

lyric = 'It seemed like a good idea at the time...'

print(lyric,lyric,lyric,end ='?\n')

What will this output?

5
New cards

Strings are immutable in Python. Once a string is created it cannot be modified, but it can be replaced.

Are string mutable or immutable in Python?

6
New cards

x, y = y, x

What is the syntax of swapping the value of 2 variables?

7
New cards

len(string)

“len” starts counting at 1 not zero

What is the syntax of checking the length of a string in python?

8
New cards

10 // 3

Output = 3

What is the syntax of integer division in python?

9
New cards

In Python integer division (also known as floor division) rounds down.

For negative numbers, it still rounds down (towards negative infinity):

print(-7 // 2)

Output: -4

In Python does integer division round up or down?

10
New cards

empty_list = []

or

empty_list = list()

What is the syntax of creating an empty list in python?

11
New cards

In the console

Where does the output of the code display?

12
New cards
print(f"|{123:10}|")

How do I achieve the following output?

# Output: |       123| (right-justified by default)

13
New cards
print(f"|{myNum:10}|")

How do I achieve the following output?

myNum = 123
# Output: |       123| (right-justified by default)

14
New cards
print(f"|{myNum:<10}|")

How do I achieve the following output?

myNum = 123
# Output: |123       |

15
New cards
print(f"|{myNum:^10}|")

How do I achieve the following output?

myNum = 123
# Output: |   123    |

16
New cards
print(f"|{myNum:>10}|")

How do I achieve the following output?

myNum = 123
# Output: |       123|

17
New cards
print(f"|{myNum:05}|")

How do I achieve the following output?

myNum = 123
# Output: |00123| ( zero padding )

18
New cards
import math
print(f"|{math.pi:.2f}|") 

How do I achieve the following output?

# Output: |3.14| ( precision)

19
New cards
print(f"|{255:x}|")

How do I achieve the following output?

# Output: |ff| ( hexadecimal)

20
New cards
print(f"|{0.75:.2%}|")

How do I achieve the following output?

# Output: |75.00%| ( percentage conversion)

21
New cards

1 2

2 1

x, y = 1, 2

print(x, y)

x, y = y, x

print(x, y)

What will this output?

22
New cards

This is short for Local->Enclosed->Global->Builtin and defines the path the interpreter searches for variables for resolution. If the variable doesn't exist locally, it looks in the enclosing scope ( within the function ), then global space, and finally built-in environment variables.

What is the LEGB rule?

23
New cards

1

2

2

x = 1
print
(x)
def change():
global x
x = 2
print
(x)
change()
print(x)

What will this output?

24
New cards

1

2

1

x = 1
print(x)
def change():
x = 2
print(x)
change()
print(x)

What will this output?

25
New cards

A local variable can be read in a nested function, but it cannot be modified in a nested function.

Why does the following code throw an error in python?

def func():
x = 1
def nested_func
():
x += 1

26
New cards

// is floor division

5 // 3 = 1

5.0 // 3 = 1.0

What is the result of x = 5 // 3?

27
New cards

x**y

What is python’s equivalent of C#’s Math.Pow(x, y)

28
New cards

var = expression_true if condition else expression_false
Example: x = y if r < 0 else z

What is python’s equivalent of C#’s ternary expression?

Example: x = r < 0 ? y : z;

29
New cards

x = 1
match x:
case 1:
print("x is 1")
case 2:
print("x is 2")

What is the syntax of a match?

30
New cards

match

What is the equivalent of C#’s switch?

31
New cards

Underscore

case _:

Can be used in a tuple: case (300, _):

What represents the wildcard in match?

32
New cards

flag = False

match(x, y):

case (100, 200) if flag:

What is the syntax of using an if statement within a case of a match statement?

33
New cards

match(x, y):

case (100 | 200 | 300, 200) :

What is the syntax of using an or within a case of a match statement?

34
New cards

squares = [x**2 for x in numbers]

Using comprehensions how would one store the squared values from a list into a new list “squares”?

numbers = [1,2,3,4,5]

35
New cards

[expression for item in iterable if condition]

Here, 'expression' is applied to each 'item' in the 'iterable', and 'condition' (optional) filters the items

What is the basic syntax for a list comprehension?

36
New cards

new = [x for x in numbers if x % 2 == 0]

Using comprehensions how would one create a new list containing only the even numbers from the original list?

numbers = [1,2,3,4,5]

37
New cards

new = [x for i,x in enumerate(numbers) if i % 2 != 0]

or

new = [t[1] for t in enumerate(numbers) if t[0] % 2 != 0]

enumerate returns index, value

i & t[0] = index x & t[1] = value

Using comprehensions how would one create a new list containing only the elements of the original list located in the odd indices?

numbers = [1,2,3,4,5]

38
New cards

list = [num for row in matrix for num in row]

exterior = for row in matrix

interior = for num in row

Which is the inner for loop and which is the outer for loop?

list = [num for row in matrix for num in row]

39
New cards

import random

random.shuffle(list)

How do you use random to mix up a collection or sequence?

40
New cards

import random

random.choice(list)

How does one use random to make a random selection from a collection or sequence?

41
New cards

The random.random() function in Python produces a random floating-point number between 0.0 and 1.0, inclusive of 0.0 but not 1.0

What does random.random() produce?

42
New cards

s.index(‘x’, i, j)
collection.index(searched element, starting index(inclusive), end of search(exclusive))

What is the syntax of finding the index of the first occurrence of x in s (at or after index i and before index j)?

43
New cards

s.count(x)

What is the syntax of finding the total number of occurrences of x in s?

44
New cards

The for loop automatically stops when the generator is done.

Why is it convenient to use a for loop to call a generator?

45
New cards

import time

start = time.perf_counter()

“code to be evaluated”

end = time.perf_counter()

print(end-start)

What is the syntax of capturing the time it takes to run a selection of code?

46
New cards

PEP 8, or Python Enhancement Proposal 8, is the official style guide for Python code. Created in 2001 by Guido van Rossum, Barry Warsaw, and Nick Coghlan, PEP 8 provides comprehensive guidelines for writing clean, readable, and consistent Python code. The main goals of PEP 8 are:

  1. To improve code readability

  2. To make Python code consistent across different projects and developers

  3. To reduce bugs and errors by promoting clear and understandable code

What is PEP 8?

47
New cards

The 'f' stands for "fixed-point notation", which is a way of writing floating-point numbers with a specific number of digits after the decimal point.

The .2 specifies the precision (number of decimal places), while the f indicates that it should be formatted as a float

pi = 3.14159

print(f"|{pi:.2f}|")

What does the “f” that follows the 2 stand for?

48
New cards

if value in collection

What is the syntax of checking if a collection contains a specific element?

49
New cards

if value not in collection

What is the syntax of checking if a collection does not contain a specific element?

50
New cards

slice of s from i to j with step k

  • i is the start index (inclusive)

  • j is the end index (exclusive)

  • k is the step or stride

What does the following do?
s[i:j:k]

51
New cards

min(collection)

What is the syntax of retrieving the smallest item of a collection?

52
New cards

max(collection)

What is the syntax of retrieving the largest item of a collection?

53
New cards

collection.index(x, i, j)
i & j are optional

j is exclusive(it will not compare the element at j)

What is the syntax of finding the index of the first occurrence of x in collection (at or after index i and before index j)

54
New cards

def function(*args)

One asterisk

What comes before the args variable?

55
New cards

def function(**kwargs)

Two asterisks

Nothing comes in front when inside the function

What comes before the kwargs variable?

56
New cards

key word arguments

What is kwargs an abbreviation of?

57
New cards

list = string.split(‘,’)

The string method split() will split the string every time it encounters the delimiter in the string and adds all the portions to a list.
If no delimiter is assigned, the default is ‘ ‘(a space).

What is split() used for and what is it’s syntax?

58
New cards

import string

alphabet = string.ascii_letters

string.ascii_lowercase and string.ascii_uppercase if you don’t want both.

What is the easiest method of obtaining a string of the alphabet, lowercase and uppercase?

59
New cards

import string

numbers = string.digits

What is the easiest way of getting a string of numbers 0 - 9?

60
New cards

iterable = iterable.reverse()

What is the syntax of reversing an iterable?

61
New cards

listy = [1,2,3,4,5]

def squared(nums):

return num**2

listy_squared = map(squared, listy, …)

map(function, iterable, ...)

  1. function: This is the function that will be applied to each item in the iterable(s).

  2. iterable: This is the sequence, collection, or iterator object that you want to map.

  3. ...: You can provide multiple iterables as arguments. If multiple iterables are provided, the function must accept as many arguments as there are iterables

listy = [1,2,3,4,5]

listy_squared = []

def squared(nums):

return num**2

What is the syntax of using the map() method to do the same thing as the following code?
for num in listy:

listy_squared.append(squared(num))

62
New cards

When the top level elements are altered in a shallow copy the original is unchanged. But when any nested element is altered in a shallow copy the original is altered.


When any part of a deep copy is altered the original does not change.

What type of copy affects the original when nested elements are altered in the copy and what type does not?

63
New cards

A deep copy

What type of copy recursively copies the entire object tree including all nested structures? Modifications to the copy or its nested objects do not affect the original

64
New cards

Shallow copy

What type of copy only copies the top level structure, not the nested objects. Changes to the nested objects in the copy will affect the original, and vice versa

65
New cards

copied = copy.copy(original)

How does one perform a shallow copy?

66
New cards

deep_copied = copy.deepcopy(original)

How does one perform a deep copy?

67
New cards

a_list.extend(b_list)

print(a_list)

Outputs: [1,2,3,4,5,6]

a_list = [1,2,3]

b_list = [4,5,6]

What python built in function performs the same function as

a_list += b_list

68
New cards

collection.pop(2)
Pop retrieves the item at index 2 and also removes it from the collection

If the index is not populated an ValueError will be thrown

How does the built in “pop()” function work?

69
New cards

collection.remove(“q”)

Removes the first item from collection where the value equals “q”

If the item does not exist in the collection an IndexError is thrown

How does the built in function “remove()” work?

70
New cards

reversed_collection = sorted(original_collection, reverse=True)

How does one use a built in function to sort a collection in reverse order?

71
New cards

help(function)

example:

help(random.choice)

How do you access the built in help from Python?

72
New cards

It produces a shallow copy and that means that any changes to nested items in the copy will alter the items in the original as well. The top level items will not change in the original.

copyList = copyList + copyList + copyList

Does the preceding produce a deep copy or shallow copy and what does that mean?

73
New cards

It produces a shallow copy and that means that any changes to nested items in the copy will alter the items in the original as well. The top level items will not change in the original.

List copy operations are all shallow-copy.

copyList = intList.copy()

Does the preceding produce a deep copy or shallow copy and what does that mean?

74
New cards

Neither, when you make a copy using assignment, it is called a reference or an alias. This method does not create a new object but instead creates a new reference to the same object in memory.

This type of assignment is neither a shallow copy nor a deep copy. It simply creates a new name that points to the same object. As a result, any changes made to copy1 will affect original_list and vice versa, because they are referring to the same object in memory

When one makes a copy by assignment (ex. copy1 = original_list) is it a shallow copy or a deep copy?

75
New cards

A slice of a list is a shallow copy. Changes at the top level will not change the original but changes to a nested item will change the original.

What type of copy is a slice of a list?

76
New cards

Sets are unordered.

How are sets ordered?

77
New cards

If you run random.seed() repeatedly with the same value in the brackets you will always output the same sequence of random numbers.

What does random.seed() do?

78
New cards

def function_name(argument1=default1, argument2= defualt2):

def add(num1=5, num2=10):

What is the syntax of defining defaults for arguments in functions?

79
New cards

‘::’.join(iterable)

What is the syntax of concatenating an iterable into a single string with :: between each item?

80
New cards

In Python, the .sort() method can only be used on lists. It is a built-in method of the list object that sorts the elements in-place, meaning it modifies the original list.

What collections can the .sort() method be used on in python? Does it return the original collection or a new collection?

81
New cards

The sorted() function can be used on any iterable, including lists, tuples, dictionaries, and sets

What collections can the sorted() method be used on in python? Does it return the original collection or a new collection?

82
New cards
class Person:
    def __init__(self,name,age):
        self.name = name
        self.age = age

The init method in Python is a special method, also known as a constructor, that is automatically called when a new instance of a class is created.

It's important to note that init is not the actual constructor in Python. The new method is responsible for creating the instance, while init focuses on initializing that instance

What is the syntax of a constructor in python?

83
New cards
def __str__(self):
    return self.name + " " + str(self.age)    

or

def __str__(self):
    return f'{self.name} {self.age}'

What is the syntax of using the __str__ method in python?

84
New cards

filter(function, iterable)

The filter() function returns an iterator object.

What is the syntax of the filter() function?

What does the filter function return?

85
New cards

lambda arguments: expression

Example:
to_upper = lambda text: text.upper() print(to_upper("Hello World!"))

What is the syntax of a lambda in python?

86
New cards

The >>> is called a REPL, short for Read-Evaluate-Print-Loop, and is meant for interactive use within an existing environment

What is >>> ?

87
New cards

Verbose mode

What doctest mode provides detailed output about the tests being run, including the code being tested, its expected output, and whether the test passed or failed. It is particularly useful for debugging and understanding the behavior of your doctests.

88
New cards

raise

What keyword is used to manually trigger an exception. This allows developers to signal an error condition when a specific condition occurs in their code, enabling more controlled error handling.

89
New cards

with

What statement in Python is primarily used for resource management, ensuring that resources such as files, connections, or locks are properly cleaned up after use, regardless of whether an exception occurs or not. It works by using a context manager, which is an object that implements the context management protocol. This protocol consists of two special methods: __enter__() and __exit__()

90
New cards

Printing without an automatic newline uses a named argument end

print( myString, end="" ) #end is a named parameter which defaults to newline, substitute an empty string to override the newline

How does one prevent a print statement from automatically moving to a new line?

91
New cards

Python enforces this strict parameter order in function definitions:

  1. Positional-or-keyword parameters (required first)

  2. Positional-or-keyword parameters with defaults

  3. *args (variable positional arguments)

  4. Keyword-only parameters (after a lone *)

  5. **kwargs (variable keyword arguments)

What is the required order of args, kwargs, positional-or-keyword parameters and positional-or-keyword parameters with default values?