Python Exam 1

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

How many syntax errors are there in the following code? if totalSales>= 700000: print("Gold Customer") elif totalSales >= 400000: print("Silver Customer") elif totalSales >= 100000 and newCustomer: print("Bronze Customer and first-time prize winner") elif totalSales >= 100000 print("Bronze Customer") prnit("Thank you for your business")

3

Which variable names reflect an improper variable name declaration? choose two answers. last Name lastName last_Name last-name

last Name last-name

Evaluate the following statement and replace the underlined part with the correct statement or, if the original statement is true, indicate as such. In error handling, the else clause is optional and must come right after the except clause. the statement is correct as is is required and does not need to come right after is optional and does not need to come right after is required and must come right after

the statement is correct as is

From this code example: pieces = ["king", "queen","rook","bishop","knight","pawn"] pieces.sort() Which two commands will display the rook? print(pieces[3]) print(pieces[-1]) print(pieces[5]) print(pieces[6])

print(pieces[-1]) print(pieces[5])

-It's name is calcSubtotal -The function takes an amount and a sales tax rate and calculates a subtotal -The new subtotal is returned Choose One... calcSubtotal def calcSubtotal function calcSubtotal Choose One... () (): (amount, salesTaxRate)(amount, salesTaxRate): subtotal = amount * (1 + salesTaxRate) Choose One... return return amount return subtotal return calcSubtotal

def calcSubtotal (amount, salesTaxRate): subtotal = amount * (1 + salesTaxRate) return subtotal

price = 18.00 product = "Yellow Golf Balls"print(product [ Choose One... , + & | ] " are on sale for " [ Choose One... , + & | ] price ".")

price = 18.00 product = "Yellow Golf Balls"print(product [,] " are on sale for " [ , ] price ".")

convert the price variable to a value of 19. inventoryCount = 19.95print("We have " __________ rnd int round ceil (inventoryCount)" complete units in stock.")

inventoryCount = 19.95print("We have " int (inventoryCount)" complete units in stock.")

In the following code example, select the snippet of code that will tell python to read and print just the first line of the text file being opened. workFile = open('work.txt', 'r')workFileFirstLine = Choose One... workFile.readline() workFile.read() workFile.readfirst() workFile.readfirstline() print(workFileFirstLine)

workFile = open('work.txt', 'r')workFileFirstLine = workFile.readline() print(workFileFirstLine)

x = float(input("Enter a number. "))y = float(input("Enter a number to divide by. ")) try: print(f"The answer is {x/y}.") except: if y==0: Choose One... raise raise() showError showError() else:print("You successfully used the division feature in Python") finally: print("Thank you for playing.")

x = float(input("Enter a number. "))y = float(input("Enter a number to divide by. ")) try: print(f"The answer is {x/y}.") except: if y==0: raise else:print("You successfully used the division feature in Python") finally: print("Thank you for playing.")

In python, which character(s) should be placed before text in a line of code to make the line of code a comment? // /* ' #

#

Take a look at the following code example, used to calculate a subtotal for an order: subtotal = amount + (1 * salesTax) + shipping return subtotal order1 = calTotal(500, .07, 10) print("Your order total ", order1) Which line of code needs to be added to the top of this code example in order to complete the code example?

def calcTotal(amount, salesTax, shipping):

which keyboard is used as a placeholder for a conditional results? break continue pass while

pass

Look at the following code and then select the correct keyword to use to check to see if the word "nine" is part of the quote. If this code runs, it should return a value of True. quote = "A stitch in time saves nine" print ("nine" Choose One... in is sub substring quote)

quote = "A stitch in time saves nine" print ("nine" in quote)

You are trying to loop through some values retrieved from a list. You want the list to keep printing these values but, if the list sees a value of "end of day" then the printing should stop. Select the missing code examples to finish writing this code block. schedule = ["Opening Comments", "Breakfast", "Breakout Session 1", "Lunch", "Breakout Session 2", "End of Day", "Opening Comments", "Breakfast"] scheduledEvent = 0 Choose One... while if for do (scheduledEvent < len(schedule)): print(schedule[scheduledEvent]) if schedule[scheduledEvent] == "End of Day": Choose One... break continue stop end else: Choose One... continue break scheduledEvent +=1 scheduledEvent = 1

schedule = ["Opening Comments", "Breakfast", "Breakout Session 1", "Lunch", "Breakout Session 2", "End of Day", "Opening Comments", "Breakfast"] scheduledEvent = 0 while (scheduledEvent < len(schedule)): print(schedule[scheduledEvent]) if schedule[scheduledEvent] == "End of Day": break else: scheduledEvent +=1

