Python Data Types and Variables Quiz

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

What will be the output of the following code? print(1+1)

2

What will be the output of the following code? print(str(1)+str(1))

11

What will be the output of the following code? print("Hello"*2)

HelloHello

What does the following code print? foo = 20 bar = foo*2 print (bar)

<p>40</p> Signup and view all the answers

Is this code equivalent to the code above? foo = 20 print (foo*2)

<p>True (A)</p> Signup and view all the answers

Is there anything wrong with this code? foo = 20 print(int(foo)*2)

<p>False (B)</p> Signup and view all the answers

Is there anything wrong with the code below? Will it run? Will the answer be logically correct? # double the user's input myInput = input("Please input a number here: ") print (myInput*2)

<p>True (A)</p> Signup and view all the answers

What is the output of the following code? a = 25 b = False if (a < 25) or (not b): b = not b elif (a >= 25) and b: a /= 5 else: a += 7 b = False print(f"{a}: {b}")

<p>25: False</p> Signup and view all the answers

Are the following two functions ______?

<p>equivalent</p> Signup and view all the answers

What is the difference between the two functions below? def baz(x): return 2*x def qux(x): print(2*x)

<p>The function <code>baz(x)</code> returns the result of <code>2*x</code> to the caller, while <code>qux(x)</code> only prints the result without returning a value.</p> Signup and view all the answers

Using the same function definitions as above, identify the problem in the following code. Will it run? Will the results be what you expect? Why or why not? a = baz (3) b = qux (3) print(a) print(b)

<p>True (A)</p> Signup and view all the answers

Identify the problem in the following piece of code. def myFunc(x): int(input("Input any number.")) x = if x > 10: return True return False

<p>The code does not correctly assign the user input to the variable <code>x</code>. It's missing an assignment statement. This will result in a TypeError because the <code>if</code> statement then tries to compare the variable <code>x</code> to 10, without <code>x</code> having been assigned a value.</p> Signup and view all the answers

Write a function that takes a numeric value x (int), as well as an integer n, and uses a looping structure to return the exponent x^n.

<pre><code class="language-python">def exponent(x, n): result = 1 for i in range(n): result *= x return result </code></pre> Signup and view all the answers

Write a function that takes a list as an argument to find the sum of all elements in the list using a looping structure.

<pre><code class="language-python">def sumList(lst): sum = 0 for element in lst: sum += element return sum </code></pre> Signup and view all the answers

Write a function that takes a list as an argument and returns a new list that removes all duplicates in the list.

<pre><code class="language-python">def uniqueList(lst): unique_list = [] for element in lst: if element not in unique_list: unique_list.append(element) return unique_list </code></pre> Signup and view all the answers

Trace through the code manually to predict what will happen when the code is executed. Then, convert the code snippet into Python code to verify your answers. a = [] for i in range(50): a.append(i) print(a)

<p>The code initializes an empty list as <code>a</code> and then appends the integers from 0 to 49 to this list. Finally, it'll print the entire list <code>a</code> with all the elements.</p> Signup and view all the answers

What is the output of the code snippet for i in range(5): a.pop(i) print(f"after pop", a)

<p>The code will produce an <code>IndexError: pop index out of range</code> error.</p> Signup and view all the answers

What is the output of the code snippet for i in range(5): a.remove(a[i]) print(f"after remove a[i]", a)

<p>The output of the code snippet will be <code>after remove a[i] [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49]</code></p> Signup and view all the answers

What is the output of the code snippet b=a[:] for i in range(5): a.remove(b[i]) print(f"after remove b[i]",a)

<p>The code snippet will produce a TypeError: list indices must be integers, not str. The error occurs in the line <code>a.remove(b[i])</code>.</p> Signup and view all the answers

Write a function that returns a N-by-N 2-D list of randomly generated numbers between 0 and 100. Take n as an argument to your function.

<pre><code class="language-python">import random def create_2d_list(n): grid = [] for i in range(n): row = [random.randint(0, 100) for _ in range(n)] grid.append(row) return grid </code></pre> Signup and view all the answers

Then, write a function to print this 2-D list, line by line, as a string. The function must be counter-controlled. The functions must take two arguments: grid (your 2-D list) and n (the size of your list.)

<pre><code class="language-python">def print_2d_list(grid, n): for i in range(n): for j in range(n): print(grid[i][j], end=' ') # print elements of the row separated by space print() # print new line after each row </code></pre> Signup and view all the answers

