Python

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

using del on dictionaries. Also, notice the while loop and the if statement.

# "New" means new compared to previous level provincial_capitals = { 'Manitoba': 'Winnipeg', 'BC': 'Victoria', 'Yukon': 'Whitehorse', 'Ontario': 'Toronto' } province_name = input() while province_name != 'exit': if province_name in provincial_capitals: print(provincial_capitals[province_name]) del provincial_capitals[province_name] # New line else: print('x') province_name = input()

Write a split_check function that returns the amount that each diner must pay to cover the cost of the meal.

# add to the bill total, then divide by the number of diners. def split_check(bill, poeple, tip_percentage=0.15, tax_percentage=0.09): tip = bill * tip_percentage tax = bill * tax_percentage return (bill + tip + tax) / people bill = float(input()) people = int(input()) # Cost per diner at the default tax and tip percentages print('Cost per diner:', split_check(bill, people)) bill = float(input()) people = int(input()) new_tax_percentage = float(input()) new_tip_percentage = float(input()) # Cost per diner at different tax and tip percentages print('Cost per diner:', split_check(bill, people, new_tax_percentage, new_tip_percentage))

Using some functions for statistics

#Lebron James: Statistics for 2003/2004 - 2012/2013 games_played = [79, 80, 79, 78, 75, 81, 76, 79, 62, 76] points = [1654, 2175, 2478, 2132, 2250, 2304, 2258, 2111, 1683, 2036] assists = [460, 636, 814, 701, 771, 762, 773, 663, 502, 535] rebounds = [432, 588, 556, 526, 592, 613, 554, 590, 492, 610] years = ["2003/2004", "2004/2005", "2005/2006", "2006/2007", "2007/2008", "2008/2009","2009/2010","2010/2011","2011/2012","2012/2013"] # Print total points total_points = sum(points) print("James' total points scored fromt he 2003/2004 season through the 2012/2013 season:", total_points) # Print average points total_games_played = sum(games_played) avg_ppg = total_points/total_games_played print("James' average points per game: ", avg_ppg) # Print best scoring year mx_pts = points.index(max(points)) print('James scored', max(points), 'points during best scoring year', str(years[mx_pts])) # Print worst scoring year min_pts = points.index(min(points)) print('James scored', min(points), 'points during worst scoring year', str(years[min_pts]))

What operator do you use to see if something is divisible by a specific number? IE check to see if something is divisible by 10.

% Example div_ten = 0 for i in num: if i % 10 == 0: div_ten += 1

Numerous engineering and scientific applications require finding solutions to a set of equations. Ex: 8x + 7y = 38 and 3x - 5y = -1 have a solution x = 3, y = 2. Given integer coefficients of two linear equations with variables x and y, use brute force to find an integer solution for x and y in the range -10 to 10.

''' Read in first equation, ax + by = c ''' a = int(input()) b = int(input()) c = int(input()) ''' Read in second equation, dx + ey = f ''' d = int(input()) e = int(input()) f = int(input()) solution_found = False #For every value of x from -10 to 10 for x in range(-10, 11): #For every value of y from -10 to 10 for y in range(-10, 11): #Check if the current x and y satisfy both equations. If so, output the solution, and finish. if ((a * x + b * y) == c and (d * x + e * y) == f): solution_found = True x_solution = x y_solution = y if solution_found: print('x = {} , y = {}'.format(x_solution, y_solution)) else: print('There is no solution')

An expression to print each price in stock_prices.

# NOTE: The following statement converts the input into a list container stock_prices = input().split() for price in stock_prices: print('$', price)

my_dict.get(key, default)

Reads the value of the key entry from the dictionary. If the key does not exist in the dictionary, then returns default.

my_dict.clear()

Removes all items from the dictionary.

a program that removes all non-alpha characters from the given input.

sample_str = input() sample_str = ''.join(item for item in sample_str if item.isalpha()) print(sample_str)

List methods

vals = [1, 4, 16] vals.append(9) vals.insert(2, 18) value = vals.pop() vals.remove(4) vals.remove(55) vals.count() vals.sort() vals.sort(reverse = True) vals is a list containing elements 1, 4, and 16. The statement vals.append(9) appends element 9 to the end of the list. The statement vals.insert(2, 18) inserts element 18 into position 2 of the list. The statement vals.pop() removes the last element, 9, from the list. The statement vals.remove(4) removes the first instance of element 4 from the list. The statement vals.remove(55) removes the first instance of element 55 from the list. The list does not contain the element 55 so vals is the same. The vals.count() counts the values in the list vals.sort() sorts the values in the list vals.sort(reverse = True) sorts the values list in descending order

Outputs average of list of positive integers List ends with 0 (sentinel) Ex: 10 1 6 3 0 yields (10 + 1 + 6 + 3) / 4, or 5

values_sum = 0 num_values = 0 curr_value = int(input()) while curr_value > 0: # Get values until 0 (or less) values_sum += curr_value num_values += 1 curr_value = int(input()) print('Average: {:.0f}\n'.format(values_sum / num_values))

The following example carries out a simple guessing game, allowing a user a number of guesses to fill out the complete word.

word = 'onomatopoeia' num_guesses = 10 hidden_word = '-' * len(word) guess = 1 while guess <= num_guesses and '-' in hidden_word: print(hidden_word) user_input = input('Enter a character (guess #{}): '.format(guess)) if len(user_input) == 1: # Count the number of times the character occurs in the word num_occurrences = word.count(user_input) # Replace the appropriate position(s) in hidden_word with the actual character. position = -1 for occurrence in range(num_occurrences): position = word.find(user_input, position+1) # Find the position of the next occurrence hidden_word = hidden_word[:position] + user_input + hidden_word[position+1:] # Rebuild the hidden word string guess += 1 if not '-' in hidden_word: print('Winner!', end=' ') else: print('Loser!', end=' ') print('The word was {}.'.format(word))

