PYTHON QUESTIONS

0.0(0)
studied byStudied by 0 people
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/20

flashcard set

Earn XP

Description and Tags

pyth

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

21 Terms

1
New cards

You develop a Python application for your company.

You need to complete the code so that the print statements are accurate.

Complete the code by selecting the correct code segment from each drop-down list

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

alphalist = ["a", "b", "c", "d", "e"]

(1) [ if numlist = alphalist: / if numlist == alphalist: / if numlist += alphalist: ]

	print("numlist are equal to alphalist")

else:

	print("the values in numlist are not equal to alphalist")

if numList == alphaList:



Given lists:

numList = [1, 2, 3, 4, 5]
alphaList = ["a", "b", "c", "d", "e"]

Goal:

Check if the two lists are equal, and print a message based on the result.


Options for line (1):

  1. if numList = alphaList:
    Incorrect= is assignment, not comparison. This will cause a SyntaxError.

  2. if numList == alphaList:
    Correct== is used to check equality of lists in Python.

  3. if numList += alphaList:
    Incorrect+= is used to extend or concatenate, not compare.
    This line also causes a SyntaxError in an if condition.


Correct answer:

(1) if numList == alphaList:


Final code:

numList = [1, 2, 3, 4, 5]
alphaList = ["a", "b", "c", "d", "e"]

if numList == alphaList:
    print("numList are equal to alphaList")
else:
    print("The values in numList are not equal to alphaList")

Explanation:

  • Python compares lists element by element using ==.

  • Since [1, 2, 3, 4, 5] is not equal to ["a", "b", "c", "d", "e"], the else branch will run.

2
New cards

You are building a Python program that displays all prime numbers from 2 to 100. (A prime number is any number that is divisible only by itself and 1.)

Complete the code by moving the appropriate code segments from the list on the left to the correct locations on the right.

Note: You will receive partial credit for each correct code placement.

  • 𝚋𝚛𝚎𝚊𝚔

  • 𝚌𝚘𝚗𝚝𝚒𝚗𝚞𝚎

  • 𝚙 = 𝚙 + 𝟷

  • 𝚙 = 𝟸

    𝚒𝚜_𝚙𝚛𝚒𝚖𝚎 = 𝚃𝚛𝚞𝚎

    𝚠𝚑𝚒𝚕𝚎 𝚙 < 𝟷𝟶𝟶:

  • 𝚙 = 𝟸

    𝚠𝚑𝚒𝚕𝚎 𝚙 <= 𝟷𝟶𝟶:

    ⇥ 𝚒𝚜_𝚙𝚛𝚒𝚖𝚎 = 𝚃𝚛𝚞𝚎

(1)
	for i in range(2, p):

		if p % i == 0:

			is_prime = false

			(2)

	if is prime == true:

		print(p)
(3)

(1) - p = 2
while p <= 100:
    is_prime = True

(2) - break

(3) - p = p + 1


p = 2
while p <= 100:
    is_prime = True

    for i in range(2, p):
        if p % i == 0:
            is_prime = False
            break                # (1)

    if is_prime == True:
        print(p)

    p = p + 1                  # (2)

Code segment placement:

  • (1) = break

    • Stops the for loop early if a divisor is found (meaning the number is not prime).

  • (2) = p = p + 1

    • Increments p to check the next number.

  • (3) = already included as p = p + 1 after the if — nothing else is needed here.


Why it works:

  • Starts from p = 2, the smallest prime.

  • For each p, checks all numbers from 2 to p-1 to see if any divide evenly.

  • If any do → is_prime = False, and we break early.

  • If none do → is_prime remains True, so we print p.

  • Then move to the next number.

This will print all prime numbers from 2 to 100 inclusive.

3
New cards

A coworker wrote a program that inputs names into a database. Unfortunately, the program reversed the letters in each name/

You need to write a Python function that outputs the characters in a name in the correct order

