Python Interview Basics

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

In this code, identify the repeated pattern and replace it with a function called month_days, that receives the name of the month and the number of days in that month as parameters. Adapt the rest of the code so that the result is the same. Confirm your results by making a function call with the correct parameters for both months listed.

# REPLACE THIS STARTER CODE WITH YOUR FUNCTION def month_days(month, days): print (month +" has " + str(days) + " days.") month_days ("June", 30) month_days("July", 31)

This function compares two numbers and returns them in increasing order. Fill in the blanks, so the print statement displays the result of the function call in order. Hint: if a function returns multiple values, don't forget to store these values in multiple variables

# This function compares two numbers and returns them # in increasing order. def order_numbers(number1, number2): if number2 > number1: return number1, number2 else: return number2, number1 # 1) Fill in the blanks so the print statement displays the result # of the function call (smaller, bigger)= order_numbers(100, 99) print(smaller, bigger)

FOR MY NOTE: the meaning of [::3]

-'abcdefghijklm'[::3] # beginning to end, counting by 3 'adgjm' -'abcdefghijklm'[::-3] # end to beginning, counting down by 3 'mjgda'

Having a plan is half the battle. When planning out your program, why is it often a good idea to separate functions?

-It simplifies making changes and fixing bugs. -It allows us to use the same function for multiple purposes. (Separating functions is helpful when debugging or making other changes, as it keeps functions from getting 'tangled'. It also makes it easier to adapt functions for other uses.)

What's the value of this Python expression: 11 % 5?

1 ("%" is the modulo operator, which returns the remainder of the integer division between two numbers. 11 divided by 5 equals 2 with remainder of 1.)

What's the output of this code? def sum(x, y): return(x+y) print(sum(sum(1,2), sum(3,4)))

