Exam 2+3

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

How do you find the number of elements in a list named 'thelist'?

len(list)

What is the code for the XML version?

outfile.write('<?xml version ="1.0" ?>\n')

key()

return a list of strings which are the keys: for key in student.keys() print(student[key])

What function removes all elements from a list?

.clear()

Arithmetic Op

*, /, +, //, %

What index number is used to access the second to last element in a list?

-2

The first line in a function definition is known as the function _____.

header

What is the solution to a KeyError? Input a the code for the below: ages = {'Jim': 30, 'Pam': 28, 'Kevin': 33} person = input('Get age for: ')

.get() ages = {'Jim': 30, 'Pam': 28, 'Kevin': 33} person = input('Get age for: ') age = ages.get(person) if age: print(f'{person} is {age} years old.') else: 10 print(f"{person}'s age is unknown.")

Practice Paintjob exercise

Yes no?

Practions funcs.py

Yes no?

Which list will be referenced by the variable number after the following code is executed? numbers = [] for x in range(0, 9, 2): numbers.append(x) print(numbers)

[0, 2, 4, 6, 8]

Which list will be referenced by the variable number after the following code is executed? numbers = [] for num in range(0, 9, 2): -numbers.append(num) del numbers[2]print(numbers)

[0, 2, 6, 8]

What will be the value of the variable 'list' after the following code executes? list = [1] * 3

[1, 1, 1]

How do you open "friends.xml" into a write or read file in python?

outfile = open("friends.xml", "w" or "r")

Which method can be used to flip the order of elements in a list?

reverse.list()

How to find the type of list?

type()

Assume the variable 'dct' references a dictionary. Write an 'if' statement that determines whether the key 'James' exists in the dictionary. If so, display the value that is associated with that key. If the key is not in the dictionary, display a message indicating so.

Correct?

books.json Display the below: The Cat in the Hat by Dr. Seuss costs $6.99 Ender's Game by Orson Scott Card costs $8.99 Prey by Michael Crichton costs $9.35

Correct?

What will be the value of the variable list after the following code executes? list = [1, 2, 3, 4] list[3] = 10

[1, 2, 3, 10]

logical operators

and, or, not

append_books.py. Appending items to a dictionary

correct

A set of statements that belong together as a group and contribute to the function definition is known as a __________.

block

The __________ of a local variable is the function in which that variable is created.

scope

What is the line of code to pull a key and value

students = students_d["students"] for loop for student in students: print(student["firstName"])

items()

used to return the list with all dictionary keys with values: student = { 'lastName': 'Doe', 'major': 'CENT', 'firstName': 'Jane', 'credits': 34 } for k,v in student.items(): print(k,":",v)

For the Python program shown below, write down the output that would be sent to the screen when the program is run. x = 1 while (x < 4): if (x%2 == 0): print("x is",x) else: print("x is odd") x = x + 2

x is odd x is odd

Exam3.py

yes no?

ReviewEx.py

yes no?

What is the correct structure to create a dictionary of months where each month will be accessed by its month number (for example, January is month 1, April is month 4)?

{ 1 : 'January', 2 : 'February', ... 12 : 'December' }

What is the value of the variable 'phones' after the following code executes? phones = {'John' : '5555555', 'Julie' : '5557777'} phones['John'] = 5556666'

{'John' : '5556666', 'Julie' : '5557777'}

Selection Statements

if, elif, else

How do you open a JSON titled "books.json" with the header "books"?