Complete the code by selecting the code segment from each drop-down list.

Note: You will receive partial credit for each correct selection.

#function reverses characters in a string. 
#returns new string in reversed order.
 
def reverse_name(backward_name):
	forward_name = " "
	length = (1) [ word_list in word: / word in word_list: / word == word_list: / 
								word is word list: ]

	while length >= 0:

		forward_name += (2) [ backward name[index] / backward_name[length] / 
		backward_name[length+1] / backward_name(len(backward_name)-len(forward_name)] ]
		length = length-1

	return forward_name

print (reverse_name("nohtyp"))

Drop-down answers:

  1. length = len(backward_name) - 1
    ⇨ We subtract 1 because indexing starts at 0, and we want the last index.

  2. backward_name[length]
    ⇨ We access each character starting from the end and move backwards.



Completed code:

# Function reverses characters in a string. Returns new string in reversed order.

def reverse_name(backward_name):
    forward_name = ""
    length = len(backward_name) - 1  # ← corrected here
    while length >= 0:
        forward_name += backward_name[length]
        length = length - 1
    return forward_name

print(reverse_name("nohtyp"))  # Output: python

Explanation:

  • We initialize forward_name as an empty string.

  • length is the index of the last character: len(string) - 1

  • In a while loop, we iterate from the end (length >= 0) toward the beginning.

  • We keep appending backward_name[length] to forward_name.

  • Finally, we return forward_name, which is the corrected name.

print(reverse_name("nohtyp")) correctly prints "python".

4
New cards

You are writing code to meet the following requirements:

  • Allow users to repeatedly enter words.

  • Output the number of characters in each word.

Complete the code by selecting the correct option from each drop-down list.

Note: You will receive partial credit for each correct selection.

