Programming with Python Final

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Tuples are enclosed with

()

How do you access the value associated with the key 'a' in the dictionary d = {'a': 1, 'b': 2}?

(d.get('a') and d['a']

To concatenate two strings a and b, you can use the

+ operator

What will the following code output? x = 10 while x > 0: print (x) x = x - 1

10 9 8 7 6 5 4 3 2 1

startswith( prefix ) return whether (True or False) the string starts with the given prefix string .isdigit() method is used to check weather all the characters in a given strings are numerical digits in range 0 to 9 endswith( suffix ) returns whether (True or False) the string ends with the given string suffix .isalpha() method is used to check weather all the characters in a given strings are alphabets join( sequence ) joins the sequence of values into a single string value with the "called on" string as the separator

All true

Elements of a dictionary can be accessed through their index

False

Lambda functions in Python can only take a single argument.

False

Sets can contain duplicate elements.

False

Tuples are mutable, which means their elements can be changed after creation.

False

Given the function below, what is the output of the call greet("Alice")? def greet(name): return f"Hello,{name}!"

Hello, Alice!

Function called as states_traveled("california", "Neveda","Arizona")? def states_traveled(*states): for state in states: print(f"I have traveled to {state}")

I have traveled to California I have traveled to Neveda I have travled to Arizona I have traveled to Nevada I have traveled to Arizona

Role of return statement:

Specifies the value to be passed back by the function

Every recursive function must have a base case to avoid infinite recursion

True

List, Tuples, and Sets can be converted from one data structure to another

True

The keys in a dictionary can be accessed using .keys() method.

True

The keys in a dictionary can be accessed using .values() method.

True

The keys in the dictionary are unique

True

'programming with python'.split('',1) Output?

['programming'.'with python']

List comprehension that will create a list of even numbers from 0 to 10

[x for x in range(11) if x% 2 == 0]

Write a code that will take a number as an input and return whether is it even or odd.

a=int(input("Enter any number: ")) b='' if a%2 == 0: b="even" else: b="odd" print(b)

Given a list a_list = list(range(1,11)) Use list comp. to iterate over a list print a list.. Composed of each value in a list multiplied by 10

a_list = list(range(1,11)) result = [x*10 for x in a_list] print(result)

enumerate() method:

adds a counter to a list, tuple, string, etc., and returns it as an "enumerate" object, allowing the item's index to be kept while iterating.

Create a program to detect if user is a minor

age= int(input("enter your age: ")) if age >=18: print("You're an adult") else: print("You're a minor")

Define a class called "Book" that stores three instance variables "title," "author," and "price" of a book. Tite and author stored as strings and price as decimal value.Then create an instance called book1

class Book: def __init__(self,title,author,price): self.title = title self.author = author self.price = price def__str(self): returnf"Title:{self.title}, Author:{self.author}, Price:$[self.price:.2f]" book = Book("Happy Halloween", "Mark", 95.98) print(book1)

Write a Python program that creates a class called Dog. Provide two instances (name and walk). Create an object in the class.

class Dog: def __init__(self, name): self.name = name def walk(self): print(f"{self.name} likes to go on walks.") my_dog = Dog('Scarlett') print(f"{my_dog.name} is a puppy!") my_dog.walk()

Create a class named people, add three instances (name, age and favorite color, abbreviate these as you wish). Create an object in said class using your info and print it.

class People: def __init__(self, n, a, fc) : self.name=n self.age=a self.favorite_color=fc sophia=People("Sophia","18", "green") print(f' My name is {sophia.name}. I am {sophia.age} years old, and my favorite color is {sophia.favorite_color}.')

To count the number of occurrences of an element in a tuple, use the method

count()

ictionary d of that maps department abbreviations to their full names Initially containing:'CS': 'Computer Science' 'CE': 'Computer Engineering' 'METR': 'Meteorology'Print value associated with CS, Update value CE to full name, Remove METR

d= { 'CS': 'Computer Science', 'CE': 'Computer Engineering', 'METR':'Meteorology' } print("Value for 'CS':", d['CS']) d['CE'] = 'Civil Engineering' print("Updated dictionary:",d) del d['METR'] print{"Dictionary after removing 'METR':", d)

Defining a function

def

Define a function area_rectangle that takes two parameters, length and breadth, calculates the area of the rectange and returns the result

def area_rectangle(length,breadth): area = length * breadth return area

Create a function that returns the area of any triangle and takes two arguments (base, height).

def area_triangle(base, height): area=(base/2)*height return area

Write a code that with find the factorial and stop when a negative number is entered

def calculate_factorial(): print("Enter numbers to calculate their factorial. Enter a negative number to stop.") while True: num = int(input("Enter a number: ")) if num < 0: print("Program stopped.") break factorial = 1 for i in range(1, num + 1): factorial *= i print(f"Factorial of {num} is: {factorial}") calculate_factorial()

Function called count_occurrences(text) that texts a single sentence as a string argument called text. Analyze the string and return a dictionary where each key is a unique word from the sentence, and each corresponding value is the count of occurrences of the word.

def count_occurrences(text): words = text.split() word_count = [] for word in words: word_count [word]= words.count(word) return word_count

Calculate the factorial of a number

def factorial(n): if n==1: return 1 else: return n*factorial(n-1)

Take a decimal number as input and returns it formatted as a price with a precision of two decimal places with a $ symbol at the beginning

def format_price(price): formatted_price="${:.2f}".format(price) return formatted_price

How do you pass multiple arguments to a function using args?

def function(*args):

Valid function with a default argument:

def hello(name="John"): return name

Create a function that returns a new list with all negative numbers from a given list, then print the returned list

def print_neg_nums(list_nums): neg_list = [] for i in list_nums: if i < 0: neg_list.append(i) return neg_list listb = [6,2,-10,-6,-7,-8,23,4] print(print_neg_nums(listb))

Write code that checks if a character is a vowel

def replace_vowels(s): vowels = "aeiou" result = "" for char in s: if char.lower() in vowels: # Check if the character is a vowel next_vowel = vowels[(vowels.index(char.lower()) + 1) % len(vowels)] if char.isupper(): result += next_vowel.upper() else: result += next_vowel else: result += char # Non-vowel characters remain the same return result

Function that returns the sum of two numbers a and b?

def sum(a,b):return a + b

Write a functionthat takes two parameters, a list of words and a letter and returns a # new list of all words that only start with the specified letter.

def words_starting_with(words, letter): return [word for word in words if word.startswith(letter)] #or input_list = ["apple", "banana", "avocado", "apricot"] specified_letter = "a" result = words_starting_with(input_list, specified_letter) print(result)

Given the following dictionary, invert the dictionary: dictA={"dorine":21, "dayra":22, "sandra":20, "maggie":19}

dictA={"dorine":21, "dayra":22, "sandra":20, "maggie":19} def invert_dictionary(dictionary): return {values:keys for keys, values in dictionary.items()} print(invert_dictionary(dictA))

To add a new key-value pair to a dictionary, use the syntax

dictionary[key] = value

s = "Hello World" print(s[1:5]) Output?

ello

Given a list called items, use list slicing to print a list that contains all the elements at even index positions from the original list in the reverse order. items= [10, 20, 30, 40, 50]

even_items = items [::2] even_reverse = even_items [::-1] print (even_reverse)

If you want to create a subplot with two rows and one column, which of the following commands should you use?

fig, ax = plt.subplots(2, 1)

Check if any words contain punctuation

for idx, word in enumerate(inputList.copy()): for char in word: if char.isdigit() or char.isalpha(): pass else: inputList[idx] = word.replace(char,")

Explain what get method does in this code and the output? d ={'CS':'ComputerScience','CE':'ComputerEngineering', 'METR':'Meterology'} print(d.get('Bio',None'))

get method checks to see if Bio exists in the dictionary (d).Since it is not, the get method returns the 'None" value # Output = None

calling a function named greet

greet()

Write a Python program that prints what is said in a text file from a different path directory.

import os path=input("Enter path:") file=input("Enter file name:") file=os.path.join(path, file) with open(file) as f: c = f.read() print(c)

Write a Python program that has a random letter generator of the alphabet and a random number generator that ranges from 0-9 that then prints a result from each.

import random x =[random.randint(0,9)] z = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] zr = random.choice(z) print(x,zr)

#7 Prompt the user to enter an input integer, generates a random number between 0 and 100, and prints the sum of the random number and the input integer.

import random #Allows you to use functions for generating random numbers. n = int(input("Enter a number:")) #Prompts the user to enter an integer and then converts that to an integer. x = random.randint (0,100) #Generates a random number between 0 and 100. result = n + x #Calculates the sum of input and the random number. print("The sum of", n, "and", x, "is:", result) #Prints the output value of n, x, and their sum.

Which of the following methods is used to find the index of a substring in a string?

index() and find()

Given a list called "items" that contains 5 elements, use list slicing to replace the third element with two zeros items = [1,2,3,4,5]

items [2:3] = [0,0]

Find the median for a given list and print it: lista = [3,2,5,2,7,3,6,3,6]

length = len(lista) lista.sort() if length % 2 == 0: median1 = lista[length//2] median2 = lista[length//2 - 1] median = (median1 + median2)/2 else: median = lista[length//2] print(f"Median is: {median}")

Which will correctly add an element to the end of the list?

list1.append(4)

Given a list of numbers in the range (0, 100), create a list of odd numbers greater than 20

list1=list(range (0, 100)) list2= [x for x in list1 if x%2 != 0 and x>20] print(list2)

Given a list called "num" that contains integers, using For loop, write a program that prints the sum of all numbers in a list.

num = [1, 2, 3, 4, 5] #The variable num is defined. sum = 0 #The sum = 0 puts the variable sum to zero to store the total. for i in num: #Repeats over each element i in the num list. sum = sum + i #Adds each element of i to the total sum. print ("The sum of all numbers in the list is:",sum) #Prints the output of the total sum of numbers in the list.

Prompt the user to input an integer from the console. The program should check if the entered number is divisble by 3 and print a message to the console indicating whether or not the number is divisble by 3.

num = int(input("Enter a number:")) #Prompts the user to enter an integer and converts the input from a string to integer. if num%3 == 0: #Checks if the remainder when the num is divided by 3 is zero. If so the num is divisble by 3. print(num, "Is divisible by 3) else: print(num, "Is not divisible by 3")

Find the error in the code: number = input ("Enter a number between 1 and 10:") if number%2 == 0: print ("The number is divisble by 2") else: print ("The number is not divisble by 2")

number is a string, but needs to be converted to an integer.

#10 Given a list of numbers = [1,5,3,7,6]. Use a for loop to iterate over the list and print the following output to the console. Note that the number of times a number is printed ineach line is equal to the value of the number.

numbers = [1, 5, 3, 7, 6] #Numbers is defined for i in numbers: #Outer loop: repeats over each number in the list which assigns it to num. for i in range(i): #Inner loop: uses the range based on the value of num. print(i,end="") #Prints the number followed by a space, and the print() at the end movesthe cursor to the next line after printing all occurances. print ()

You want to plot two datasets, one as a red solid line and anotheras green triangles, and add a legend titled "Data".Which of these lines of code correctly sets the legend?

plt.legend(title='Data', loc='best')

What is the following code snippet do? Explain all the contents of the below code.

plt.savefig('plot.pdf', format='pdf')

Methods to use to remove a key from a dictionary?

pop()

Finish the code for number in range(1,6):

print(f"number: {number}")

Which of the following operations will add an element to the set s?

s.add()

Explain what setdefault method does in this code and what is the ouput? d = {'CS':'ComputerScience','CE':'ComputerEngineering','METR':'Meterology') print(d.setdefault('MATH','Mathematics'))

setdefault method checks to see if MATH is present in the dictionary(d). Since it is not present, the program adds the key MATH with the value of Mathematics. The method returns the value and the dictionary will be updated. # Output = Mathematics

Given a list called "list_num" Write a code that gives the smallest number in the list. list_num = [11, 5, 3, 9, 2]

small = min(list_num) print(small)

Given a list called "num" write a code to sort the items in the list and print it to the console (list operations) num= [5,2,9,1,5,6]

sorted_num = sorted (num) print (sorted_num)

Use a for loop to generate a list of square numbers from 1 to 5.

square_nums = [] for x in range(1, 6): square = x**2 square_nums.append(square) print(square_nums)

The method to convert a string to all lowercase in Python is

string.lower()

The string method ______ removes all whitespace from both ends of a string.

strip()

Convert: def sum_squares(x,y): return x**2 + y**2 To a lambda function

sum_squares = lambda x,y:x**2 + y**2

Which of the following is a valid way to access the second element of a tuple t?

t[1]

How do you create an empty tuple in Python

tuple() and ()

Unpack elements from a tuple.

tuple1=('1','2','3') a,b,c=tuple1 print(a) print(b) print(c)

#9 Using an infinite while loop, prompt the user for input inside the loop and print whatever they enter. The loop should coninue asking for input until the user types "exit"

while True: #Creates an infinite loop that does not stop until the break statement occurs. user_input = input ("Enter anything:")#Prompts the user to enter something. if user_input == "exit": #If the user types exit, then the break statement is executed and the loop is left. break print (user_input) #Anything else that is entered will continue the loop forever and will be printed.

Prompt the user to input an integer and store it in a variable called x. Write an if statement with a single condition to check if either x is not even or x is greater than 10.

x = int(input("Enter a number:")) #Prompts the user to enter an integer and converts the input to an integer. if not (x%2 == 0) or (x > 10):#Checks both if x is even and greater than 10. print(x, "meets the condition,")#If both check out then the prgram prints that it is true. else: #If the condition is not true, the program prints that it did not meet the condition. print(x,"does not meet the condition.")

Fill out the missing part of the code that contains all integers greater than 10 and less/= 89 a_list = list(range(100)) my_list = [x for x in a_list if

x > 10 and x <= 89]

What is the output of the following code snippet? A = {1, 2, 3} B = {3, 4, 5} print( A.union(B))

{1,2,3,4,5}

What will be the output of the following code? s = {1, 2, 3} s.add(2) print(s)

{1,2,3}

The purpose of __init__ method in a Python class?

It is called automatically when a new object is created and intializes instance attributes

Does a set guarantee the order of items as they are added? Specifically, when using a loop to print the items, will they be returned in the same order in which they were added?

No

What does the plt.plot([1, 2, 3, 4], 'g^') command do?

Plots only green triangles pointing up


Set pelajaran terkait

Short Story Literary Terms Study Guide

View Set

Ch_3_Interaction of X-Radiation With Matter

View Set

Managerial Accounting RQ Chapter 13 #1

View Set

Chapter 7 (Energy and Metabolism) and Chapter 8 (Cellular Respiration)

View Set

PNE 105 Chapter 46: Caring for Clients with Disorders of the Lower GI Tract. Med-Surg.

View Set

nclex pn safe, effective care environment

View Set

AP Calculus AB Unit 1: Limits and Continuity

View Set

Medical-Surgical: Immune and Infectious

View Set