10. (We're calling the sum function 3 times: returning 3, then 7, then adding up 3 plus 7 for the total of 10.)

What's the output of this code if number equals 10? if number > 11: print(0) elif number != 10: print(1) elif number >= 20 or number < 12: print(2) else: print(3)

2

Which of these activities are good use cases for recursive programs? Check all that apply.

Going through a file system collecting information related to directories and files. (Because directories can contain subdirectories that can contain more subdirectories, going through these contents is a good use case for a recursive program.) Managing permissions assigned to groups inside the company, when each group can contain both subgroups and users. (As the groups can contain both groups and users, this is the kind of problem that is a great use case for a recursive solution.)

The fractional_part function divides the numerator by the denominator, and returns just the fractional part (a number between 0 and 1). Complete the body of the function so that it returns the right number. Note: Since division by 0 produces an error, if the denominator is 0, the function should return 0 instead of attempting the division.

def fractional_part(numerator, denominator): if denominator == 0: # Operate with numerator and denominator to # keep just the fractional part of the quotient return 0 return (numerator/denominator)%1

Fill in the blanks to make the print_prime_factors function print all the prime factors of a number. A prime factor is a number that is prime and divides another without a remainder.

def print_prime_factors(number): # Start with two, which is the first prime factor = 2 # Keep going until the factor is larger than the number while factor <= number: # Check if factor is a divisor of number if number % factor == 0: # If it is, print it and divide the original number print(factor) number = number / factor else: # If it's not, increment the factor by one factor += 1 return "Done"

The retry function tries to execute an operation that might fail, it retries the operation for a number of attempts. Currently the code will keep executing the function even if it succeeds. Fill in the blank so the code stops trying after the operation succeeded.

def retry(operation, attempts): for n in range(attempts): if operation(): print("Attempt " + str(n) + " succeeded") if n==1: break else: print("Attempt " + str(n) + " failed") --------------------------------------------- retry(create_user, 3) retry(stop_service, 5)

What's a computer program?

A list of instructions that computer has to follow to reach a goal. (At a basic level, a computer program is a recipe of instructions that tells your computer what to do.)

What is a computer program?

A step-by-step recipe of what needs to be done to complete a task, that gets executed by the computer (Being able to write such programs is a super useful skill that you'll acquire through this course.)

What makes an object different from a class?

An object is a specific instance of a class (Objects are an encapsulation of variables and functions into a single entity.)

What Is a Method?

Calling methods on objects executes functions that operate on attributes of a specific instance of the class. This means that calling a method on a list, for example, only modifies that instance of a list, and not all lists globally. We can define methods within a class by creating functions inside the class definition. These instance methods can take a parameter called self which represents the instance the method is being executed on. This will allow you to access attributes of the instance using dot notation, like self.name, which will access the name attribute of that specific instance of the class object. When you have variables that contain different values for different instances, these are called instance variables.

It's important to know why we've written a function. In the example used in the video (shown here), what is the purpose of "if len(users) > 0:" ? def generate_report(machines): for machine, users in machines.items(): if len(users) > 0: user_list = ", ".join(users) print("{}: {}".format(machine, user_list))

Ensure that we don't print any machines where nobody is currently logged in (Generating the string underneath this check prevents lists with zero users from being printed.)

What's the value of this Python expression: "big" > "small"

False (The conditional operator > checks if two values are equal. The result of that operation is a boolean: either True or False. Alphabetically, "big" is less than "small".)

What are functions in Python?

Functions are pieces of codes that perform a unit of work. (Python functions encapsulate a certain action, like outputting a message to the screen in the case of print().)

Which of these scenarios are good candidates for automation? Select all that apply.

Generating a sales report, split by region and product type ( Creating a report that presents stored data in specific ways is a tedious task that can be easily automated.) Copying a file to all computers in a company (A task like copying files to other computers is easily automated, and helps to reduce unnecessary manual work.) Sending personalized emails to subscribers of your website (Sending out periodic emails is a time-consuming task that can be easily automated, and you won't have to worry about forgetting to do it on a regular basis.)

Which of the following tasks do you think are good candidates for automation? Check all that apply.

Installing software on laptops given to new employees when they are hired (Installing and configuring software is a task that can be automated. Ensuring that everyone gets the exact same setup and reducing the amount of manual work needed for each new employee.) Periodically scanning the disk usage of a group of file servers (Scanning the disk usage is a task that can be easily automated. By letting the computer do it, you won't have to worry about forgetting to do it whenever it's needed.)

What's a major advantage of using dictionaries over lists?

It's quicker and easier to find a specific element in a dictionary (Because of their unordered nature and use of key value pairs, searching a dictionary takes the same amount of time no matter how many elements it contains)

What are keywords in Python?

Keywords are reserved words that are used to construct instructions. (Using the reserved words provided by the language we can construct complex instructions that will make our scripts.)

What are the values passed into functions as input called?

Parameters. A parameter, also sometimes called an argument, is a value passed into a function for use within the function.

What are some characteristics of the Python programming language? Check all that apply.

Python programs are easy to write and understand (Because the syntax used by Python is similar to the one used by the English language) The python interpreter reads our codes and transforms it into computer instructions (We write our code using Python's syntax and semantics, and the interpreter transforms that into instructions that our computer executes.) We can practice Python using web interpreters or codepads as well as executing it locally (We can practice writing Python code with many different tools available to us, both online and offline)

Let's check whether you soaked all that in with a quick question! Select all options that explain why Python is relevant to today's IT industry

Python scripts are easy to write, understand, and maintain.(Python is a language that tries to mimic our natural language and so Python scripts are generally easy to write, understand and maintain.) There are many system administration tools built with Python.(Over the years, the Python community has developed a lot of additional tools that can be used by system administrators to get their job done.) Python is available on a wide variety of platforms. (Python is available on Windows, Linux, MacOS and even on mobile devices, making it a great tool for IT specialist looking to create scripts that can work across platforms.)

RECURSIVE: What is recursion used for?

Recursion lets us tackle complex problems by reducing the problem to a simples one .

What's the value of this Python expression? ((10 >= 5*2) and (10 <= 5*2))

TRUE (When using the "and" operator, a statement is True if both parts of the conditional are True.)

What are semantics when applied to programming code and pseudocode?

The effect of the programming instructions have (Like human language, the intended meaning or effect of words, or in this case instructions, are referred to as semantics.)

What does the print function do in Python?

The print functions output messages to the screen (Using the print() we can generate output for the user of our programs.)

What's automation?

The process of replacing a manual step with one that happens automatically (By replacing a manual step with an automatic one we create automation that helps us reduce unnecessary manual work.)

What's automation?

The process of replacing a manual step with one that happens automatically.

What's the syntax of a language?

The rules of how to express things in that language. (In a human language, syntax is the rules for how a sentence is constructed, and in a programming language, syntax is the rules for how each instruction is written.)

What's the difference between a program and a script?

There's not much different, but scripts are usually simpler and shorter (The line between a program and a script is blurry; scripts usually have a shorter development cycle. This means that scripts are shorter, simpler, and can be written very quickly.)

Why do we need to learn the syntax and semantics of a programming language?

To allow us to clearly express what we want the computer to do (Knowing the syntax and understanding the semantics of a programming language allows us to tell the computer what we want it to do.)

What's the value of this Python expression: (2**2) == 4?

True. The conditional operator == checks if two values are equal. The result of that operation is a boolean: either True or False.

Tuples and lists are very similar types of sequences. What is the main thing that makes a tuple different from a list?

Tuple is immutable (can't be changed)

What is the purpose of the def keyword?

Use to define a new function. When defining a new function, we must use the def keyword followed by the function name and properly indented body.

How are while loops and for loops different in Python?

While loops iterate while a condition is true. For loops iterate through a sequence of elements

Modify the first_and_last function so that it returns True if the first letter of the string is the same as the last letter of the string, False if they're different. Remember that you can access characters using message[0] or message[-1]. Be careful how you handle the empty string, which should return True since nothing is equal to nothing. def first_and_last(message): return False

def first_and_last(message): if len(message) == 0: return True elif message[0] == message[-1]: return True else: return False -------------------------- print(first_and_last("else")) print(first_and_last("tree")) print(first_and_last(""))

RECURSIVE: Which of the following scenarios would benefit the most from using a recursive function to solve the problem?

You need to create a family tree, showing several generations of your ancestors, with all of their children. (You're getting the concept of recursion and when it's a better solution than the traditional looping techniques.)

This code is supposed to display "2 + 2 = 4" on the screen, but there is an error. Find the error in the code and fix it, so that the output is correct.

a = 2 b = a+a print("2 + 2 = " + str(b) )

What do you call a combination of numbers, symbols, or other values that produce a result when evaluated?

an expression

Let's test your knowledge of using dot notation to access methods and attributes in an object. Let's say we have a class called Birds. Birds has two attributes: color and number. Birds also has a method called count() that counts the number of birds (adds a value to number). Which of the following lines of code will correctly print the number of birds? Keep in mind, the number of birds is 0 until they are counted!

bluejay.count() print(bluejay.number) (We must first call the count() method, which will populate the number attribute, allowing us to print number and receive a correct response.)

class ___: color = 'unknown' rose = Flower() rose.color = ___ violet = ___ ___ this_pun_is_for_you = ___ print("Roses are {},".format(rose.color)) print("violets are {},".format(violet.color)) print(this_pun_is_for_you)

class Flower: color = "unknown" rose = Flower() rose.color = "red" violet = Flower() violet.color = "blue" this_pun_is_for_you = Flower() print("Roses are {},".format(rose.color)) print("violets are {},".format(violet.color)) print(this_pun_is_for_you)

Complete the code to iterate through the keys and values of the cool_beasts dictionary. Remember that the items method returns a tuple of key, value for each element in the dictionary.

cool_beasts = {"octopuses":"tentacles", "dolphins":"fins", "rhinos":"horns"} for key, value in cool_beasts.items(): print("{} have {}".format(key, value))

Complete the function by filling in the missing parts. The color_translator function receives the name of a color, then prints its hexadecimal value. Currently, it only supports the three additive primary colors (red, green, blue), so it returns "unknown" for all other colors.

def color_translator(color): if color == "red": hex_color = "#ff0000" elif color == "green": hex_color = "#00ff00" elif color == "blue": hex_color = "#0000ff" else: hex_color = "unknown" return hex_color

Using the format method, fill in the gaps in the convert_distance function so that it returns the phrase "X miles equals Y km", with Y having only 1 decimal place. For example, convert_distance(12) should return "12 miles equals 19.2 km".

def convert_distance(miles): km = miles * 1.6 result = "{} miles equals {:.1f} km".format (miles,km) return result ---------------------------------- print(convert_distance(12)) # Should be: 12 miles equals 19.2 km print(convert_distance(5.5)) # Should be: 5.5 miles equals 8.8 km print(convert_distance(11)) # Should be: 11 miles equals 17.6 km

n this code, there's an initialization problem that's causing our function to behave incorrectly. Can you find the problem and fix it? def count_down(start_number): while current > 0: print (current) current -= 1 print ("Zero!") count_down(3)

def count_down(current): while current > 0: print (current) current -= 1 print ("Zero!") count_down(3)

Modify the double_word function so that it returns the same word repeated twice, followed by the length of the new doubled word. For example, double_word("hello") should return hellohello10. def double_word(word): return

def double_word(word): return (word *2) + str(len(word*2)) ----------------------------------------------- print(double_word("hello")) # Should return hellohello10 print(double_word("abc")) # Should return abcabc6 print(double_word("")) # Should return 0

Students in a class receive their grades as Pass/Fail. Scores of 60 or more (out of 100) mean that the grade is "Pass". For lower scores, the grade is "Fail". In addition, scores above 95 (not included) are graded as "Top Score". Fill in this function so that it returns the proper grade.

def exam_grade(score): if score == 100: grade = "Top Score" elif 95 >= score >= 60: grade = "Pass" else: grade = "Fail" return grade

In math, the factorial of a number is defined as the product of an integer and all the integers below it. For example, the factorial of four (4!) is equal to 1*2*3*4=24. Fill in the blanks to make the factorial function return the right number.

def factorial(n): result = 1 for i in range(1, n+1): result *= i return result

Fill in the blanks to make the factorial function return the factorial of n. Then, print the first 10 factorials (from 0 to 9) with the corresponding number. Remember that the factorial of a number is defined as the product of an integer and all integers before it. For example, the factorial of five (5!) is equal to 1*2*3*4*5=120. Also recall that the factorial of zero (0!) is equal to 1.

def factorial(n): result = 1 for x in range(1,n): result = result * x return result for n in range(0,10): print(n, factorial(n+1))

Using the "split" string method from the preceding lesson, complete the get_word function to return the {n}th word from a passed sentence. For example, get_word("This is a lesson about lists", 4) should return "lesson", which is the 4th word in this sentence. Hint: remember that list indexes start at 0, not 1.

def get_word(sentence, n): # Only proceed if n is positive if n > 0: words = sentence.split() # Only proceed if n is not more than the number of words if n <= len(words): return(words[n-1]) return("") ------------------------------ print(get_word("This is a lesson about lists", 4)) # Should print: lesson print(get_word("This is a lesson about lists", -4)) # Nothing print(get_word("Now we are cooking!", 1)) # Should print: Now print(get_word("Now we are cooking!", 5)) # Nothing

Complete the script by filling in the missing parts. The function receives a name, then returns a greeting based on whether or not that name is "Taylor".

def greeting(name): if name == "Taylor": return "Welcome back Taylor!" else: return "Hello there, " + name print(greeting("Taylor")) print(greeting("John"))

The group_list function accepts a group name and a list of members, and returns a string with the format: group_name: member1, member2, ... For example, group_list("g", ["a","b","c"]) returns "g: a, b, c". Fill in the gaps in this function to do that.

def group_list(group, users): members = group + ": " + ", ".join(users) return members -------------------- print(group_list("Marketing", ["Mike", "Karen", "Jake", "Tasha"])) # Should be "Marketing: Mike, Karen, Jake, Tasha" print(group_list("Engineering", ["Kim", "Jay", "Tom"])) # Should be "Engineering: Kim, Jay, Tom" print(group_list("Users", "")) # Should be "Users:"

Fill in the gaps in the initials function so that it returns the initials of the words contained in the phrase received, in upper case. For example: "Universal Serial Bus" should return "USB"; "local area network" should return "LAN" def initials(phrase): words = phrase.___ result = "" for word in words: result += ___ return ___

def initials(phrase): words = phrase.split() result = "" for word in words: result += word[0].upper() return result ----------------------- print(initials("Universal Serial Bus")) # Should be: USB print(initials("local area network")) # Should be: LAN print(initials("Operating system")) # Should be: OS

The is_palindrome function checks if a string is a palindrome. A palindrome is a string that can be equally read from left to right or right to left, omitting blank spaces, and ignoring capitalization. Examples of palindromes are words like kayak and radar, and phrases like "Never Odd or Even". Fill in the blanks in this function to return True if the passed string is a palindrome, False if not.

def is_palindrome(input_string): # We'll create two strings, to compare them new_string = input_string.replace(" ", "").lower() reverse_string = input_string.replace(" ",""). lower()[::-1] if new_string == reverse_string: return True return False ---------------------------- print(is_palindrome("Never Odd or Even")) # Should be True print(is_palindrome("abc")) # Should be False print(is_palindrome("kayak")) # Should be True

The is_positive function should return True if the number received is positive, otherwise it returns None. Can you fill in the gaps to make that happen?

def is_positive(number): if number > 0: return True

Fill in the blanks to make the is_power_of function return whether the number is a power of the given base. Note: base is assumed to be a positive number. Tip: for functions that return a boolean value, you can return the result of a comparison.

def is_power_of(number, base): # Base case: when number is smaller than base. if number ==1: return True if number < base: # If number is equal to 1, it's a power (base**0). return False number /= base # Recursive case: keep dividing number by base. return is_power_of(number, base) ---------------------------------------- print(is_power_of(8,2)) # Should be True print(is_power_of(64,4)) # Should be True print(is_power_of(70,10)) # Should be False

The following code can lead to an infinite loop. Fix the code so that it can finish successfully for all numbers. Note: Try running your function with the number 0 as the input, and see what you get!

def is_power_of_two(n): # Check if the number can be divided by two without a remainder while n % 2 == 0 and n != 0: n = n / 2 # If after dividing by two the number is 1, it's a power of two if n == 1: return True n += 1 return False

The longest_word function is used to compare 3 words. It should return the word with the most number of characters (and the first in the list when they have the same length). Fill in the blank to make this happen.

def longest_word(word1, word2, word3): if len(word1) >= len(word2) and len(word1) >= len(word3): word = word1 elif len(word2) >= len(word1) and len(word2) >= len(word3): word = word2 else: word = word3 return(word)

Let's revisit our lucky_number function. We want to change it, so that instead of printing the message, it returns the message. This way, the calling line can print the message, or do something else with it if needed. Fill in the blanks to complete the code to make it work.

def lucky_number(name): number = len(name) * 9 return "Hello " + name + ". Your lucky number is " + str(number) ___ (lucky_number("Kay")) (lucky_number("Cameron")) The function now returns the message, for the calling line to use it in any way it wants to.

The multiplication_table function prints the results of a number passed to it multiplied by 1 through 5. An additional requirement is that the result is not to exceed 25, which is done with the break statement. Fill in the blanks to complete the function to satisfy these conditions.

def multiplication_table(number): # Initialize the starting point of the multiplication table multiplier = 1 # Only want to loop through 5 while multiplier <= 5: result = multiplier * number # What is the additional condition to exit out of the loop? if result > 25: break print (str(number) + "x" + str(multiplier) + "=" + str(result)) # Increment the variable for the loop multiplier += 1

The number_group function should return "Positive" if the number received is positive, "Negative" if it's negative, and "Zero" if it's 0. Can you fill in the gaps to make that happen?

def number_group(number): if number > 0: return "Positive" elif number == 0: return "Zero" else: return "Negative"

The skip_elements function returns a list containing every other element from an input list, starting with the first element. Complete this function to do that, using the for loop to iterate through the input list.

def skip_elements(elements): # Initialize variables new_list = [] i = 0 # Iterate through the list for i in range(len(elements)): # Does this element belong in the resulting list? if i%2 ==0: # Add this element to the resulting list new_list.append(elements[i]) # Increment i return new_list -------------- print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g'] print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach'] print(skip_elements([])) # Should be []

Try out the enumerate function for yourself in this quick exercise. Complete the skip_elements function to return every other element from the list, this time using the enumerate function to check if an element is on an even position or an odd position.

def skip_elements(elements): # code goes here new_list = [] for index, word in enumerate(elements): if index%2 ==0: new_list.append(word) return new_list --------------------------------------------------- print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g'] print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']

Fill in the gaps of the sum_squares function, so that it returns the sum of all the squares of numbers between 0 and x (not included). Remember that you can use the range(x) function to generate a sequence of numbers from 0 to x (not included).

def square(n): return n*n def sum_squares(x): sum = 0 for n in range(x): sum += square(n) return sum

Modify the student_grade function using the format method, so that it returns the phrase "X received Y% on the exam". For example, student_grade("Reed", 80) should return "Reed received 80% on the exam". def student_grade(name, grade): return ""

def student_grade(name, grade): return ("{} received {}% on the exam" .format(name, grade)) ----------------------------------- print(student_grade("Reed", 80)) print(student_grade("Paige", 92)) print(student_grade("Jesse", 85))

Fill in the empty function so that it returns the sum of all the divisors of a number, without including it. A divisor is a number that divides into another without a remainder.

def sum_divisors(n): i = 1 sum = 0 # Return the sum of all divisors of n, not including n while i < n: if n % i == 0: sum += i i +=1 else: i+=1 return sum

RECURSIVE : The function sum_positive_numbers should return the sum of all positive numbers between the number n received and 1. For example, when n is 3 it should return 1+2+3=6, and when n is 5 it should return 1+2+3+4+5=15. Fill in the gaps to make this work:

def sum_positive_numbers(n): # The base case is n being smaller than 1 if n < 1: return n # The recursive case is adding this number to # the sum of the numbers smaller than this one. return n + sum_positive_numbers(n-1)

Implement the sum_positive_numbers function, as a recursive function that returns the sum of all positive numbers between the number n received and 1. For example, when n is 3 it should return 1+2+3=6, and when n is 5 it should return 1+2+3+4+5=15.

def sum_positive_numbers(n): if n<1: return n return n + sum_positive_numbers(n-1) return 0 -------------------------------------------- print(sum_positive_numbers(3)) # Should be 6 print(sum_positive_numbers(5)) # Should be 15

The validate_users function is used by the system to check if a list of users is valid or invalid. A valid user is one that is at least 3 characters long. For example, ['taylor', 'luisa', 'jamaal'] are all valid users. When calling it like in this example, something is not right. Can you figure out what to fix?

def validate_users(users): for user in users: if is_valid(user): print(user + " is valid") else: print(user + " is invalid") validate_users(["purplecat"]) <---- !!!!!!! (square bracket it!)

Write a script that prints the multiples of 7 between 0 and 100. Print one multiple per line and avoid printing any numbers that aren't multiples of 7. Remember that 0 is also a multiple of 7.

for i in range(0,100,7): print(i)

Write a script that prints the first 10 cube numbers (x**3), starting with x=1 and ending with x=10.

for x in range(1,11): print(x**3)

Use Python to calculate how many different passwords can be formed with 6 lower case English letters. For a 1 letter password, there would be 26 possibilities. For a 2 letter password, each letter is independent of the other, so there would be 26 times 26 possibilities. Using this information, print the amount of possible passwords that can be formed with 6 letters.

p = 26 total = p ** 6 print(total)

Figure out what's the relationship between the strings "cat" and "Cat" by replacing the plus sign with comparison operators.

print("cat" > "Cat") "cat" is larger than "Cat"(In Python uppercase letters are alphabetically sorted before lowercase letters.)

FOR MY NOTE: [::2]

return elements[::2] # USE STEP TO SKIP 2 #return elements[::-1] # USE NEGATIVE TO REVERSE THEN SKIP #return elements[::3] # USE STEP TO SKIP 3

Keeping in mind there are 86400 seconds per day, write a program that calculates how many seconds there are in a week, if a week is 7 days. Print the result on the screen. Note: Your result should be in the format of just a number, not a sentence.

seconds_in_day = 86400 days_in_week = 7 sum = seconds_in_day * days_in_week print(sum)

There are two standard methods to sort a list in Python, sort and sorted. What is the difference between these two methods?

sorted returns a new list, while sort returns the same list reorganized.(So you were paying attention. Knowing the difference between these two methods is not nearly as important as the ability to research the tools we have available to us)

What is the elif keyword used for?

to handle more than 2 comparison cases. (The elif keyword is used in place of multiple embedded if clauses, when a single if/else structure is not enough.)

The "toc" dictionary represents the table of contents for a book. Fill in the blanks to do the following: 1) Add an entry for Epilogue on page 39. 2) Change the page number for Chapter 3 to 24. 3) Display the new dictionary contents. 4) Display True if there is Chapter 5, False if there isn't.

toc = {"Introduction":1, "Chapter 1":4, "Chapter 2":11, "Chapter 3":25, "Chapter 4":30} toc ["Epilogue"] = 39 toc ["Chapter 3"] = 24 print(toc) print("Chapter 5" in toc) ----------------- ___ # Epilogue starts on page 39 ___ # Chapter 3 now starts on page 24 ___ # What are the current contents of the dictionary? ___ # Is there a Chapter 5?

Which line from the program we just wrote combines each logged-in user attribute into one variable?

user_list = ", ".join(users) (The join() function of str gathers the user attributes (which is a string) into a single string, with commas separating the users.)

In Python, a dictionary can only hold a single value for a given key. To workaround this, our single value can be a list containing multiple values. Here we have a dictionary called "wardrobe" with items of clothing and their colors. Fill in the blanks to print a line for each item of clothing with each color, for example: "red shirt", "blue shirt", and so on.

wardrobe = {"shirt":["red","blue","white"], "jeans":["blue","black"]} for item, color in wardrobe.items(): for colorsub in color: print("{} {}".format(colorsub,item)) ------------ red shirt blue shirt white shirt blue jeans black jeans

The dict.update method updates one dictionary with the items coming from the other dictionary, so that existing entries are replaced and new entries are added. What is the content of the dictionary "wardrobe" at the end of the following code?

wardrobe = {'shirt': ['red', 'blue', 'white'], 'jeans': ['blue', 'black']} new_items = {'jeans': ['white'], 'scarf': ['yellow'], 'socks': ['black', 'brown']} wardrobe.update(new_items) --------------------------- answer : --------- {'shirt': ['red', 'blue', 'white'], 'jeans': ['white'], scarf': ['yellow'], 'socks': ['black', 'brown']}


संबंधित स्टडी सेट्स

Abnormal psych FINAL: Substance use and addictive D/o

View Set

Insurance contracts and regulations

View Set

RETIREMENT PLANNING: Ch. 3 - Qualified Retirement Plans

View Set

Chapter 29 Introduction to the Autonomic Nervous System

View Set