x = "Hello"
(1) [ for / if / while ] x != "QUIT":
	num = 0
	(2) [ for / if / while '] char (3) [ and / or / in / not ] x:
		num += 1
	print(num)
	x = input("Enter a new word or QUIT to exit: ")

Correct options:

  • (1) = while
    ↳ because the loop should continue while the input is not "QUIT"

  • (2) = for
    ↳ we're iterating over each character in the string

  • (3) = in
    ↳ correct syntax is: for char in x



Final version:

x = "Hello"

while x != "QUIT":                    # (1)
    num = 0
    for char in x:                    # (2) and (3)
        num += 1
    print(num)
    x = input("Enter a new word or QUIT to exit: ")

Summary:

  • This loop keeps asking the user for a new word.

  • For each word, it counts the number of characters using a for loop.

  • If the user types "QUIT", the loop ends.

5
New cards
6
New cards

Review the following code:

x = "oranges"
y = “apples”
z = “bananas”

date = “ {1} and {0} and {2} " 
print(data.format(z, y, x))

What is the output of the print statement?

○ apples and bananas and oranges

○ bananas and oranges and apples

○ oranges and apples and bananas

○ apples and oranges and bananas

apples and bananas and oranges



format(z, y, x) assigns:

  • {0}z"bananas"

  • {1}y"apples"

  • {2}x"oranges"

So the string becomes:

arduino

CopyEdit

" apples and bananas and oranges "

Correct output:

apples and bananas and oranges

7
New cards

With the following code segment:

open("python.txt", "a")
write("This is a line of text.")
close()

Which statement about the code segment is true? Select True or False.

  1. A file named python.txt is created if it does not exist.

  2. The data in the file will be overwritten.

  3. Other code can open the file after this code runs.

  1. True

  2. False

  3. True



Let's analyze each statement based on the given code segment:

open("python.txt", "a")
write("This is a line of text.")
close()

1. A file named python.txt is created if it does not exist.

  • True

  • Explanation: Opening a file in append mode ("a") creates the file if it does not already exist.

2. The data in the file will be overwritten.

  • False

  • Explanation: Opening a file in append mode adds data to the end without overwriting existing content.

3. Other code can open the file after this code runs.

  • True (assuming the file is properly closed)

  • Explanation: After calling close(), the file is properly closed and can be accessed by other code.

8
New cards

Review the following code segment:

product = 2
n = 5

while (n != 0):
	product *= n
	print (product)
	n -= 1
	if n == 3:
		break

How many lines of output does the code print?

Enter the number as an integer: …

2



  • The variable product starts at 2, and n starts at 5.

  • The while loop runs as long as n is not 0.

  • Inside the loop, product is multiplied by n, then the new product is printed.

  • After printing, n is decreased by 1.

  • Then, if n equals 3, the loop breaks immediately.

Now, let's see what happens in each iteration:

  • First iteration:
    n is 5.
    product becomes 2 * 5 = 10.
    10 is printed.
    n is decreased to 4.
    Since n is not 3, continue.

  • Second iteration:
    n is 4.
    product becomes 10 * 4 = 40.
    40 is printed.
    n is decreased to 3.
    Now n equals 3, so the loop breaks.

The loop stops here. The third iteration never happens.

How many times did it print? Twice — for the values 10 and 40.


Answer: The code prints 2 lines.

9
New cards

You are writing a program to randomly assign rooms (room_number) and team-building groups (group) for a company retreat.

Complete the code by selecting the correct code segment from each drop-down list.

Note: You will receive partial credit for each correct selection.

import random
roomsassigned=[1]
room_number=1
grouplist [ "ropes", "rafting", "obstacle", "wellness"]
count=0
print("welcome to companypro's team-building weekend!") 
name=input("please enter your name (q to quit)?")
while name.Lower() != 'q' and count < 50:
	while room_number in rooms assigned:
		(1) [ room_number=random(1,50) / room_number=random.Randint(1,50) / room_number=random shuffle(1,50) / room number=random.Random(1,50) ]
	print(f" (name), your room number is (room_number}")
	roomsassigned.Append(room_number)
(2) [ group = random.Choice(grouplist) / group = random.Randrange(grouplist) / group = random.Shuffle(grouplist) / group = random.Sample(grouplist) ]
room number=random.Random(1,50)
print(f"you will meet with the {group} group this afternoon.")
count+=1
name=input("Please enter your name (q to quit)? ")

  • (1) → room_number = random.randint(1, 50)

  • (2) → group = random.choice(groupList)



At (1):

You want to assign a random room number between 1 and 50, and you want to use the random module to generate this.

Options:

  • room_number=random(1,50) → Incorrect, random() is not a function in the random module for this.

  • room_number=random.randint(1,50) → Correct. randint(a,b) returns an integer N such that a ≤ N ≤ b.

  • room_number=random shuffle(1,50) → Incorrect, shuffle is for lists, and syntax is wrong.

  • room number=random.random(1,50) → Incorrect, random() takes no args and returns float between 0 and 1.

Correct choice for (1):

room_number = random.randint(1, 50)

At (2):

You want to assign the user to a random group from the list groupList.

Options:

  • group = random.choice(groupList) → Correct. choice() picks one element randomly from a sequence.

  • group = random.randrange(groupList) → Incorrect, randrange() works with integers, not lists.

  • group = random.shuffle(groupList) → Incorrect, shuffle() shuffles the list in place and returns None.

  • group = random.sample(groupList) → Incorrect, sample() requires at least two arguments.

Correct choice for (2):

group = random.choice(groupList)

10
New cards

You are writing a function that increments the player score in a game.

The function has the following requirements:

  • If no value is specified for points, then points start at one

  • If bonus is True, then points must be doubled

You write the following code Line numbers are included for reference only.

01 def increment score (score, bonus, points):
02     if bonus == true:
03         points points 2
04     score = score + points
05     return score
06 points = 5
07 score = 10
08 new_score = increment_score (score, true, points)

For each statement, select True or False.

Note: You will receive partial credit for each correct selection.

  1. To meet the requirements, you must change line 01 to def increment_score(score, bonus, points = 1):

  2. If you do not change line 01 and the function is called with only two parameters, an error occurs.

  3. Line 03 will also modify the value of the vanable points declared at line 06.

Final Answers:

  1. True

  2. True

  3. False



Statement 1:

"To meet the requirements, you must change line 01 to def increment_score(score, bonus, points = 1):"

This is True.
→ The requirement says that if no value is specified for points, then points should default to 1.
→ Therefore, points must have a default parameter value in the function definition.

Answer: True


Statement 2:

"If you do not change line 01 and the function is called with only two parameters, an error occurs."

This is also True.
→ Your original function is defined like this:

def increment_score(score, bonus, points):

→ All three parameters are required here.
→ If you try to call it like increment_score(score, bonus), without the points, Python will raise a TypeError.

Answer: True


Statement 3:

"Line 03 will also modify the value of the variable points declared at line 06."

This is False.
→ The points variable on line 06 is defined in the global scope,
→ But the points inside the function is a parameter, meaning it's local to the function.

→ When you write:

points = points * 2

it only changes the local copy of points inside the function.
The global points remains unchanged.

Answer: False

11
New cards

A game development company needs a way to find the number of words in a list that contain a specific letter.

Complete the code by selecting the correct code segment from each drop-down list.

Note: You will receive partial credit for each correct selection.

#Function accepts list of words and letter to search for.

#Returns count of the number of words that contain that letter.

def count_letter(letter, word_list):
	count = 0

	for (1) [ word_list in word:  /  word in word_list:  /  word == word_list: /  word is word list  ]
		if (2)  [  word is letter:  /  letter is word:  /  word in letter:  /  letter in word:  ]
	return count

# word list is populated by the readWords() function. Code not shown. 

word_list = readWords()

letter = input("Which letter would you like to count")
letter_count = count_letter(letter, word_list)
print("There are: ", letter_count, "words that contain ", letter)

Answers:

  • (1) → word in word_list:

  • (2) → letter in word:



GOAL:

You need to count how many words in a list contain a specific letter.


Function:

def count_letter(letter, word_list):
	count = 0

	for (1) [ ??? ]
		if (2) [ ??? ]
	return count

(1) — Loop through each word in the list:

The correct option is:

  • **word in word_list:**
    ↳ because word_list is a list, and we want to loop over each word in it.


(2) — Check if letter is in the word:

The correct option is:

  • **letter in word:**
    ↳ this checks if the letter appears anywhere in the word.


Final Correct Function:

def count_letter(letter, word_list):
	count = 0
	for word in word_list:
		if letter in word:
			count += 1
	return count

12
New cards

A friend asks you to refactor and document the following Python code:

value1 = 9
value2 = 4

answer = ( value1 % value2 * 10) // 2.0 ** 3.0 + value2

You run the code.

What is the result?

○ The value 5.667 is displayed.

○ A syntax error occurs.

○ The value 5.0 is displayed.

○ The value 129 is displayed.

The value 5.0 is displayed.



🔍 Step-by-step: 1. value1 % value2

9 % 4 = 1

2. 1 * 10 = 10 3. 2.0 ** 3.0 = 8.0 4. 10 // 8.0

→ This is floor division of an int and a float
10 // 8.0 = 1.0 (still a float)

5. 1.0 + value2 = 1.0 + 4 = 5.0


Final result:

5.0

13
New cards

You find errors while evaluating the following code. Line numbers are included for reference

only.

01 numbers = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
02 index = 0
03 while (index < 10)
04     print(numbers[index])
05
06     if numbers(index) = 6
07         break
08     else:
09         index += 1

You need to correct the code at line 03 and line 06.

Evaluate the code and answer the questions by selecting the correct option from each drop- down list.

Note: You will receive partial credit for each correct selection.

  1. Which code segment should you use at line 03?

    ○ while (index <10):

    ○ while [index < 10]

    ○ while (index < 5):

    ○ while [index < 5]

  2. Which code segment should you use at line 06?

    ○ if numbers[index] == 6

    ○ if numbers[index] == 6:

    ○ if numbers(index) = 6:

    ○ if numbers[index] != 6

while (index < 10):

if numbers[index] == 6:



Which code segment should you use at line 03?

Correct answer: while (index < 10):
This uses correct syntax for a while loop in Python:
 - while keyword
 - parentheses () are optional, but acceptable
 - ends with a colon :


Which code segment should you use at line 06?

Correct answer: if numbers[index] == 6:
This is the correct way to:
 - Access an element in a list: numbers[index]
 - Compare using equality: ==
 - Include a colon : at the end


🧠 Why the other options are wrong:

  • while [index < 10] and while [index < 5] invalid syntax ([] is for lists, not conditions)

  • if numbers(index) = 6: () is function call, and = is assignment, not comparison

  • if numbers[index] == 6 valid, but missing : at the end, which is required

14
New cards

You are creating a Python program that compares numbers

You write the following code. Line numbers are included for reference only

01 num1 = eval(input ("please enter the first number: "))
02 num2 = eval(input ("please enter the second number: "))
03 if num1 == num2:
04     print("the two numbers are equal.")
05 if num1 <= num2:
06     print("number 1 is greater than number 2.")
07 if num1 > num2:
08     print("number 1 is greater than number 2.") 
09 if num2 = num1:
10     print("the two numbers are the same.")

You need to ensure that the comparisons are accurate For each statement, select True or False

Note: You will receive partial credit for each correct selection.

  1. The print statement at line 04 will print only if the two numbers are equal in value.

  2. The print statement at line 06 will print only if num1 is less than num2.

  3. The print statement at line 08 will print only if numl is greater than num2.

  4. The statement at line 09 is an invalid comparison.

Final Answers:

  1. True

  2. False

  3. True

  4. True



Statement 1:

"The print statement at line 04 will print only if the two numbers are equal in value."

True
→ Line 03 checks: if num1 == num2:
→ So line 04 will print only if the two values are equal.

Answer: True


Statement 2:

"The print statement at line 06 will print only if num1 is less than num2."

False
→ Line 05 uses: if num1 <= num2:
→ That means it prints if num1 is less than OR equal to num2.
So the statement claiming "only if less than" is incorrect.

Answer: False


Statement 3:

"The print statement at line 08 will print only if num1 is greater than num2."

True
→ Line 07 is: if num1 > num2:
→ So line 08 prints only if num1 is strictly greater than num2.

Answer: True


Statement 4:

"The statement at line 09 is an invalid comparison."

True
→ Line 09 says: if num2 = num1:
→ This uses = (assignment) instead of == (comparison),
which causes a syntax error in Python.

Answer: True

15
New cards

You work on a team that is developing a game.

You need to write code that generates a random number that meets the following requirements:

  • The number is a multiple of 5.

  • The lowest number is 5.

  • The highest number is 100.

Which two code segments will meet the requirements? Each correct answer presents a complete solution. (Choose 2)

Note: You will receive partial credit for each correct answer.

☐ 𝚏𝚛𝚘𝚖 𝚛𝚊𝚗𝚍𝚘𝚖 𝚒𝚖𝚙𝚘𝚛𝚝 𝚛𝚊𝚗𝚍𝚛𝚊𝚗𝚐𝚎

𝚙𝚛𝚒𝚗𝚝 (𝚛𝚊𝚗𝚍𝚛𝚊𝚗𝚐𝚎(𝟶, 𝟷𝟶𝟶, 𝟻))

☐ 𝚏𝚛𝚘𝚖 𝚛𝚊𝚗𝚍𝚘𝚖 𝚒𝚖𝚙𝚘𝚛𝚝 𝚛𝚊𝚗𝚍𝚛𝚊𝚗𝚐𝚎

𝚙𝚛𝚒𝚗𝚝(𝚛𝚊𝚗𝚍𝚛𝚊𝚗𝚐𝚎(𝟻, 𝟷𝟶𝟻, 𝟻))

☐ 𝚏𝚛𝚘𝚖 𝚛𝚊𝚗𝚍𝚘𝚖 𝚒𝚖𝚙𝚘𝚛𝚝 𝚛𝚊𝚗𝚍𝚒𝚗𝚝

𝚙𝚛𝚒𝚗𝚝 (𝚛𝚊𝚗𝚍𝚒𝚗𝚝(𝟷, 𝟸𝟶) 𝟻)

☐ 𝚏𝚛𝚘𝚖 𝚛𝚊𝚗𝚍𝚘𝚖 𝚒𝚖𝚙𝚘𝚛𝚝 𝚛𝚊𝚗𝚍𝚒𝚗𝚝

𝚙𝚛𝚒𝚗𝚝(𝚛𝚊𝚗𝚍𝚒𝚗𝚝(𝟶, 𝟸𝟶) = 𝟻)

Final correct answers:

  • Option 1: randrange(5, 105, 5)

  • Option 3: randint(1, 20) * 5



The correct code must generate a random number that:

  • Is a multiple of 5

  • Starts at 5

  • Ends at 100

  • And includes both 5 and 100

Let’s evaluate each option:


Option 1:

from random import randrange
print(randrange(5, 105, 5))
  • Starts at 5

  • Ends before 105 (i.e. max = 100 included)

  • Step of 5 (only multiples of 5)
    Correct


Option 2:

from random import randrange
print(randrange(0, 100, 5))
  • Starts at 0 (violates "lowest number is 5")

  • Step of 5

  • Up to but not including 100
    Incorrect


Option 3:

from random import randint
print(randint(1, 20) * 5)
  • randint(1, 20) → values from 1 to 20

  • Multiply by 5 → results from 5 to 100

  • All values are multiples of 5
    Correct


Option 4:

from random import randint
print(randint(0, 20) = 5)
  • Syntax error: = is assignment, not valid in print()
    Incorrect

16
New cards

You are writing a Python program to determine if a number (num) the user inputs is one, two, or more than two digits (digits).

Complete the code by selecting the correct code segment from each drop-down list.

𝚗𝚞𝚖 = 𝚒𝚗𝚝(𝚒𝚗𝚙𝚞𝚝("𝙴𝚗𝚝𝚎𝚛 𝚊 𝚗𝚞𝚖𝚋𝚎𝚛 𝚠𝚒𝚝𝚑 𝟷 𝚘𝚛 𝟸 𝚍𝚒𝚐𝚒𝚝𝚜: "))

𝚍𝚒𝚐𝚒𝚝𝚜 = "𝟶"

(𝟷) [ 𝚒𝚏 𝚗𝚞𝚖 > -𝟷𝟶 𝚊𝚗𝚍 𝚗𝚞𝚖 < 𝟷𝟶: / 𝚒𝚏 𝚗𝚞𝚖 > -𝟷𝟶𝟶 𝚊𝚗𝚍 𝚗𝚞𝚖 < 𝟷𝟶𝟶: ]

	𝚍𝚒𝚐𝚒𝚝𝚜 = “𝟷”

(𝟸) [ 𝚒𝚏 𝚗𝚞𝚖 > -𝟷𝟶𝟶 𝚊𝚗𝚍 𝚗𝚞𝚖 < 𝟷𝟶𝟶: / 𝚎𝚕𝚒𝚏 𝚗𝚞𝚖 > -𝟷𝟶𝟶 𝚊𝚗𝚍 𝚗𝚞𝚖 < 𝟷𝟶𝟶: / 𝚒𝚏 𝚗𝚞𝚖 > -𝟷𝟶 𝚊𝚗𝚍 𝚗𝚞𝚖 < 𝟷𝟶: / 𝚎𝚕𝚒𝚏 𝚗𝚞𝚖>-𝟷𝟶 𝚊𝚗𝚍 𝚗𝚞𝚖 < 𝟷𝟶: ]

	𝚍𝚒𝚐𝚒𝚝𝚜= "𝟸"

(𝟹) [ 𝚎𝚕𝚜𝚎 / 𝚎𝚕𝚒𝚏 ]

	𝚍𝚒𝚐𝚒𝚝𝚜= ">𝟸"

𝚙𝚛𝚒𝚗𝚝(𝚍𝚒𝚐𝚒𝚝𝚜 + " 𝚍𝚒𝚐𝚒𝚝𝚜.")

(1) - if num > -10 and num < 10:
(2) - elif num > -100 and num < 100:
(3) - else


num = int(input("Enter a number with 1 or 2 digits: "))
digits = "0"

(1) First condition:

We want to check if num has only 1 digit, including negative values like -9.

So the range must be from -9 to 9, i.e., -10 < num < 10.

Best choice:

if num > -10 and num < 10:

Then:

digits = "1"

(2) Second condition:

We want to check if num has 2 digits. That’s when num is between -99 and -10, or 10 and 99.

But since we already handled the one-digit case, we can now check for two-digit values only.

Best choice:

elif num > -100 and num < 100:

Then:

    digits = "2"

(3) Else:

Any number outside the range -99 to 99 has more than 2 digits.

Best choice:

else:

Then:

    digits = ">2"

Final completed code:

num = int(input("Enter a number with 1 or 2 digits: "))
digits = "0"

if num > -10 and num < 10:
    digits = "1"
elif num > -100 and num < 100:
    digits = "2"
else:
    digits = ">2"

print(digits + " digits.")

17
New cards

The Script.py file contains the following code:

import sys
print(sys.Argv[2])

You run the following command.

python script.py cheese bacon bread

What is the output of the command?

○ Bread

○ Cheese

○ Bacon

○ Script.py

Correct answer:

○ Bacon



📜 Code in Script.py:

import sys
print(sys.argv[2])

Run command:

python Script.py Cheese Bacon Bread

🔢 What sys.argv contains:

sys.argv is a list where:

  • sys.argv[0]"Script.py"

  • sys.argv[1]"Cheese"

  • sys.argv[2]"Bacon"

  • sys.argv[3]"Bread"


So, sys.argv[2] = "Bacon"

18
New cards

You are creating a function to calculate admission fees (admission fee) based on the following rules:

  • Anyone under age 5= free admission

  • Anyone age 5 or older who is in school = $10

  • Anyone age 5 to 17 who is not in school = $20

  • Anyone older than age 17 who is not in school = $50

Rate represents the price in dollars.

Complete the code by selecting the correct code segment from each drop-down list.

def admission fee (age, school):
	rate = 0
	(1) [ if age >= 5 and school == true: / if age >= 5 and age <=17: / if age >= 5 and school == false: ]
		rate = 10
	(2) [ elif age >= 5 and school == false: / else age >= 5 and school == false: / elif age >= 5 and school == true: ]
		(3) [ if age >= 5 and school == true: / if age >= 5 and school == false: / if age <=17 ]
			rate = 20
		else:
			rate = 50
return rate

Complete answer (dropdown replacements):

  • (1)if age >= 5 and school == True:

  • (2)elif age >= 5 and school == False:

  • (3)if age <= 17



🧠 Explanation:

Let's break down the logic from the requirements:


🔹 Rule 1: Anyone under age 5 = free admission

➤ We don't need a separate if for this — the default rate = 0 at the top covers it if no other condition matches.


🔹 Rule 2: Age 5 or older, in school$10

if age >= 5 and school == True:rate = 10


🔹 Rule 3: Age 5 to 17, not in school$20

elif age >= 5 and school == False:
   then inside it: if age <= 17:rate = 20


🔹 Rule 4: Age over 17, not in school$50

➤ still inside the elif, use else:rate = 50


Final working structure:

def admission_fee(age, school):
    rate = 0
    if age >= 5 and school == True:
        rate = 10
    elif age >= 5 and school == False:
        if age <= 17:
            rate = 20
        else:
            rate = 50
    return rate

19
New cards
20
New cards

You need to identify the data types of various type operations.

Move the appropriate data types from the list on the left to the correct operations on the right. You may use each other type once, more than once or not at all.

Note: You will receive partial credit for each correct match.

1) 𝚒𝚗𝚝

