CSE 1321 Lecture Test 2 Topics

0.0(0)
studied byStudied by 0 people
0.0(0)
full-widthCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/55

flashcard set

Earn XP

Description and Tags

These flashcards cover essential topics from the CSE 1321 Lecture notes to aid in exam preparation.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

56 Terms

1
New cards

What is the primary difference between mutable and immutable data types in Python? Provide an example of each.

Mutable data types can be changed after they are created (e.g., lists, dictionaries, sets). Immutable data types cannot be changed after creation; any modification creates a new object (e.g., integers, floats, strings, tuples).

2
New cards

What is the output of the following Python code?

print(10 + 5 * 2 - 3)

17

3
New cards

What is the output of the following Python code?

data = [10, 20, 30, 40, 50, 60]
print(data[::2])
[10, 30, 50]
4
New cards

What is the output of the following Python code?

d = {'x': 10, 'y': 20}
d.update({'z': 30, 'x': 15})
print(d['x'])
15
5
New cards

What is the output of the following Python code?

a = True
b = False
c = True
print(a and not b or c)
True
6
New cards

What is the output of the following Python code?

def calculate(x, y=5):
    return x * y
print(calculate(3, 2))
print(calculate(4))
6
20
7
New cards

What will happen when the following Python code is executed?

message = "Hello"
print(massage)

This code will raise a NameError because massage is not defined. It should be message.

NameError: name 'massage' is not defined
8
New cards

What will happen when the following Python code is executed?

my_list = [10, 20]
print(my_list[len(my_list)])

This code will raise an IndexError because list indices are 0-based, so len(my_list) (which is 2) is out of bounds for a list of size 2 (valid indices are 0 and 1).

IndexError: list index out of range
9
New cards

What will happen when the following Python code is executed?

print("Number: " + 123)

This code will raise a TypeError because you cannot concatenate a string with an integer directly. The integer 123 would need to be converted to a string first.

TypeError: can only concatenate str (not "int") to str
10
New cards

What is the output of the following Python code?

price = 25.50
quantity = 3
print(f"Total: ${price * quantity:.2f}")
Total: $76.50
11
New cards

What is the output of the following Python code?

cubes = [x**3 for x in range(3)]
print(cubes)
[0, 1, 8]
12
New cards

What is the output of the following Python code?

coords = (1, 2, 3)
x, y, z = coords
print(y)
2
13
New cards

What is the output of the following Python code?

i = 0
while i < 5:
    if i == 3:
        break
    print(i, end=' ')
    i += 1
0 1 2
14
New cards

What will happen when the following Python code is executed?

if True
    print("Condition met")

This code will raise a SyntaxError because an if statement requires a colon (:) at the end of the condition.

SyntaxError: expected ':'
15
New cards

What will happen when the following Python code is executed?

def example_func():
 print("Hello")
  print("World")
example_func()

This code will raise an IndentationError because the lines inside the function have inconsistent indentation. Python requires consistent indentation to define code blocks.

IndentationError: unexpected indent
16
New cards

What is the output of the following Python code?

person = {'name': 'Charlie', 'age': 28, 'city': 'NY'}
print(person.get('country', 'USA'))
USA
17
New cards

Explain the significance of the __init__ method in Python classes.

The __init__ method is a special method (constructor) in Python classes. It is automatically called when a new instance of the class is created. Its primary purpose is to initialize the attributes (data) of the newly created object.

18
New cards

What is the output of the following Python code?

x = 100
def func():
    global x
    x = 200
func()
print(x)
200
19
New cards

What will happen when the following Python code is executed?

val = 5
def add_val():
    val += 10
    print(val)
add_val()

This code will raise an UnboundLocalError. Inside the add_val function, val is treated as a local variable because of the assignment val += 10. However, it's used (val + 10) before it has been assigned a value within the local scope, hence the error.

UnboundLocalError: local variable 'val' referenced before assignment
20
New cards

What is the output of the following Python code?

for i in range(3):
    if i == 1:
        continue
    print(i, end=' ')
else:
    print("Loop finished")
0 2 Loop finished
21
New cards

What is the output of the following Python code?

print(10 % -3)
-2
22
New cards

What will happen when the following Python code is executed?

my_data = {'id': 101, 'name': 'Dan'}
print(my_data['major'])

This code will raise a KeyError because the key 'major' does not exist in the my_data dictionary.

KeyError: 'major'
23
New cards

What is the output of the following Python code?

a = [1]
b = [1]
print(a is b)
False
24
New cards

Describe the short-circuit evaluation of and and or logical operators in Python.

For A and B, if A is false, B is not evaluated (short-circuited), and the expression returns A. For A or B, if A is true, B is not evaluated (short-circuited), and the expression returns A. This behavior affects performance and potential side effects.

25
New cards

What is the behavior of the following Python code?

x = 5
while x > 0:
    print(x)
    # Missing x -= 1

This code will result in an infinite loop, continuously printing 5, because the value of x is never decremented, so the condition x &gt; 0 always remains True.

(Infinite loop printing 5)
26
New cards

What is the output of the following Python code?

if (length := len("Python Programming")) > 10:
    print(f"The string is long: {length} chars")
else:
    print("The string is short")
The string is long: 18 chars
27
New cards

What is the output of the following Python code?

subtract = lambda x, y: x - y
print(subtract(10, 4))
6
28
New cards

In Python, what is the purpose of positional arguments versus keyword arguments when calling a function?

Positional arguments are assigned to parameters based on their order in the function call. Keyword arguments are assigned to parameters based on their name, allowing their order to be flexible and improving readability, especially for functions with many parameters or optional ones.

29
New cards

What is the output of the following Python code?

data_str = "apple,banana,cherry"
fruits = data_str.split(',')
print(" ".join(fruits))
apple banana cherry
30
New cards