Consider the following code: myDict = {} for i in range (1,5): myDict[i] = i*2 for key in myDict: print(f"{key}: {myDict[key]}") Bob says: I believe this code will print out "1:2, 2:4, 3:6, 4:8, 5:10", in that order, all on new lines. However, Alice disagrees. Who is correct? If Alice is correct, what are the reasons Bob is wrong?

<p>Alice is correct. Bob is wrong because the output of the given code will be:</p> <pre><code>1: 2 2: 4 3: 6 4: 8 </code></pre> Signup and view all the answers

Assume that the userCart variable is a list of strings representing the items in the user's cart. For example, ["banana", "apple", "bacon", "apple"] is a valid shopping cart. Write a function, receipt(userCart), to calculate the total cost of a user's cart and print a nicely formatted receipt.

<p>True (A)</p> Signup and view all the answers

We will calculate the sum of a list of numbers recursively. However, we will trace the steps to solve this by hand. You may also implement the code if you wish. Complete the following trace: sum([5,6,2,8,9])

<pre><code>sum([5,6,2,8,9]) 5 + (sum([6,2,8,9])) 5 + (6 + (sum([2,8,9]))) 5 + (6 + (2 + (sum([8, 9])))) 5 + (6 + (2 + (8 + (sum([9]))))) 5 + (6 + (2 + (8 + (9)))) 5 + (6 + (2 + (17))) 5 + (6 + (19)) 5 + (25) 30 </code></pre> Signup and view all the answers

Now, we will do the same for the product of a list of numbers. prod([10,9,6,4,2]) # Complete this line as well

<pre><code>prod([10,9,6,4,2]) 10 * (prod([9, 6, 4, 2])) </code></pre> Signup and view all the answers

We define n!=n*(n-1)(n-2)...21. 1. What is the base case? 2. What is the recursive case? 3. Write the code to define the recursive function fact(n).