which of the following code examples is using incorrect syntax? a) newItems = [] b) price = 19.95 c) onSale = true d) serialNumber = "345678"

onSale = true

Take a look at the following function: def subtotal(orderAmt, salesTax): subtotal = float(orderAmt) * (1 + float(salesTax)) return subtotal Which example properly calls the function and returns a calculation? orderTotal = def subtotal(500, .07) orderTotal = subtotal(500, .07) call subtotal(500,.07) orderTotal(subtotal(500,.07))

orderTotal = subtotal(500, .07)

The strftime function converts a string into a date format. The strptime function formats a date strptime, strftime strptime, strdtime The statement is correct as is strdtime, strftime

strptime, strftime

The following code example does a simple calculation to divide two numbers. You want to handle any errors gracefully and ensure that the last print statement always prints, even if there is an error. Choose One... try: except: else: finally: x = float(input("Enter a number. ")) y = float(input("Enter a number to divide by. ")) print(f"The answer is {x/y}.") Choose One... try: except: else: finally: print("Uh oh. Did you enter something besides a number? Did you try to divide by zero?") Choose One... try: except: else: finally: print("You successfully played the division game.") Choose One... try: except: else: finally: print("Thank you for playing.")

try: x = float(input("Enter a number. ")) y = float(input("Enter a number to divide by. ")) print(f"The answer is {x/y}.") except: print("Uh oh. Did you enter something besides a number? Did you try to divide by zero?") else: print("You successfully played the division game.") finally: print("Thank you for playing.")

The goal with this is to show the nearest integer above and below the # (above for the upperBound variable and below for the lowerBound variable) given and have it work when a different number is present. Choose One... import math use math sys.math sampleNumber = 77.4 upperBound = Choose One... math.ceil math.ceiling math.round math.floor (sampleNumber) lowerBound = Choose One... math.ceil math.ceiling math.round math.floor (sampleNumber) print(upperBound) print(lowerBound)

As the math built-in module is being used, the module needs to be imported. That is done on the first line of code. The math.ceil function takes a floating number up to the next whole number. The math.floor function lowers a floating number to its base whole number. A round function would not be efficient here as it would not guarantee the upper and lower integers from the floating number and returned