a program that takes a simple password and makes it stronger by replacing characters using the key below, and by appending "!" to the end of the input string. i becomes 1 a becomes @ m becomes M B becomes 8 s becomes $

word = input() password = '' for x in word: if(x=='i'): password+="1" elif(x=='a'): password += "@" elif (x == 'm'): password += "M" elif (x == 'B'): password += "8" elif (x == 's'): password += "$" else: password += x password += "!" print(password)

using my_dict.pop(key, default). What will this print? my_dict['burger'] = my_dict['sandwich'] val = my_dict.pop('sandwich') print(my_dict['burger'])

2.99

Using my_dict.get(key, default). What will this print? my_dict = dict(bananas=1.59, fries=2.39, burger=3.50, sandwich=2.99) my_dict.update(dict(soda=1.49, burger=3.69)) burger_price = my_dict.get('burger', 0) print(burger_price)

3.69

my_dict1.update(my_dict2)

Merges dictionary my_dict1 with another dictionary my_dict2. Existing entries in my_dict1 are overwritten if the same keys exist in my_dict2.

A program that lets a user enter N and that outputs N! (N factorial, meaning N*(N-1)*(N-2)*...*2*1). Hint:Use a loop variable i that counts from total-1 down to 1. Compare your output with some of these answers: 1:1, 2:2, 3:6, 4:24, 5:120, 8:40320.

N = int(input()) # Read user-entered number total = N # Initialize the loop variable i = N-1 while i >1: # Set total to total * (i) total = total*i # Decrement i i -= 1 print(total)

my_dict.pop(key, default)

Removes and returns the key value from the dictionary. If key does not exist, then default is returned.

Assign max_sum with the greater of num_a and num_b, PLUS the greater of num_y and num_z. Use just one statement. Hint: Call find_max() twice in an expression.

def find_max(num_1, num_2): max_val = 0.0 if (num_1 > num_2): # if num1 is greater than num2, max_val = num_1 # then num1 is the maxVal. else: # Otherwise, max_val = num_2 # num2 is the maxVal return max_val max_sum = 0.0 num_a = float(input()) num_b = float(input()) num_y = float(input()) num_z = float(input()) max_sum1 = find_max(num_a, num_b) max_sum2 = find_max(num_y, num_z) max_sum = max_sum1 + max_sum2 print('max_sum is:', max_sum)

Define stubs for the functions get_user_num() and compute_avg(). Each stub should print "FIXME: Finish function_name()" followed by a newline, and should return -1. Each stub must also contain the function's parameters.

def get_user_num(): print("FIXME: Finish get_user_num()") return -1 def compute_avg(user_num1, user_num2): print("FIXME: Finish compute_avg()") return -1 user_num1 = 0 user_num2 = 0 avg_result = 0 user_num1 = get_user_num() user_num2 = get_user_num() avg_result = compute_avg(user_num1, user_num2) print('Avg:', avg_result)

a program with a car's miles/gallon and gas dollars/gallon (both floats) as input, and output the gas cost for 10 miles, 50 miles, and 400 miles.

def driving_cost(driven_miles, miles_per_gallon, dollars_per_gallon): return driven_miles * (1.0/miles_per_gallon) * dollars_per_gallon #miles driven / gallons used = mpg #miles driven = end - start if __name__ == '__main__': miles_per_gallon = float(input()) dollars_per_gallon = float(input()) miles_10 = driving_cost(10, miles_per_gallon, dollars_per_gallon) miles_50 = driving_cost(50, miles_per_gallon, dollars_per_gallon) miles_400 = driving_cost(400, miles_per_gallon, dollars_per_gallon) print('{:.2f}'.format(miles_10)) print('{:.2f}'.format(miles_50)) print('{:.2f}'.format(miles_400))

Print air_temperature with 1 decimal point followed by C.

air_temperature = float(input()) print('{air_temperature:.1f}C'.format(air_temperature=air_temperature))

list.sort() method example: Alphabetically sorting book titles.

books = [] prompt = 'Enter new book: ' user_input = input(prompt).strip() while (user_input.lower() != 'exit'): books.append(user_input) user_input = input(prompt).strip() books.sort() print('\nAlphabetical order:') for book in books: print(book)

a for loop to print each contact in contact_emails in a dictionary

contact_emails = { 'Sue Reyn' : '[email protected]', 'Mike Filt': '[email protected]', 'Nate Arty': '[email protected]' } new_contact = input() new_email = input() contact_emails[new_contact] = new_email for contact in contact_emails: print(contact_emails[contact], 'is', contact)

Iterating through multi-dimensional lists using enumerate().