2) 𝚏𝚕𝚘𝚊𝚝

3) 𝚜𝚝𝚛

4) 𝚋𝚘𝚘𝚕

a) 𝚝𝚢𝚙𝚎(+𝟷𝙴𝟷𝟶)

b) 𝚝𝚢𝚙𝚎(𝟻.𝟶)

c) 𝚝𝚢𝚙𝚎(“𝚃𝚛𝚞𝚎“)

d) 𝚝𝚢𝚙𝚎(𝙵𝚊𝚕𝚜𝚎)

1) + a) = 𝚏𝚕𝚘𝚊𝚝 – 𝚝𝚢𝚙𝚎(+𝟷𝙴𝟷𝟶)
2) + b) = 𝚏𝚕𝚘𝚊𝚝 – 𝚝𝚢𝚙𝚎(𝟻.𝟶)
3) + c) = 𝚜𝚝𝚛 – 𝚝𝚢𝚙𝚎("𝚃𝚛𝚞𝚎")
4) + d) = 𝚋𝚘𝚘𝚕 – 𝚝𝚢𝚙𝚎(𝙵𝚊𝚕𝚜𝚎)


1) + a) = float – type(+1E10)
+1E10 is scientific notation for the number 10,000,000,000.0
➤ In Python, numbers written in exponential form (like 1E10) are automatically treated as floats, not ints.
type(+1E10) returns <class 'float'>