What will happen when the following Python code is executed?

my_tuple = (10, 20, 30)
my_tuple[1] = 25

This code will raise a TypeError because tuples are immutable, meaning their elements cannot be changed after creation.

TypeError: 'tuple' object does not support item assignment
31
New cards

What problem does a KeyError typically signal in Python, and how can it often be safely handled?

A KeyError signals an attempt to access a dictionary key that does not exist. It can be safely handled using the dict.get(key, default_value) method, which returns None or a specified default if the key is not found, or by using a try-except block around the dictionary access.

32
New cards

What is the output of the following Python code?

result1 = 9 / 2
result2 = 9 // 2
print(f"{result1} {result2}")
4.5 4
33
New cards

What is the main difference between call-by-value and call-by-reference in general programming, and which one does Python primarily use for object arguments?

Call-by-value passes a copy of the argument's value, so changes to the parameter inside the function do not affect the original argument. Call-by-reference passes the argument's memory address, allowing the function to modify the original argument. Python uses a mechanism often called 'call-by-object-reference' or 'call-by-sharing', meaning it passes a copy of the reference to the object. If the object is mutable, changes made through the reference inside the function will affect the original object outside.

34
New cards

What is the output of the following Python code?

count = 0
for char in "Python":
    if char == 'o':
        count += 1
print(count)
1
35
New cards

What is the purpose of a docstring in Python?

A docstring (documentation string) is a multi-line string used to explain what a Python module, function, class, or method does. It is defined as the first statement of these blocks and can be accessed using __doc__ attribute or help() function.

36
New cards

What is the output of the following Python code?

list1 = [1, 2, 3]
list2 = list1
list2.append(4)
print(list1)
[1, 2, 3, 4]
37
New cards

What is the primary use case for Python's try-except block?

The try-except block is used for error handling. It allows you to 'try' a block of code, and if an error (exception) occurs, the 'except' block will execute, preventing the program from crashing and allowing for graceful error recovery.

38
New cards

What is the output of the following Python code?

text = "Hello, World!"
print(text[7:12])
World
39
New cards

What will happen when the following Python code is executed?

import math
print(math.sqrt(-1))

This code will raise a ValueError because the math.sqrt() function does not support negative numbers (it is designed for real numbers only). For complex numbers, you would typically use Python's cmath module.

ValueError: math domain error
40
New cards

In Python, what is a global keyword used for?

The global keyword is used inside a function to declare that a variable refers to a global variable rather than a local one. This allows a function to modify a global variable defined outside its scope.

41
New cards

What is the output of the following Python code?

numbers = {5, 2, 8, 2, 5}
print(len(numbers))
3
42
New cards

Explain the difference between list.append() and list.extend() in Python.

list.append(element) adds a single element to the end of the list. list.extend(iterable) iterates over an iterable (like another list or tuple) and adds each of its elements to the end of the current list.

43
New cards

What will happen when the following Python code is executed?

def greet(name, greeting='Hello'):
    print(f"{greeting}, {name}!")
greet(greeting='Hi', 'Alice')

This code will raise a SyntaxError. Once a keyword argument is used in a function call (e.g., greeting='Hi'), all subsequent arguments must also be keyword arguments.

SyntaxError: positional argument follows keyword argument
44
New cards

What is the output of the following Python code?

"Hello".replace("l", "X", 1)
'HeXlo'
45
New cards

How do you define a single-line comment and a multi-line comment in Python?

Single-line comments start with a hash symbol (#). Multi-line comments are typically achieved by enclosing text within triple quotes ('''text''' or """text"""), although these are technically multi-line string literals that are ignored if not assigned to a variable.

46
New cards

What is the output of the following Python code?

x = 10
y = "20"
print(str(x) + y)
1020
47
New cards

What is the purpose of the pass statement in Python?

The pass statement is a null operation; nothing happens when it executes. It is used as a placeholder where a statement is syntactically required but you don't want any code to execute, for example, in an empty function or class definition.

48
New cards

What is the output of the following Python code?

items = ["apple", "banana", "cherry"]
print("banana" in items and "grape" not in items)
True
49
New cards

What is the output of the following Python code?

counter = 0
while counter < 5:
    counter += 1
    if counter % 2 == 0:
        continue
    print(counter)
1
3
5
50
New cards

What is a TypeError in Python, and what often causes it?

A TypeError is an exception raised when an operation or function is applied to an object of an inappropriate type. It's often caused by attempting to perform an operation (like concatenation, arithmetic, or calling a method) on data types that don't support it (e.g., adding a string to an integer, or trying to use list methods on a tuple).

51
New cards

What is the output of the following Python code?

data = [1, 2, 3]
data.insert(1, 4)
print(data)
[1, 4, 2, 3]
52
New cards

What is the output of the following Python code?

def power(base, exp=2):
    return base ** exp
print(power(3, 3))
print(power(4))
27
16
53
New cards

What is a list comprehension in Python, and why is it used?

A list comprehension is a concise way to create new lists from existing iterables. It offers a more readable and often more efficient alternative to for loops and lambda functions for creating lists based on some transformation or filtering condition. Its syntax is [expression for item in iterable if condition].

54
New cards

What will happen when the following Python code is executed?

for i in range(5):
print(i)

This code will raise an IndentationError because the print(i) statement is not indented correctly within the for loop, which expects an indented block of code.

IndentationError: expected an indented block
55
New cards

What is the output of the following Python code?

matrix = [[1, 2], [3, 4]]
print(matrix[1][0])
3
56
New cards

What is the purpose of the return statement in a Python function?

The return statement is used to exit a function and send a value or set of values back to the caller. If no value is specified, or if return is omitted, the function implicitly returns None.