Intro to Python

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

Choose which of the following are valid Python variable names.

BankAccount _27_ stor_txt

Which of the following two snippets of code are equal?

from json import load file = open("scores.txt") load(file) import json file = open("scores.txt") json.load(file)

A for loop will process a file sentence-by-sentence

False

A while loop will execute at least once

False

A while loop will execute once for each expression in the conditional

False

Dictionaries are useful because you can have duplicate keys

False

Dictionaries will always have at least one key and one value

False

The given program correctly closes the file: def has_a_cat(filename): a_file = open(filename) return "cat" in a_file.read() a.file.close() has_a_cat("story.txt")

False

The open function consumes a String representing a path and returns a String of the file's contents

False

The print function can only print literal values

False

The print function is necessary to call a function

False

The statement count = count + 1 will cause an error because no number can be greater than itself

False

Tuples are composed of key/value pairs

False

Variable names are important because computers understand the meaning of names and change their value accordingly.

False

Variables in Python are used to solve for unknown values, like in Algebra.

False

You can nest if statements of other if statements, but not inside functions

False

You can store a List as one of the keys of a Dictionary

False

You should not put error messages into help seeking emails because it can clutter up the email

False

Label each of the following function call, method call, or not a call

Function.call() (M) print() (F) file.close() (N/A) method() (F) "function"method() (N/A) (input) (N/A)

Which of the following is the best description of this line of code? from math import sqrt as square_root

Loads the sqrt function in the math module but renames it square_root

Unlike List, Tuples are immutable, meaning Tuples cannot be changed after they are created

True

Variables change their value over time according to the instructions in a program

True

You can store a Dictionary as one of the element of a List

True

You can store a List of the values of a Dictionary

True

You must import the json module before you can use the load function

True

The print function does which of the following?

Writes output to the console Consumes arguments

Mark each of the following email titles if they are GOOD titles when seeking help from a senior colleague

"What is a TypeError and how do I get rid of it?" "How do I update a variable?"

How many values can be used at a time with each of the following operators?

+ (2) not (1) and (2) != (2)

Identify each of the components of the Dictionary literal below: { 5 : "Key" , "Value" : 9 }

1 = Curly Brace 2 = Key 3 = Colon 4 = Value 5 = Comma 6 = Key 7 = Colon 8 = Value 9 = Curly Brace

How many branches do each of these code snippets have?

2, 2, 3

What will be printed after this code is run? points = {"Virginia Tech": 5} points["Virginia Tech"] = 3 print(points["Virginia Tech"])

3

How many times does the loop body below execute? command = "" words = [] while command != "quit": command = input("Give me another word:") words.append("Said " + command) print (words)

At least once

Which of the following can be involved in an expression?

Conditional operators Variables Other expressions Mathematical operators Values