2) + b) = float – type(5.0)
5.0 has a decimal point, so it's clearly a float, even though it represents a whole number.
type(5.0) returns <class 'float'>


3) + c) = str – type("True")
"True" is enclosed in quotes, so it's a string, not a boolean.
➤ Even though it looks like the boolean value True, Python sees it as text.
type("True") returns <class 'str'>


4) + d) = bool – type(False)
False (without quotes) is one of the two boolean values in Python.
type(False) returns <class 'bool'>

21
New cards

You need to identify the results of performing vanous slicing operations on the following sequence structure.

alph = “abcdefghijklmnopqrstuvwxyz"

Move the appropriate results from the list on the left to the correct slicing operations on the right. You may use each result once, more than once or not at all.

Note: You will receive partial credit for each correct match.

1) 𝚊𝚕𝚙𝚑[𝟹:𝟼]

2) 𝚊𝚕𝚙𝚑[:𝟼]

a) 𝚍𝚎𝚏

b) 𝚊𝚋𝚌𝚍𝚎𝚏

c) 𝚌𝚍𝚎

d) 𝚍𝚎𝚏𝚐

e) 𝚌𝚍𝚎𝚏

f) 𝚊𝚋𝚌𝚍𝚎

Final answers:

  • alph[3:6] a) def

  • alph[:6] b) abcdef



Let's break down each slicing operation based on:

alph = "abcdefghijklmnopqrstuvwxyz"

1) alph[3:6]

– Index 3 = 'd'
– Index 6 (stop) = not included, so we go up to index 5: 'f'
→ So this slice is: 'd', 'e', 'f'
Result: def


2) alph[:6]

– Start is omitted → starts at index 0 ('a')
– Ends at index 5 ('f'), since 6 is not included
→ Slice: 'a', 'b', 'c', 'd', 'e', 'f'
Result: abcdef