Open the shirts file in a mode to where it cannot be written to Read the contents of the entire file Print the contents of the entire file Not every line of code is used: shirtFile = open("shirts.txt","a) shirtFileContents = shirtFile.read() for shirtLines = range(shirtFile): print(shirtFileContents) shirtFile = open("shirts.txt","r")

LINE 1: shirtFile = open("shirts.txt", "r") LINE 2: shirtFileContents = shirtFile.read() LINE 3: print(shirtFileContents)

Take a look at the following code example: carLoan = 20000 intRate = .05 licenseFee = 500 totalLoan = carLoan + licenseFee * intRate A user of the app with this code is complaining that the total loan amount is far lower than what is anticipated. What kind of error is taking place here? User Syntax Runtime Logic

Logic

What type of error could potentially occur, depending upon what a user inputs? x = float(input("Enter a number. ")) y = float(input("Enter a number to divide by. ")) print(f"The answer is {x/y}.") Logic Runtime User Syntax

Runtime

When declaring variables in Python, a data type must be specified. yes or no Python makes the distinction between integers and floating variables. yes or no When setting a boolean variable, the value must start with a capital letter. yes or no

When declaring variables in Python, a data type must be specified. no Python makes the distinction between integers and floating variables. yes When setting a boolean variable, the value must start with a capital letter. yes

Choose the correct operator to get a print result of 4. a = 24 b = 5 print(a Choose One...b) / mod % ^

a = 24 b = 5 print(a % b)

Look at the following code and then indicate, for each question, a yes or no based on whether the statement is true or false. a = 5 b = 3 b = a a == b yes or no a is b yes or no b == 3 yes or no

a == b yes a is b yes b == 3 no

Student with scores of 90 or higher get an A Student with scores between 80 and 89 get a B Students with scores between 70 and 79 get a C Everyone else gets an F def grade(score): if Choose One... score >= 90: grade = "A" score > 90: grade = "A" grade == "A" elif Choose One... score <= 89: grade = "B" score >= 80: grade = "B" score < 90: grade = "B" score > 80: grade = "B" elif Choose One... score >= 70: grade = "C" score > 70: grade= "C" score <= 79: grade = "C" score < 80: grade = "C" else Choose One... grade = "F" score <= 70: grade = "F" score < 70: grade = "F" return grade

def grade(score): if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" else grade = "F" return grade

The following code example needs to print, for five weeks, the # of minutes per day to walk, starting with 10 minutes a day in week 1 and ending 50 minutes a day in week 5 choose the correct line of code to start this iteration and finish this code example. Choose One... a) for week in range(1,5) b) for week in range(5) c) for week in range(1,6) d) while week < 5 print("You should walk for ", week * 10, " minutes in ", week)

for week in range(1,6)

A user gets five chances to correctly guess a whole number between 1 and 10. If the user guesses correctly they will get a congratulatory message and the game ends. If not, they get a message thanking them for playing. Choose One... from random import rand from random import randint from random import randrange for i in range(5): guess = int(input("Enter a number between 1 and 10. ")) randNum = Choose One... randrange(0,10) randrange(1,10) randint(1,10) randint(0,10) if guess == randNum: print("We matched!") break else: print("We did not match. Try again")

from random import randint for i in range(5): guess = int(input("Enter a number between 1 and 10. ")) randNum = randint(1,10) if guess == randNum: print("We matched!") break else: print("We did not match. Try again")

When using python in a command line environment, what command will list available python commands and show information on these commands when an individual command is entered? help() dir help command()

help()

Look at the following code example and then indicate which symbol is needed in the missing area to continue the line of code written on the next line. if annualSales >= 700000:print("Great year")elif annualSales >= 300000:print("Decent year")else::print("Better luck next year") print("Thank you for your efforts")print(f"Your sales representative is Nicole, you are in the East region, " Choose One... \ \\ \n \t "and you are based in the Potomac office.")

if annualSales >= 700000:print("Great year")elif annualSales >= 300000:print("Decent year")else::print("Better luck next year") print("Thank you for your efforts")print(f"Your sales representative is Nicole, you are in the East region, " \"and you are based in the Potomac office.")

The goal of this code example is to print today's date in mm/dd/yy format. Using the drop-down arrows, fill in the missing code to make this happen. Choose One... import date import datetime use date use datetime todayWithoutTime = Choose One... date.today() datetime.today() datetime.date.today() datetime.datetime.today() print(todayWithoutTime) print("The current date is", datetime.datetime. Choose One... strftime(todayWithoutTime, "%m/%d/%Y") strftime(todayWithoutTime, "%mm/%dd/%YY) strftime(todayWithoutTime, "%m/%d/%yyyy") strftime(todayWithoutTime, "%m/%d/%YYYY") )

import datetime todayWithoutTime = datetime.date.today() print(todayWithoutTime) print("The current date is", datetime.datetime.strftime(todayWithoutTime, "%m/%d/%Y"))

_______ used to read from and write to files ____ can display error messages that would not otherwise show ______ allows python code to create folders _________ allows python code to find specific files and folders

io Used to read from and write to files sys Can display error messages that would not otherwise show os Allows Python code to create folders os.path Allows Python code to find specific files and folders

The following code example opens a file, reads it and then prints its contents. In the missing code line, indicate what should be done with the file in order to free up memory the file has been using. jacketsFile = open('jackets.txt', 'r') jacketsFileContents = jacketsFile.read() print(jacketsFileContents) Choose One... jacketsFile.close() jacketsFile.end() jacketsFile.close("jackets.txt")jacketsFile.end("jackets.txt")

jacketsFile = open('jackets.txt', 'r') jacketsFileContents = jacketsFile.read() print(jacketsFileContents) jacketsFile.close()

The following code example, as is prints "You have {items} items in stock" instead of the number of items in stock. Using the drop-down arrow, add the symbol needed to get the number of items to print instead of {items}. price = 9.95 items= 15 print( Choose One..."We have {items} items in stock.") f \ % format

price = 9.95 items= 15 print(f "We have {items} items in stock.")

Finish the following code example with the print statement that will return a value of True. a = 5 b = 5.5 c = 7 d = 7.5 print( Choose One... print(a == int(b) and c != int(d)) print(a != int(b) and c != int(d)) print(a != int(b) and c == int(d)) print (a == int(b) and c == int(d)) )

print(a == int(b) and c == int(d)) print(5 == int(5.5) and 7 == int(7.5))


Kaugnay na mga set ng pag-aaral

Ch. 1 The Four Core Principles of Economics

View Set

Chapter 49: Disorders of Musculoskeletal Function: Developmental and Metabolic Disorders

View Set

Abeka: Science Order and Design Reading Quiz S 7th Grade

View Set

OPM 101 EXAM 1 REVIEW Full Set to study

View Set

Praxis ii 5039 Writing, Speaking, and Listening

View Set