<ol> <li>The base case is when n is equal to 0. In this case, the factorial of 0 is 1. 2. The recursive case is when n is greater than 0. In this case, the factorial of n is calculated by multiplying n by the factorial of (n-1). 3. ```python def fact(n): if n == 0: return 1 else: return n * fact(n-1)</li> </ol> <pre><code></code></pre> Signup and view all the answers

What will happen when this function is run? def myFunc(x): return x + myFunc(x-1)

<p>The function will produce a RecursionError: maximum recursion depth exceeded in comparison.</p> Signup and view all the answers

What will happen when this function is run? def myFunc(x): if x == 0: return x print(myFunc(x-1))

<p>The function will result in a Stack Overflow error due to infinitely calling the function.</p> Signup and view all the answers

What will each line of the following code print? print(1+1)

<p>2</p> Signup and view all the answers

What will each line of the following code print? print(str(1)+str(1))

<p>11</p> Signup and view all the answers

What will each line of the following code print? print("Hello"*2)

<p>HelloHello</p> Signup and view all the answers

Are the following two functions equivalent? def foo(x): myVar = 2*x return myVar def bar(x): return 2*x

<p>Yes, these functions are equivalent.</p> Signup and view all the answers

Flashcards

String Concatenation

The + operator concatenates strings, not performing arithmetic addition.

Converting Integer to String

The str() function converts an integer to a string, allowing concatenation with other strings.

String Replication

Multiplying a string by an integer repeats the string that many times.

Variables in Programming

Variables store values in a program.

Signup and view all the flashcards

Assignment Operator

The = operator assigns a value to a variable.

Signup and view all the flashcards

User Input

The input() function takes user input from the console.

Signup and view all the flashcards

Converting String to Integer

The int() function converts a string to an integer.

Signup and view all the flashcards

Conditional Statement

The if statement controls code execution based on a condition.

Signup and view all the flashcards

Elif Statement

The elif statement is used for multiple conditions, executed if the previous if or elif conditions are false.

Signup and view all the flashcards

Else Statement

The else statement executes code when the previous if and elif conditions are all false.

Signup and view all the flashcards

Not Operator

The not operator inverts the truth value of a boolean expression.

Signup and view all the flashcards

For Loop

The for loop iterates through a sequence of elements.

Signup and view all the flashcards

Functions

Functions are reusable blocks of code that can be called multiple times.

Signup and view all the flashcards

Function Parameters

Parameters are variables passed into functions.

Signup and view all the flashcards

Return Statement

The return statement sends a value back from a function.

Signup and view all the flashcards

Lists

Lists are ordered collections of elements.

Signup and view all the flashcards

Dictionaries

Dictionaries are unordered collections of key-value pairs.

Signup and view all the flashcards

Recursion

Recursion is a technique where a function calls itself within its own definition.

Signup and view all the flashcards

Classes

Classes are blueprints for creating objects.

Signup and view all the flashcards

Objects

Objects are instances of classes, having attributes and methods.

Signup and view all the flashcards

Object Attributes

Attributes are variables that belong to an object.

Signup and view all the flashcards

Object Methods

Methods are functions that belong to an object.

Signup and view all the flashcards

Files

Files are stored on a computer and can be accessed using file I/O.

Signup and view all the flashcards

File Modes

File modes specify how a file will be opened.

Signup and view all the flashcards

Debugging

Debugging is the process of finding and fixing errors in code.

Signup and view all the flashcards

Try-Except Block

The try-except block handles exceptions or errors in code.

Signup and view all the flashcards

Searching Algorithms

Searching algorithms find specific elements within a data structure.

Signup and view all the flashcards

Sorting Algorithms

Sorting algorithms arrange elements in a specific order.

Signup and view all the flashcards

Binary Search

Binary search is a fast searching algorithm that works on sorted data.

Signup and view all the flashcards

Study Notes

Data Types

  • Code will print the results of arithmetic and string operations
  • print(1 + 1) will print 2
  • print(str(1) + str(1)) will print "11"
  • print(str(1) + 1) will result in an error because you can't add a string to an integer
  • print("Hello" * 2) will print "HelloHello"
  • print("Hello" + 3) will result in an error because you can't add a string to an integer

Variables

  • Code will calculate and print the value of bar.
  • foo is assigned the integer value 20
  • bar will store the result of multiplying foo by 2. Thus bar would be 40
  • Code will print the value stored in bar, which is 40
  • Alternative code that print(foo * 2) does the same operation without the extra variable bar
  • Third code, print(int(foo) *2) , does the same as foo * 2

User Input

  • Code takes user input and doubles it.
  • Code attempts to multiply string (myInput) by 2.
  • String multiplication does not apply directly, leading to an error
  • Input must be cast to an integer.

Branching Control Structures

  • Code uses if, elif, and else statements to conditionally execute code.
  • a is assigned the value 25
  • b is assigned the value False.
  • Code will print the value of aand b determined from conditional statement if-else tree
  • if a < 25 or not b is true, then b is set to not b, or true.
  • if a >= 25 and b is true, then a is divided by 5.
  • otherwise a is increased by 7.
  • Values are printed (a ,b)

Looping Control Structures - Fizz Buzz

  • Code prints numbers from 1 to 100
  • Replaces multiples of 3 with "fizz"
  • Replaces multiples of 5 with "buzz"
  • Replaces multiples of 3 and 5 with "fizzbuzz"
  • Output matches the example in each case

Functions

  • foo and bar functions are equivalent because they do the same calculation.
  • baz returns a value, while qux prints the result. The functions are not equivalent.
  • Code assigns value 6 to a and prints to console a, qux(3) prints 6 for b to the console
  • myFunc(x) Code will print an error or fail to complete. It asks for input to assign to x

Data Structures - Lists

  • SumList function calculates the sum of elements in a list using a loop.
  • UniqueList function creates a new list that removes duplicate elements.
  • Code creates a list of the numbers 0 through 49

Data Structures - Dictionaries

  • Code creates a dictionary, myDict.
  • Dictionary keys are numbers 1 through 4.
  • Values are twice the key.
  • Code prints each key-value pair .
  • Bob is incorrect .Output is "1: 2", "2: 4", "3: 6", "4: 8"

Recursion

  • Function calculates the initial number of peaches
  • Recursively calls itself with one fewer day to determine how many peaches have been accumulated at the previous day.
  • Calculates the number of peaches by multiplying the peaches at the previous day.
  • This recursive formula can be used to create a closed form solution, determining the initial day's peach count

Objects & Classes

  • Class describes a generic animal
  • Attributes are species, size, sound, and isHungry.
  • __init__ method handles initialization; getSize,makeNoise, and feed methods handle specific animal actions.

File I/O

  • 'r' mode opens a file for reading
  • 'w' mode opens a file for writing (truncating the file if it exists)
  • 'a' opens a file for appending

Debugging

  • try-except blocks allow handling potential errors
  • try block executes the possibly problematic code
  • except block executes only if the error occurs

Searching

  • Two types of search algorithms (sequential, binary search) discussed.
  • Binary search is usually faster for sorted lists.
  • It will not work on an unsorted list

Sorting

  • Merge sort is often faster for larger lists than selection or bubble sort due to more efficient divide and conquer approach.

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Python Data Types and Variables
31 questions
Python Data Types and Variables Quiz
45 questions
Python Data Types and Variables
3 questions
Use Quizgecko on...
Browser
Browser