import json infile = open("books.json", "r") contents = infile.read() books_d = json.loads(contents) books = books_d["books"

How to open a JSON file

import json infile = open("students.json","r") contents = infile.read() students_d = json.loads(contents) students = students_d["students"] for student in students: print(student["firstName"])

How do open a .txt file into a readable file? Ex: "score.txt"

infile = open("scores.txt", "r")

How do you change a .csv file to an .xml file then open it as a writeable file? Ex: lab10data.csv

infilename = input("Enter file name: ") infile = open(infilename, "r") outfilename = infilename.replace(".csv", ".xml") outfile = open(outfilename, "w") outfile.write('<?xml version ="1.0" ?>\n') outfile.write("<subjects>\n") lines = infile.readlines() infile.close()

When will the following loop terminate? while keep_on_going != 123:

keep_on_going == 123

How to determine how many items a list has?

len()

Which method would you use to get the value associated with a specific key and remove that key-value pair from the dictionary?

list

Which method can be used to place an item at a specific index in a list?

list.insert([index], x)

Write a while loop that lets the user enter a number. The number should be multiplied by 4, and the result added to a variable named product (initial value is 0). The loop should iterate as long as product is less than 45.

number = input("Enter a number: ") num = int(number) product = 0 while(product < 45): --product = product + (num * 4) --print(product) --if(product >= 45): ----print("The total is too high") ----break

File Output

open(), write(), close()

How do you write onto a file then close? Ex: outfile = open("friends.xml", "w")

outfile.write('<?xml version ="1.0"?>\n') outfile.write("<friends>\n") outfile.write(" </friends>\n") outfile.close()

What is a correct syntax to output "Hello World" in Python?

print("Hello World")

How do you format a number to have a percentage sign

"{:. 0%}". format(your_number)

How do you format a number to the 2nd decimal?

'{:.2f}'.format(number)

How to index an item in a list? Ex: fruit = [apple, banana, orange]

fruit[0] fruit[1] fruit[2]

What will be displayed after the following code is executed? def pass_it(x, y): -z = x*y -result = get_result(z) -return(result) def get_result(number): -z = number + 2 -return(z) num1 = 3 num2 = 4 answer = pass_it(num1, num2) print(answer)

14

What will be displayed after the following code is executed? total = 0 for count in range(4,6): total += count print(total)

4 9

What is the output of the following program? mylist = range(5, 1, -2) for item in mylist: print(item)

5 3

What will be displayed after the following code is executed? total = 0 for count in range(1,4): total += count print(total)

6

For the Python program shown below, write down the output that would be sent to the screen when the program is run: out = '<?xml version="1.0" ?>\n' out = out + '<numbers>\n' x = 9 while (x > 4): out = out + ' <number>' + str(x) out = out + '</number>\n' x = x - 2 out = out + '</numbers>' print(out)

<?xml version="1.0"?> <numbers> <number>9</number> <number>7</number> <number>5</number> </numbers>

Relational Operators

==, !=, >, <, >=, <=

For Loop

A loop used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string)

While Loop

A loop we can execute a set of statements as long as a condition is true.

What is a root element in XML

An element that encloses all the other elements in the XML file. Ex:<students> </students>

What is KeyError?

An error that is raised when you try to access a key that isn't in a dictionary

What are the data items in a list called?

Elements

What is an XML file and what is a use?

Extensible Markup Language. Used to store data.

What does the following program do? student = 1 while student <= 3: total = 0 for score in range(1, 5): score = int(input("Enter test score: ")) total += score average = total/4 print("Student ", student, "average: ", average) student += 1

It accepts 4 test scores for each of 3 students and outputs the average for each student.

What does JSON stand for?

JavaScript Object Notation

In a dictionary, each element has two parts: a(n) _________ and a(n) _________.

Key, value

What will be the result of the following code? ages = {'Aaron' : 6, 'Kelly' : 3, 'Abigail' : 1 } value = ages['Brianna']

KeyError

What are the types of list?

List Tuple Set Dictionary

What will be the output after the following code is executed? def pass_it(x, y): -z = y + x num1 = 4 num2 = 8 answer = pass_it(num1, num2) print(answer)

None, because the function does not return 'z'

List

Ordered, changeable and allow duplicate values

What data types can a list include?

String, int, float, and boolean

Design a program that asks the user to enter a store's sales for each day of the week. The amounts should be stored in a list. Use a loop to calculate and display the total sales for the week and the daily average.

day = 0 tsale = 0 salelist = [] while(day < 8): --day += 1 --print("Day No.", day) --sale = input("Today's sales are: ") --salelist.append(sale) --for i in salelist: ----tsale = tsale + int(i) ----avg = tsale / day --if(day == 7): ----break print("Here is this week's sale", tsale) print("This week's average is", avg) print(salelist)

Write a function named times_ten. The function should accept an argument and return the product of its argument multiplied times 10. Add code that calls the function and displays the value returned.

def times_ten(x): t = x * 10 return t print(time_ten(2))

Design a program that reads a file named "scores.txt containing lines of test scores separated by commas. Read each line in the file and put each line of scores in a list. Sort the scores in each list in decreasing order and display each list. The contents of "scores.txt" are as follows: 85.6, 92.2, 57.9, 45.7 39.4, 55,6, 99.9, 46.3 98.8, 90.4, 79.3, 66.7

for line in lines: print(line) line = line.strip().split(",") line.sort() line.reverse() print(line)


Kaugnay na mga set ng pag-aaral

Nutrition Test 4 Rebecca Bibby Fall 2021

View Set

Lines & Cues for "Clue" - Motorist

View Set

Chapter 6: Criminal Law and Cyber Crime

View Set

Animal Science - First Exam Study

View Set

Anatomy Lecture Exam 5 (FINAL 4/28) powerpoint review

View Set

Bio 152 Seedless Plants, Gymnosperms/Angiosperms Quiz #2

View Set

Kaplan TX Long-Term Care and Partnership Policies Course Review

View Set