currency = [ [1, 5, 10 ], # US Dollars [0.75, 3.77, 7.53], #Euros [0.65, 3.25, 6.50] # British pounds ] for row_index, row in enumerate(currency): for column_index, item in enumerate(row): print('currency[{}][{}] is {:.2f}'.format(row_index, column_index, item)) output: currency[0][0] is 1.00 currency[0][1] is 5.00 currency[0][2] is 10.00 currency[1][0] is 0.75 currency[1][1] is 3.77 currency[1][2] is 7.53 currency[2][0] is 0.65 currency[2][1] is 3.25 currency[2][2] is 6.50

writing and calling a function that converts a temperature from Celsius into Fahrenheit. Use the formula F = C x 9/5 + 32. Test your program knowing that 50 Celsius is 122 Fahrenheit.

def c_to_f(): farenheight = temp_c * (9/5) + 32 return farenheight temp_c = float(input('Enter temperature in Celsius: ')) temp_f = None # FIXME: Call conversion function temp_f = temp_c * 9/5 + 32 print('Fahrenheit:' , temp_f)

a function calc_pyramid_volume() with parameters base_length, base_width, and pyramid_height, that returns the volume of a pyramid with a rectangular base. calc_pyramid_volume() calls the given calc_base_area() function in the calculation. Relevant geometry equations:Volume = base area x height x 1/3(Watch out for integer division).Sample output with inputs: 4.5 2.1 3.0

def calc_base_area(base_length, base_width): return base_length * base_width def calc_pyramid_volume(base_length, base_width, pyramid_height): return calc_base_area(base_length, base_width) * height * .3333333 length = float(input()) width = float(input()) height = float(input()) print('Volume for', length, width, height, "is:", calc_pyramid_volume(length, width, height))

Define a function calc_pyramid_volume with parameters base_length, base_width, and pyramid_height, that returns the volume of a pyramid with a rectangular base.

def calc_pyramid_volume(base_lenth, base_width, pyramid_height): return length * width * height/3 length = float(input()) width = float(input()) height = float(input()) print('Volume for', length, width, height, "is:", calc_pyramid_volume(length, width, height))

Using the celsius_to_kelvin function as a guide, create a new function, changing the name to kelvin_to_celsius, and modifying the function accordingly.

def celsius_to_kelvin(value_celsius): value_kelvin = 0.0 value_kelvin = value_celsius + 273.15 return value_kelvin def kelvin_to_celsius(value_kelvin): value_celcius = 0.0 value_celcius = value_kelvin - 273.15 return value_celcius value_c = 10.0 print(value_c, 'C is', celsius_to_kelvin(value_c), 'K') value_k = float(input()) print(value_k, 'K is', kelvin_to_celsius(value_k), 'C')

A pedometer treats walking 1 step as walking 2.5 feet. Define a function named feet_to_steps that takes a float as a parameter, representing the number of feet walked, and returns an integer that represents the number of steps walked. Then, write a main program that reads the number of feet walked as an input, calls function feet_to_steps() with the input as an argument, and outputs the number of steps.

def feet_to_steps(user_feet): return user_feet // 2.5 if __name__ == '__main__': user_feet = float(input()) print('{:.0f}'.format(feet_to_steps(user_feet)))

a function so that the main program below can be replaced by the simpler code that calls function mph_and_minutes_to_miles()

def mph_and_minutes_to_miles(miles_per_hour, minutes_traveled): hours_traveled = minutes_traveled / 60.0 miles_traveled = hours_traveled * miles_per_hour return miles_traveled miles_per_hour = float(input()) minutes_traveled = float(input()) print('Miles: {:f}'.format(mph_and_minutes_to_miles(miles_per_hour, minutes_traveled)))

a function number_of_pennies() that returns the total number of pennies given a number of dollars and (optionally) a number of pennies. Ex: If you have $5.06 then the input is 5 6, and if you have $4.00 then the input is 4.

def number_of_pennies(dollars, pennies=0): return dollars * 100 + pennies print(number_of_pennies(int(input()), int(input()))) # Both dollars and pennies print(number_of_pennies(int(input()))) # Dollars only

a function print_feet_inch_short(), with parameters num_feet and num_inches, that prints using ' and " shorthand. End with a newline. Remember that print() outputs a newline by default. Ex: print_feet_inch_short(5, 8) prints:

def print_feet_inch_short(num_feet, num_inches): print('{}\' {}\"'.format(num_feet, num_inches)) user_feet = int(input()) user_inches = int(input()) print_feet_inch_short(user_feet, user_inches) # Will be run with (5, 8), then (4, 11)

function print_popcorn_time() with parameter bag_ounces. If bag_ounces is less than 3, print "Too small". If greater than 10, print "Too large". Otherwise, compute and print 6 * bag_ounces followed by "seconds". End with a newline. Remember that print() automatically adds a newline.

def print_popcorn_time(bag_ounces): if bag_ounces < 3: print('Too small') elif bag_ounces > 10: print('Too large') else: print(bag_ounces * 6, 'seconds') user_ounces = int(input()) print_popcorn_time(user_ounces)

a function print_shampoo_instructions() with parameter num_cycles. If num_cycles is less than 1, print "Too few.". If more than 4, print "Too many.". Else, print "N : Lather and rinse." num_cycles times, where N is the cycle number, followed by "Done.".

def print_shampoo_instructions(num_cycyles): num_cycles = user_cycles if num_cycles < 1: print('Too few.') elif num_cycles > 4: print('Too many.') else: i = 1 while i <= num_cycles: print(i, ': Lather and rinse.') i = i + 1 print('Done.') return user_cycles = int(input()) print_shampoo_instructions(user_cycles)

a function swap that swaps the first and last elements of a list argument.

def swap(myList): #This swaps the first and last elements of the list myList[0],myList[-1]=myList[-1],myList[0] #This returns the list to the main function return myList values_list = input().split(',') # Program receives comma-separated values like 5,4,12,19 swap(values_list) print(values_list)

a program whose input is two integers and whose output is the two integers swapped.

def swap_values(user_val1, user_val2): return(user_val2, user_val1) if __name__ == '__main__': user_val1 = int(input()) user_val2 = int(input()) convert = str(swap_values(user_val1, user_val2)) print(convert)

List slicing: Using negative indices.

election_years = [1992, 1996, 2000, 2004, 2008] print(election_years[0:-1]) # Every year except the last print(election_years[0:-3]) # Every year except the last three print(election_years[-3:-1]) # The third and second to last years

Simple string splitting

file = 'C:/Users/Charles Xavier//Documents//report.doc' separator = '/' results = file.split(separator) print('Separator (/):'.format(separator), results)

Named tuple example

from collections import namedtuple Player = namedtuple('Player',['name', 'number', 'position', 'team']) cam = Player('Cam Newton', '1', 'Quarterback', 'Carolina Panthers') lebron = Player('Lebron James', '23', 'Small forward', 'Los Angeles Lakers') print(cam.name + '(#' + cam.number + ')' + ' is a ' + cam.position + ' for the ' + cam.team + '.') print(lebron.name + '(#' + lebron.number + ')' + ' is a ' + lebron.position + ' for the ' + lebron.team + '.')

a program whose input is: firstName middleName lastName and whose output is: lastName, firstInitial.middleInitial.

full_name = input().split() length = len(full_name) if length == 3: print(full_name[2]+ ', ' + full_name[0][0] + '.' + full_name[1][0] + '.') if length == 2: print(full_name[1]+ ', ' + full_name[0][0] + '.')

a function compute_gas_volume that returns the volume of a gas given parameters pressure, temperature, and moles. Use the gas equation PV = nRT, where P is pressure in Pascals, V is volume in cubic meters, n is number of moles, R is the gas constant 8.3144621 ( J / (mol*K)), and T is temperature in Kelvin.

gas_const = 8.3144621 def compute_gas_volume(gas_pressure, gas_temperature, gas_moles): return (gas_moles * gas_const * gas_temperature) / gas_pressure gas_pressure = float(input()) gas_moles = float(input()) gas_temperature = float(input()) gas_volume = 0.0 gas_volume = compute_gas_volume(gas_pressure, gas_temperature, gas_moles) print('Gas volume:', gas_volume, 'm^3')

When analyzing data sets, such as data for human heights or for human weights, a common step is to adjust the data. This adjustment can be done by normalizing to values between 0 and 1, or throwing away outliers. For this program, adjust the values by dividing all values by the largest value. The input begins with an integer indicating the number of floating-point values that follow.

height_list = [] num_val = int(input()) for i in range(0, num_val): value = float(input()) height_list.append(value) for i in height_list: print('{:.2f}'.format(float(i)/max(height_list)))

Write a while loop that prints from 1 to user_num, increasing by 1 each time.

i = 1 user_num = int(input()) # Assume positive while i <= user_num: print(i) i += 1

Loop else example: Finding a legal baby name.

import edit_distance #A few legal, acceptable Danish names legal_names = ['Thor', 'Bjork', 'Bailey', 'Anders', 'Bent', 'Bjarne', 'Bjorn', 'Claus', 'Emil', 'Finn', 'Jakob', 'Karen', 'Julie', 'Johanne', 'Anna', 'Anne', 'Bente', 'Eva', 'Helene', 'Ida', 'Inge', 'Susanne', 'Sofie', 'Rikkie', 'Pia', 'Torben', 'Soren', 'Rune', 'Rasmus', 'Per', 'Michael', 'Mads', 'Hanne', 'Dorte' ] user_name = input('Enter desired name:\n') if user_name in legal_names: print('{} is an acceptable Danish name. Congratulations.'.format(user_name)) else: print('{} is not acceptable.'.format(user_name)) for name in legal_names: if edit_distance.distance(name, user_name) < 2: print('You might consider: {},'.format(name), end=' ') break else: print('No close matches were found.') print('Goodbye.')

A list can be useful in solving various engineering problems. One problem is computing the voltage drop across a series of resistors. If the total voltage across the resistors is V, then the current through the resistors will be I = V/R, where R is the sum of the resistances. The voltage drop Vx across resistor x is then Vx = I · Rx.

num_resistors = 5 resistors = [] voltage_drop = [] print(f'{num_resistors} resistors are in the series.') print('This program calculates the'), print('voltage drop across each resistor.') input_voltage = float(input('Input voltage applied to circuit: ')) print (input_voltage) print(f'Input ohms of {num_resistors} resistors') for i in range(num_resistors): res = float(input('{i + 1})')) print(res) resistors.append(res) # Calculate current current = input_voltage / sum(resistors) # Calculate voltage drop over each resistor # Vx = I · Rx for i in range(num_resistors): voltage_drop = current * resistors[i] # Print the voltage drop per resistor print("The voltage drop is %.1f " % voltage_drop)

Common physics equations determine the x and y coordinates of a projectile object at any time, given the object's initial velocity and angle at time 0 with initial position x = 0 and y = 0. The equation for x is v * t * cos(a). The equation for y is v * t * sin(a) - 0.5 * g * t * t. The program's code asks the user for the object's initial velocity, angle, and height (y position), and then prints the object's position for every second until the object's y position is no longer greater than 0 (meaning the object fell back to Earth).

import math def trajectory(t, a, v, g, h): """Calculates new x,y position""" x = v * t * math.cos(a) y = h + v * t * math.sin(a) - 0.5 * g * t * t return (x,y) def degree_to_radians(degrees): """Converts degrees to radians""" return ((degrees * math.pi) / 180.0) gravity = 9.81 # Earth gravity (m/s^2) time = 1.0 # time (s) x_loc = 0 h = 0 angle = float(input('Launch angle (deg): ')) print(angle) angle = degree_to_radians(angle) velocity = float(input('Launch velocity (m/s): ')) print(velocity) height = float(input('Initial height (m): ')) y_loc = height print(y_loc) while ( y_loc >= 0.0 ): # While above ground print('Time {:3.0f} x = {:3.0f} y = {:3.0f}'.format(time, x_loc, y_loc)) x_loc, y_loc = trajectory(time, angle, velocity, gravity, height) time += 1.0

On a piano, a key has a frequency, say f0. Each higher key (black or white) has a frequency of f0 * rn, where n is the distance (number of keys) from that key, and r is 2(1/12). Given an initial key frequency, output that frequency and the next 4 higher key frequencies. Output each floating-point value with two digits after the decimal point, which can be achieved as follows: print('{:.2f} {:.2f} {:.2f} {:.2f} {:.2f}'.format(your_value1, your_value2, your_value3, your_value4, your_value5))

import math key_input = float(input()) power = 1.05946309436 distance = pow(power, 0) distance2 = pow(power, 1) distance3 = pow(power, 2) distance4 = pow(power, 3) distance5 = pow(power, 4) value1 = key_input * distance value2 = key_input * distance2 value3 = key_input * distance3 value4 = key_input * distance4 value5 = key_input * distance5 print('{:.2f} {:.2f} {:.2f} {:.2f} {:.2f}'.format(value1, value2, value3, value4, value5))

Given three floating-point numbers x, y, and z, output x to the power of z, x to the power of (y to the power of z), the absolute value of (x minus y), and the square root of (x to the power of z). Output each floating-point value with two digits after the decimal point, which can be achieved as follows: print('{:.2f} {:.2f} {:.2f} {:.2f}'.format(your_value1, your_value2, your_value3, your_value4))

import math x = float(input()) y = float(input()) z = float(input()) x_z = pow(x, z) x_y_z = pow(x, pow(y, z)) x_y_absolute = abs(x-y) x_zsquare_root = math.sqrt(x_z) print('{:.2f} {:.2f} {:.2f} {:.2f}'.format(x_z, x_y_z, x_y_absolute, x_zsquare_root ))

The following program calculates the number of times the sum of two dice (randomly rolled) is equal to six or seven.

import random num_sixes = 0 num_sevens = 0 num_rolls = int(input('Enter number of rolls:\n')) if num_rolls >= 1: for i in range(num_rolls): die1 = random.randint(1,6) die2 = random.randint(1,6) roll_total = die1 + die2 #Count number of sixes and sevens if roll_total == 6: num_sixes = num_sixes + 1 if roll_total == 7: num_sevens = num_sevens + 1 print('Roll {} is {} ({} + {})'.format(i, roll_total, die1, die2)) print('\nDice roll statistics:') print('6s:', num_sixes) print('7s:', num_sevens) else: print('Invalid number of rolls. Try again.')

An expression that continues to bid until the user enters 'n'.

import random random.seed(5) keep_bidding = '-' next_bid = 0 while keep_bidding != 'n': next_bid = next_bid + random.randint(1, 10) print('I\'ll bid ${}!'.format(next_bid)) print('Continue bidding?', end=' ') keep_bidding = input()

Below is a program that has a "conversation" with the user. The program asks the user to type something and then randomly prints one of four possible responses until the user enters "Goodbye". Note that the first few lines of the program represent a docstring: a multi-line string literal delimited at the beginning and end by triple-quotes. Either single ' or double " quotes can be used.

import random # Import a library to generate random numbers print('Tell me something about yourself.') print('You can type \'Goodbye\' at anytime to quit.\n') user_text = input() while user_text != 'Goodbye': random_num = random.randint(0, 2) # Gives a random integer between 0 and 2 if random_num == 0: print('\nPlease explain further.\n') elif random_num == 1: print("\nWhy do you say: '{}'?\n".format(user_text)) elif random_num == 2: print('\nWhat else can you share?\n') else: print('\nUh-oh, something went wrong. Try again.\n') user_text = input() print('It was nice talking with you. Goodbye.\n')

outputs the amount of money in a savings account each year for the user-entered number of years, with $10,000 initial savings and 5% yearly interest

initial_savings = 10000 interest_rate = 0.05 print('Initial savings of ${}'.format(initial_savings)) print('at {:.0f}% yearly interest.\n'.format(interest_rate*100)) years = int(input('Enter years: ')) print() savings = initial_savings i = 1 # Loop variable while i <= years: # Loop condition print(' Savings at beginning of year {}: ${:.2f}'.format(i, savings)) savings = savings + (savings*interest_rate) i = i + 1 # Increment loop variable print('\n')

The below program uses a for loop to calculate savings and interest. Try changing the range() function to print every three years instead, using the three-argument alternate version of range(). Modify the interest calculation inside the loop to compute three years worth of savings instead of one.

initial_savings = 10000 interest_rate = 0.05 years = int(input('Enter years: ')) print() savings = initial_savings for i in range(years): print(' Savings in year {}: ${:.2f}'.format(i, savings)) savings = savings + (savings*interest_rate) print('\n')

Convert user input into a list of integers.

inp = input('Enter numbers:') my_list = [int(i) for i in inp.split()] print(my_list)

Given num_rows and num_cols, print a list of all seats in a theater. Rows are numbered, columns lettered, as in 1A or 3E. Print a space after each seat.

num_rows = int(input()) num_cols = int(input()) # Note 1: You will need to declare more variables # Note 2: Place end=' ' at the end of your print statement to separate seats by spaces for curr_row in range(1, num_rows + 1): curr_col_let = 'A' for curr_col in range(1, num_cols + 1): print ('%d%s' % (curr_row, curr_col_let), end=' ') curr_col_let = chr(ord(curr_col_let) + 1) print()

Given the number of rows and the number of columns, write nested loops to print a rectangle.

num_rows = int(input()) num_cols = int(input()) for i in range(num_rows): for j in range(num_cols): print('*', end=' ') print()

if-else statement

input_month = input() input_day = int(input()) if (input_month == 'March') and (input_day >= 20 and input_day <= 31): print('Spring') elif (input_month == 'April') and (input_day > 0 and input_day <= 30) : print('Spring') elif input_month == 'May' and (input_day > 0 and input_day <= 31): print('Spring') elif (input_month == 'June') and (input_day > 0 and input_day <= 20): print('Spring') elif (input_month == 'June') and (input_day >= 21 and input_day <= 30): print('Summer') elif (input_month == 'July') and (input_day > 0 and input_day <= 31): print('Summer') elif (input_month == 'August') and (input_day > 0 and input_day <= 31): print('Summer') elif (input_month == 'September') and (input_day > 0 and input_day <= 21): print('Summer') elif (input_month == 'September') and (input_day >= 22 and input_day <= 30): print('Autumn') elif (input_month == 'October') and (input_day > 0 and input_day <= 31): print('Autumn') elif (input_month == 'November') and (input_day > 0 and input_day <= 30): print('Autumn') elif (input_month == 'December') and (input_day > 0 and input_day <= 20): print('Autumn') elif (input_month == 'December') and (input_day >= 21 and input_day <= 30): print('Winter') elif (input_month == 'January') and (input_day > 0 and input_day <= 31): print('Winter') elif (input_month == 'February') and (input_day > 0 and input_day <= 29): print('Winter') elif (input_month == 'March') and (input_day > 0 and input_day <= 19): print('Winter') else: print('Invalid')

Leap year if-else statement

is_leap_year = False input_year = int(input()) if (input_year % 4 == 0) and (input_year % 400 == 0 or input_year % 100 != 0): is_leap_year = True else: is_leap_year = False if is_leap_year == True: print('{:} - leap year'.format(input_year)) else: print('{:} - not a leap year'.format(input_year))

The following illustrates matrix multiplication for 4x2 and 2x3 matrices captured as two-dimensional lists.

m1_rows = 4 m1_cols = 2 m2_rows = m1_cols # Must have same value m2_cols = 3 m1 = [ [3, 4], [2, 3], [1, 2], [0, 2] ] m2 = [ [5, 4, 4], [0, 2, 3] ] m3 = [ [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0] ] # m1 * m2 = m3 for i in range(m1_rows): # for each row of m1 for j in range(m2_cols): # for each column of m2 # Compute dot product dot_product = 0 for k in range(m2_rows): # for each row of m2 dot_product += m1[i][k] * m2[k][j] m3[i][j] = dot_product for i in range(m1_rows): for j in range(m2_cols): print('{}'.format(m3[i][j]), end=' ') print() # Print single newline

Set example

male_names = { 'John', 'Bailey', 'Charlie', 'Chuck', 'Michael', 'Samuel', 'Jayden', 'Aiden', 'Henry', 'Lucas' } female_names = { 'Elizabeth', 'Meghan', 'Kim', 'Khloe', 'Bailey', 'Jayden', 'Aiden', 'Britney', 'Veronica', 'Maria' } # Use set methods to create sets all_names, neutral_names, and specific_names. all_names = set.union(male_names, female_names) neutral_names = set.intersection(male_names, female_names) specific_names = male_names.symmetric_difference(female_names) print(sorted(all_names)) print(sorted(neutral_names)) print(sorted(specific_names))

Using sorted() to create a new sorted list from an existing list without modifying the existing list

numbers = [int(i) for i in input('Enter numbers: ').split()] sorted_numbers = sorted(numbers) print('\nOriginal numbers:', numbers) print('Sorted numbers:', sorted_numbers)

The example program below shows how certain methods might be used to store passenger names and travel destinations in a database. The use of strip(), lower(), and upper() standardize user-input for easy comparison. Run the program below and add some passengers into the database. Add a duplicate passenger name, using different capitalization, and print the list again.

menu_prompt = ('Available commands:\n' ' (add) Add passenger\n' ' (del) Delete passenger\n' ' (print) Print passenger list\n' ' (exit) Exit the program\n' 'Enter command:\n') destinations = ['PHX', 'AUS', 'LAS'] destination_prompt = ('Available destinations:\n' '(PHX) Phoenix\n' '(AUS) Austin\n' '(LAS) Las Vegas\n' 'Enter destination:\n') passengers = {} print('Welcome to Mohawk Airlines!\n') user_input = input(menu_prompt).strip().lower() while user_input != 'exit': if user_input == 'add': name = input('Enter passenger name:\n').strip().upper() destination = input(destination_prompt).strip().upper() if destination not in destinations: print('Unknown destination.\n') else: passengers[name] = destination elif user_input == 'del': name = input('Enter passenger name:\n').strip().upper() if name in passengers: del passengers[name] elif user_input == 'print': for passenger in passengers: print('{} --> {}'.format(passenger.title(), passengers[passenger])) else: print('Unrecognized command.') user_input = input('Enter command:\n').strip().lower()

Program to calculate statistics from student test scores Uses some list functions

midterm_scores = [99.5, 78.25, 76, 58.5, 100, 87.5, 91, 68, 100] final_scores = [55, 62, 100, 98.75, 80, 76.5, 85.25] #Combine the scores into a single list all_scores = midterm_scores + final_scores num_midterm_scores = len(midterm_scores) num_final_scores = len(final_scores) print(num_midterm_scores, 'students took the midterm.') print(num_final_scores, 'students took the final.') #Calculate the number of students that took the midterm but not the final dropped_students = num_midterm_scores - num_final_scores print(dropped_students, 'students must have dropped the class.') lowest_final = min(final_scores) highest_final = max(final_scores) print('\nFinal scores ranged from', lowest_final, 'to', highest_final) average_midterm_scores = sum(midterm_scores) / len(midterm_scores) print('average midterm scores: {:.0f}'.format(average_midterm_scores)) average_final_scores = sum(final_scores) / len(final_scores) print('average final scores: {:.0f}'.format(average_final_scores))

example of changing element's values combines the len() and range() functions to iterate over a list and increment each element of the list by 5.

my_list = [3.2, 5.0, 16.5, 12.25] for i in range(len(my_list)): my_list[ i ] += 5

Add 10 to every element in a list

my_list = [5, 20, 50] my_list = [(i+10) for i in my_list] print(my_list)

Convert every element to a string in a list

my_list = [5, 20, 50] my_list = [str(i) for i in my_list] print(my_list)

using key argument for sort() and sorted() functions

my_list = [[25], [15, 25, 35], [10, 15]] sorted_list = sorted(my_list, key=max) print('Sorted list:', sorted_list)

Find the sum of the row with the smallest sum in a two-dimensional table.

my_list = [[5, 10, 15], [2, 3, 16], [100]] min_row = min([sum(row) for row in my_list]) print(min_row)

Find the sum of each row in a two-dimensional list.

my_list = [[5, 10, 15], [2, 3, 16], [100]] sum_list = [sum(row) for row in my_list] print(sum_list)

using key argument for sort() and sorted() functions

names = [] prompt = 'Enter name: ' user_input = input(prompt) while user_input != 'exit': names.append(user_input) user_input = input(prompt) no_key_sort = sorted(names) key_sort = sorted(names, key=str.lower) print('Sorting without key:', no_key_sort) print('Sorting with key: ', key_sort)

A list comprehension construct has the following form:

new_list = [expression for loop_variable_name in iterable] A list comprehension has three components: An expression component to evaluate for each element in the iterable object. A loop variable component to bind to the current iteration element. An iterable object component to iterate over (list, string, tuple, enumerate, etc).

A list comprehension can be extended with an optional conditional clause that causes the statement to return a list with only certain elements.

new_list = [expression for name in iterable if condition] Example: Return an even list of numbers: # Get a list of integers from the user numbers = [int(i) for i in input('Enter numbers:').split()] # Return a list of only even numbers even_numbers = [i for i in numbers if (i % 2) == 0] print('Even numbers only:', even_numbers)

Here is a nested loop example that graphically depicts an integer's magnitude by using asterisks, creating what is commonly called a histogram:

num = 0 while num >= 0: num = int(input('Enter an integer (negative to quit):\n')) if num >= 0: print('Depicted graphically:') for i in range(num): print('*', end=' ') print('\n') print('Goodbye.')

An example of using a loop to compute a mathematical quantity. The program computes the greatest common divisor (GCD) among two user-entered integers num_a and num_b, using Euclid's algorithm: If num_a > num_b, set num_a to num_a - num_b, else set num_b to num_b - num_a. Repeat until num_a equals num_b, at which point num_a and num_b both equal the GCD.

num_a = int(input('Enter first positive integer: ')) print() num_b = int(input('Enter second positive integer: ')) print() while num_a != num_b: if num_a > num_b: num_a = num_a - num_b else: num_b = num_b - num_a print('GCD is {}'.format(num_a))

a loop to populate the list user_guesses with a number of guesses. The variable num_guesses is the number of guesses the user will have, which is read first as an integer. Read each guess (an integer) one at a time using int(input()).

num_guesses = int(input()) user_guesses = [] for i in range(num_guesses): guess = int(input()) user_guesses.append(guess) print('user_guesses:', user_guesses)

Given positive integer num_insects, write a while loop that prints, then doubles, num_insects each iteration. Print values ≤ 100. Follow each number with a space.

num_insects = int(input()) # Must be >= 1 while (num_insects > 0 and num_insects <= 100): print(num_insects, end=' ') num_insects *= 2

A program that prints the number of stars you tell it to

num_printed = 0 num_stars = int(input()) while num_printed != num_stars: print('*') num_stars -= 1

Sort short_names in reverse alphabetic order.

user_input = input(). short_names = user_input.split() short_names.sort(reverse = True) print(short_names)

Finding the maximum even number in a list with a for loop

nums = [1, 4, 15, 456] max_even = None for num in nums: if num % 2 == 0: # The number is even? if max_even == None or num > max_even: # Greatest even number seen? max_even = num Loop iterates over all elements of list nums. Only larger even numbers update the value of max_num. Odd numbers, or numbers smaller than max_num, are ignored. When the loop ends, max_num is set to the largest even number 456.

Golf scores if-else statement

par = int(input()) num_strokes = int(input()) par_allowed = (3, 4, 5) if par in par_allowed: if num_strokes <= par - 2: print('Eagle') elif num_strokes <= par - 1: print('Birdie') elif num_strokes == par: print('Par') elif num_strokes >= par + 1: print('Bogey') else: print('Error')

Assign number_segments with phone_number split by the hyphens.

phone_number = input() number_segments = phone_number.split('-') area_code = number_segments[0] print('Area code:', area_code)

two-character .com names, where the second character can be a letter or a number, e.g., a2.com. Hint: Add a second while loop nested in the outer loop, but following the first inner loop, that iterates through the numbers 0-9.

print('Two-letter domain names:') letter1 = 'a' letter2 = '?' while letter1<='z': letter2 = 'a' while letter2<='z': print('%s%s.com'% (letter1,letter2)) letter2 = chr(ord(letter2) +1) num = 0 while num <= 9: print('%s%d.com' % (letter1, num)) num += 1 letter1 = chr(ord(letter1) + 1)

The reverse argument can be set to a Boolean value, either True or False. Setting reverse=True flips the sorting from lower-to-highest to highest-to-lowest

sorted([15, 20, 25], reverse=True)

convert any negative numbers in a list to 0 Enter numbers:5 67 -5 -4 5 6 6 4 0: 5 1: 67 2: -5 3: -4 4: 5 5: 6 6: 6 7: 4 New numbers: 5 67 0 0 5 6 6 4

user_input = input('Enter numbers: ') tokens = user_input.split() # Convert strings to integers nums = [] for token in tokens: nums.append(int(token)) # Print each position and number print() for pos, val in enumerate(nums): print('{}: {}'.format(pos, val)) # Change negative values to 0 for pos in range(len(nums)): if nums[pos] < 0: nums[pos] = 0 # Print new numbers print('New numbers: ') for num in nums: print(num, end=' ')

The following program allows the user to enter a phone number that includes letters, which appear on phone keypads along with numbers and are commonly used by companies as a marketing tactic (e.g., 1-555-HOLIDAY). The program then outputs the phone number using numbers only.

user_input = input('Enter phone number:\n') phone_number = '' for character in user_input: if ('0' <= character <= '9') or (character == '-'): phone_number += character elif ('a' <= character <= 'c') or ('A' <= character <= 'C'): phone_number += '2' elif ('d' <= character <= 'f') or ('D' <= character <= 'F'): phone_number += '3' elif ('g' <= character <= 'i') or ('G' <= character <= 'I'): phone_number += '4' elif ('j' <= character <= 'l') or ('J' <= character <= 'L'): phone_number += '5' elif ('m' <= character <= 'o') or ('M' <= character <= 'O'): phone_number += '6' elif ('p' <= character <= 's') or ('P' <= character <= 'S'): phone_number += '7' elif ('t' <= character <= 'v') or ('T' <= character <= 'V'): phone_number += '8' elif ('w' <= character <= 'z') or ( 'W' <= character <= 'Z'): phone_number += '9' else: phone_number += '?' print('Numbers only: %s' % phone_number)

Modify short_names by deleting the first element and changing the last element to Joe.

user_input = input() short_names = user_input.split() del short_names[0] short_names[2] = 'Joe' print(short_names)

Using del to remove a key from a dictionary

user_input = input() entries = user_input.split(',') country_capital = {} for pair in entries: split_pair = pair.split(':') country_capital[split_pair[0]] = split_pair[1] # country_capital is a dictionary, Ex. { 'Germany': 'Berlin', 'France': 'Paris' del country_capital ['Prussia'] print('Prussia deleted?', end=' ') if 'Prussia' in country_capital: print('No.') else: print('Yes.') print ('Spain deleted?', end=' ') if 'Spain' in country_capital: print('No.') else: print('Yes.') print ('Togo deleted?', end=' ') if 'Togo' in country_capital: print('No.') else: print('Yes.')

Write a loop to print all elements in hourly_temperature. Separate elements with a -> surrounded by spaces.Sample output for the given program with input: '90 92 94 95' 90 -> 92 -> 94 -> 95

user_input = input() hourly_temperature = user_input.split() for index in range(len(hourly_temperature)): print(hourly_temperature[index], end=' ') if index != (len(hourly_temperature) - 1): print('->', end=' ') print('') # print newline

Assign sum_extra with the total extra credit received given list test_grades. Iterate through the list with for grade in test_grades:. The code uses the Python split() method to split a string at each space into a list of string values and the map() function to convert each string value to an integer. Full credit is 100, so anything over 100 is extra credit.

user_input = input() test_grades = list(map(int, user_input.split())) # test_grades is an integer list of test scores sum_extra = 0 # Initialize 0 before your loop for grade in test_grades: if grade > 100: sum_extra = sum_extra + (grade - 100) print('Sum extra:', sum_extra)

Write a program that takes a string and an integer as input, and outputs a sentence using the input values as shown in the example below. The program repeats until the input string is quit and disregards the integer input that follows.

user_input = input() tokens = user_input.split() while tokens[0] != 'quit': #['apples', '5'] print(f'Eating {tokens[1]} {tokens[0]} a day keeps the doctor away.') user_input = input() tokens = user_input.split()

Print the two-dimensional list mult_table by row and column. On each line, each character is separated by a space. Hint: Use nested loops. Sample output with input: '1 2 3,2 4 6,3 6 9': 1 | 2 | 3 2 | 4 | 6 3 | 6 | 9

user_input= input() lines = user_input.split(',') # This line uses a construct called a list comprehension, introduced elsewhere, # to convert the input string into a two-dimensional list. # Ex: 1 2, 2 4 is converted to [ [1, 2], [2, 4] ] mult_table = [[int(num) for num in line.split()] for line in lines] for row in mult_table: for index, cell in enumerate(row): if index != (len(row) - 1): print(cell, '|', end=' ') else: print(cell)

An expression that executes the loop body as long as the user enters a non-negative number

user_num = int(input()) while user_num >= 0: print('Body') user_num = int(input()) print('Done.')

A while loop that repeats while user_num ≥ 1. In each loop iteration, divide user_num by 2, then print user_num.

user_num = int(input()) while user_num >= 1: user_num = user_num / 2 print(user_num)

a program that takes in a string representing an integer as input, and outputs yes if every character is a digit 0-9.

user_string = input() if user_string.isdigit(): print('yes') else: print('no')

a program whose input is a string which contains a character and a phrase, and whose output indicates the number of times the character appears in the phrase.

user_string = input(str()) # determine location of character is in phrase character = user_string[0] phrase = user_string[1:] # output # of times character is in phase if character in phrase: num_occur = phrase.count(character) print(num_occur) if character not in phrase: print(0)

if-else statement to print 'LOL means laughing out loud' if user_tweet contains 'LOL'.

user_tweet = input() if 'LOL' in user_tweet: print('LOL means laughing out loud.') else: print('No abbreviation.')

Replaces any occurrence of 'TTYL' with 'talk to you later'

user_tweet = input() decoded_tweet = user_tweet.replace('TTYL', 'talk to you later') print(decoded_tweet)

a program that takes in a positive integer as input, and outputs a string of 1's and 0's representing the integer in binary. For an integer x, the algorithm is: As long as x is greater than 0 Output x modulo 2 (remainder is either 0 or 1) Assign x with x divided by 2

x = int(input()) while x > 0 : print(x % 2, end='') x //= 2 print()

Write a program that prints the U.S. presidential election years from 1792 to present day, knowing that such elections occur every 4 years.

year = 1792 current_year = 2021 while year <= current_year: # Print the election year print(year) year = year + 4


Ensembles d'études connexes

NURS 310- Fundamentals of Nursing- CH 41.- EAQs- Oxygenation

View Set

[RPH] Rizal Retraction Must Know Facts

View Set