What is the type of the iteration variable in this code? groceries = [{"Name": "Apple", "Cost": 1.99, "Calories": 20}

Dictionary

Which of the following are possible subtypes for a list?

Dictionary, Boolean, List, String, Integer

Every function created with the def keyword must have AT LEAST ONE parameter

False

Expressions are always evaluated from left to right

False

Humans discovered programming languages in the 1940s and have been decoding them ever since.

False

Once a function returns a variable, that variable is available outside of the function

False

Printing is the same thing as returning

False

Strings are composed of only letters and symbols

False

The body of a for loop will contain one statement for each element of the iteration list

False

Is the print call before, inside, or after the for loop? for name in names: print(name)

Inside

What is the value of tax after this program executes? If False: tax = 5 print(tax)

No value, because an error occurs since the value has not been defined

When the following code is executed, what will be the value of the variable named greeting? def make_greeting(name): print("Hello", name) greeting = make_greeting("Mr.Anderson")

None

The input function does which of the following?

Returns a string Consumes arguments Writes output to the console Retrieves input from the user

Math the type of graph with the kind of question it is most suited to

Scatter Plot: The relationship between two lists of numbers Histogram: The distribution of a list of numbers Line Plot: The trend in a list of numbers

Given the file named scores.txt with the following contents: 44,23,37 And the following python code: score_file = open("scores.txt") score_data = score_file.read() What will be the type of score_data?

String

Which of the following types are sequences?

String, Dictionary, File, List, Tuple

Keys can be added to a dictionary after the dictionary has been created

True

Like an if statement and a function call, the for Loop might cause the execution to not follow the sequential order of lines

True

List comprehensions cannot express everything that a for loop can

True

Normally, statements are executed from top to bottom

True

The Iteration Variable will take on each value of the List Variable, one at a time.

True

Which of the following demonstrates proper syntax for accessing a dictionary's value?

a_dictionary["Key"]

What does the pass do?

absolutely nothing

The following complex, nested data structure represents books. Print out the total price of all the books summed together.

books = [ {"Title": "Great Expectations", "Pages": 321, "Sales": {"Price": 10, "In Stock?": "True"}}, {"Title": "The Grapes of Wrath", "Pages": 470, "Sales": {"Price": 5, "In Stock?": "True"}}, {"Title": "Pride & Prejudice", "Pages": 273, "Sales": {"Price": 20, "In Stock?": "True"}}, ] total = 0 for book in books: total += book["Sales"]["Price"] print(total)

Define a function calculate_range that consumes a temperature and returns a tuple of two numbers, the high and the low. These numbers are calculated as follows: high = temperature + 20low = temperature - 30 Then, you will need to call your function once to create two variables today_low and today_high for today's temperature of 70.

def calculate_range(temperature): high = temperature + 20 low = temperature - 30 return high, low today_high, today_low = calculate_range(70)

Define a function clean_string that consumes a string and returns a new, cleaned string. To clean a string, you will need to: Strip whitespace from the end Replace any plus signs with spaces So, for example, the string " Hello+World " would become "Hello World".

def clean_string(string): return string.replace("+"," ").strip(" ") print(clean_string("Hello+World"))

Define a function filter_toppings that consumes a list of strings and returns a new list. This new list should not have any of the following strings, regardless of capitalization: "ham", "bacon", "sausage". For example, the list ["Bacon", "Onions", "green pepper", "HAM"] would return ["Onions", "green pepper"].

def filter_toppings(toppings): result = [] for topping in toppings: if topping.lower() not in ['ham','bacon','sausage']: result.append(topping) return result

Define a function is_sentence that consumes a string and returns a boolean indicating whether the string ends in a ".", "?", or "!". For example, the string "Hello?" would return True but the string "Dog" would return False.

def is_sentence(string): return string[-1]=="." or string[-1]=="!" or string[-1]=="?" print(is_sentence("Dog"))

Define a function make_demanding that consumes a string and returns a new, more demanding string. To make a string more demanding, add the string ", now!" to the end. For example, the string "Pass the butter" would become "Pass the butter, now!".

def make_demanding(string): return string +", now!" print(make_demanding("Pass the butter"))

Define a function sum_file that consumes a string representing a filename and returns a number. This number will represent the sum of all the numbers in the given file. Assume that all files will have each number on their own line.

def sum_file(filename): try: total = 0 with open(filename, 'r') as f: for line in f: total += int(line.strip()) return total except: return 0

Define a function get_data that consumes a dictionary and returns the value associated with the key "Data". If the key "Data" is not in the dictionary, then return the value 0 instead.

dict={'not':1} def get_data(dict): if "Data" in dict: return dict["Data"] else: return 0 print(get_data(dict))

Given the following code, dict = {"Key": "Value", 7: 8, True: "Hello"} key = 7

dict["Key"] dict[7] dict[True] dict[key]

Define a function convert_distance that consumes a number (representing distance in kilometers) and returns that number converted to meters by applying the following formula: meters = kilometers * 1000 Then use this function to convert each element of the given list and print the result.

distances = [10, 5, 4.3] def convert_distance(kilometers): return kilometers * 1000 new_distance = [convert_distance(item) for item in distances] print(new_distance)

print a Boolean value indicating whether the user-inputted string (from input) is a punctuation symbol. If the user types more than one character, you can print out False.

from string import punctuation ch = input() if len(ch) == 1: print(ch in punctuation) else: print(False)

The given file contains JSON data. Use the data associated with the "Employees" key (a list inside of a dictionary inside of a dictionary inside of a dictionary) to plot the distribution of employees.

import json import matplotlib.pyplot as plt data = open("report.json").read() data = json.loads(data) plt.plot(data["Records"]["Data"]["Employees"]) plt.show()

Use the input function to consume a plus-separated string of numbers from the user (e.g., 4+2+3). Add up all these numbers and print their sum (9, in the case shown before).

inputs=input('Enter a string of numbers you want to add.') numbers = inputs.split('+') total = 0 for number in numbers: total = total + int(number) print(total)

Which of the following expressions creates two new variables?

month, year = (11,17)

The following complex, nested data structure represents movies. Use a combination of list indexing and dictionary access to print out the third character in the second movie.

movies = [ {"Name": "Iron Man", "Length": 126, "Characters": ["Tony", "Pepper", "Obidiah"]}, {"Name": "Thor", "Length": 130, "Characters": ["Thor", "Jane", "Loki"]}, {"Name": "Captain America", "Length": 126, "Characters": ["Steve", "Peggy", "Bucky"]}] print(movies[1]["Characters"][2])

Given the following code:

movies[0]["Name"]: "Iron Man" movies[2]["Name"]: "Captain America" movies[0][127]: Raises an error movies[1][1]: Raises an error movies[127]["Name"]: Raises an error movies[2]["Characters"][0]: "Steve" movies[2]["Characters"]["Steve"]: Raises an error movies[1]["Characters"][2]: Loki movies[2]["Steve"]: Raises an error movies[-1]["Length"]: 126

Which of the following lines of code will have the data flow correctly through both functions in order to print the message with the fixed capitalization?

name = fix_capitalization(name) print_message(fix_capitalization(name))

Label each of the following as either a "Read", a "Write", or a "Read and Write" for the variable price

print = 0 (Write) print(price) (R&W) adjusted=price*tax (Write) price = price *.9 (Read)

Print out each of the following literal values on their own lines: A positive integer (int) A negative float (float) A non-empty string (str) A boolean (bool) A None (None) A non-empty list of integers (list) A non-empty dictionary mapping strings to integers (dict) A tuple of two strings (tuple)

print(5) print(-5.0) print("hello") print(True) print(None) print([1,2,4,4]) print({"a":1}) print(('python','cool'))

The following complex, nested data structure represents multiple students' scores over multiple assignments. Count the total number of scores.

scores = [ [90, 95, 75], [13, 27], [44, 60, 55, 27, 21] ] count = 0 for score in scores: count += len(score) print(count)

Which of the following have a body?

while loop if statement for loop function definition


Kaugnay na mga set ng pag-aaral

3E951 CDC Volume 2 Unit Review Exercises

View Set

SPC Level 2 Exam 2- Anemia Adaptive Quiz

View Set