# Complete the function to print the first X number of characters in the given string
def printFirst(mystring, x):
# Student code goes here
my_str = mystring[0:x]
print(my_str, end='')
print(' ')
# expected output: WGU
printFirst('WGU College of IT', 3)
# expected output: WGU College
printFirst('WGU College of IT', 11)
=======================================================================================
# Complete the function to return the first two items in the given list
def getFirstTwo(mylist):
# Student code goes here
x = mylist[:2]
return x
# expected output: [8, 3]
print(getFirstTwo([8,3,5,2,10]))
# expected output: [15, 2]
print(getFirstTwo([15,2,10,12]))
=======================================================================================
# Complete the function to return the last two items in the given list
def getLastTwo(mylist):
# Student code goes here
y = mylist[-2:]
return y
# expected output: [2, 10]
print(getLastTwo([8,3,5,2,10]))
# expected output: [9, 12]
print(getLastTwo([15,2,9,12]))
=======================================================================================
# Complete the function to add num1 to the end of the given list
def addToEnd(mylist, num1):
# Student code goes here
mylist.append(num1)
return mylist
# expected output: [4, 5, 6, 7]
print(addToEnd([4,5,6], 7))
# expected output: [9, 8, 7, 6]
print(addToEnd([9,8,7], 6))
=======================================================================================
# Complete the function to add num1 to the front of the given list
def addToFront(mylist, num1):
# Student code goes here
mylist.insert(0, num1)
return mylist
# expected output: [3, 4, 5, 6]
print(addToFront([4,5,6], 3))
# expected output: [10, 9, 8, 7]
print(addToFront([9,8,7], 10))
=======================================================================================
# Complete the function to return a new list containing
# the first two and last two items in the given list
def getFirstTwoAndLastTwo(mylist):
# Student code goes here
first = mylist[:2]
last = mylist[-2:]
# print(first)
# print(last)
final = first + last
return final
# expected output: [8, 3, 19, 1]
print(getFirstTwoAndLastTwo([8,3,7,15,2,10,19,1]))
# expected output: [7, 15, 3, 5]
print(getFirstTwoAndLastTwo([7,15,2,10,19,1,3,5]))
=======================================================================================
# Complete the function to remove the first item in the given list
def removeFirst(mylist):
# Student code goes here
mylist.pop(0)
return mylist
# expected output: [7, 8, 9]
print(removeFirst([6,7,8,9]))
# expected output: [2, 3, 4]
print(removeFirst([1,2,3,4]))
=======================================================================================
# Complete the function to remove the third item in the given list
def removeThird(mylist):
# Student code goes here
mylist.pop(2)
return mylist
# expected output: [6, 7, 9]
print(removeThird([6,7,8,9]))
# expected output: [1, 2, 4]
print(removeThird([1,2,3,4]))
=======================================================================================
# Complete the function to order the values in the list
# if ascending is true then order lowest to highest
# if ascending is false then order highest to lowest
def sortList(mylist, ascending):
# Student code goes here
if ascending == True:
mylist.sort()
else:
mylist.sort(reverse=True)
return mylist
# expected output: [4, 12, 19, 33]
print(sortList([19,4,33,12], True))
# expected output: [33, 19, 12, 4]
print(sortList([19,4,33,12], False))
=======================================================================================
# Complete the function to return a dictionary using
# list1 as the keys and list2 as the values
def createDict(list1, list2):
# Student code goes here
x = dict(zip(list1, list2))
return x
# expected output: {'tomato': 'red', 'banana': 'yellow', 'lime': 'green'}
print(createDict(['tomato', 'banana', 'lime'], ['red','yellow','green']))
# expected output: {'Brazil': 'Brasilia', 'Ireland': 'Dublin', 'Indonesia': 'Jakarta'}
print(createDict(['Brazil', 'Ireland', 'Indonesia'], ['Brasilia','Dublin','Jakarta']))
=======================================================================================
# Complete the function to return a dictionary value
# if it exists or return Not Found if it doesn't exist
def findDictItem(mydict, key):
# Student code goes here
return mydict.get(key, 'Not found')
# if key in mydict.keys():
# return mydict[key]
# else:
# return 'Not Found'
# expected output: yellow
print(findDictItem({'tomato': 'red', 'banana': 'yellow', 'lime': 'green'} , 'banana'))
# expected output: Not Found
print(findDictItem({'Brazil': 'Brasilia', 'Ireland': 'Dublin', 'Indonesia': 'Jakarta'},'Cameroon'))
=======================================================================================
# Complete the function to remove a dictionary item if it exists
def removeDictItem(mydict, key):
# Student code goes here
if key in mydict.keys():
mydict.pop(key)
return mydict
else:
return mydict
# expected output: {'tomato': 'red', 'lime': 'green'}
print(removeDictItem({'tomato': 'red', 'banana': 'yellow', 'lime': 'green'} , 'banana'))
# expected output: {'Brazil': 'Brasilia', 'Ireland': 'Dublin', 'Indonesia': 'Jakarta'}
print(removeDictItem({'Brazil': 'Brasilia', 'Ireland': 'Dublin', 'Indonesia': 'Jakarta'},'Cameroon'))
=======================================================================================
# Complete the function to print every key and value
def printDict(mydict):
# Student code goes here
for key, val in mydict.items():
print(key,'=',val, sep='')
# expected output:
# tomato=red
# banana=yellow
# lime=green
printDict({'tomato': 'red', 'banana': 'yellow', 'lime': 'green'})
# expected output:
# Brazil=Brasilia
# Ireland=Dublin
# Indonesia=Jakarta
printDict({'Brazil': 'Brasilia', 'Ireland': 'Dublin', 'Indonesia': 'Jakarta'})
riders_per_ride = 3 # Num riders per ride to dispatch
line = [] # The line of riders
num_vips = 0 # Track number of VIPs at front of line
menu = ('(1) Reserve place in line.\n' # Add rider to line
'(2) Reserve place in VIP line.\n' # Add VIP
'(3) Dispatch riders.\n' # Dispatch next ride car
'(4) Print riders.\n'
'(5) Exit.\n\n')
user_input = input(menu).strip().lower()
while user_input != '5':
if user_input == '1': # Add rider
name = input('Enter name:').strip().lower()
print(name)
line.append(name)
elif user_input == '2': # Add VIP
print('FIXME: Add new VIP')
name = input('Enter name:').strip().lower()
line.insert(0, name)
num_vips += 1
# Add new rider behind last VIP in line
# Hint: Insert the VIP into the line at position num_vips.
#Don't forget to increment num_vips.
elif user_input == '3': # Dispatch ride
print('FIXME: Remove riders from the front of the line.')
line.pop(0)
num_vips -= 1
# Remove last riders_per_ride from front of line.
# Don't forget to decrease num_vips, if necessary.
elif user_input == '4': # Print riders waiting in line
print('{} person(s) waiting:'.format(len(line)), line)
else:
print('Unknown menu option')
user_input = input('Enter command: ').strip().lower()
print(user_input)
non_alpha = input()
i = ''
for each in non_alpha:
# print(each)
if each.isalpha():
i += each
print(i)
char_phr = input()
character = char_phr[0]
phrase = char_phr[1:]
count = 0
for char in phrase:
if character == char:
count += 1
#print(count)
if count == 1:
print(f'{count} {character}')
else:
print(f'{count} {character}\'s')
Input: Pat Silly Doe
Output: Doe, P.S.
name = input()
name = name.split()
myName = len(name)
if myName == 3:
print(name[2] + ', ' + name[0][0] + '.' + name[1][0] + '.')
else:
print(name[1]+ ', ' + name[0][0] + '.')
Checker for integer string
user_string = input()
if user_string.isdigit():
print('Yes')
else:
print('No')
Q: Define a function named swap_values that takes four integers as parameters and swaps the first with the second, and the third with the fourth values. Then write a main program that reads four integers from input, calls function swap_values() to swap the values, and prints the swapped values on a single line separated with spaces.
A:
def swap_values(user_val1, user_val2, user_val3, user_val4):
temp1 = user_val1
temp2 = user_val3
user_val1 = user_val2
user_val2 = temp1
user_val3 = user_val4
user_val4 = temp2
print(user_val1, end=' ')
print(user_val2, end=' ')
print(user_val3, end=' ')
print(user_val4)
return user_val1, user_val2, user_val3, user_val4
if __name__ == '__main__':
user_val1 = int(input())
user_val2 = int(input())
user_val3 = int(input())
user_val4 = int(input())
swap_values(user_val1, user_val2, user_val3, user_val4)
Q: Write 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 % 2 (remainder is either 0 or 1)
x = x // 2
Note: The above algorithm outputs the 0's and 1's in reverse order. You will need to write a second function to reverse the string.
A:
def int_to_reverse_binary(integer_value):
binary_num = ''
while integer_value > 0:
x = integer_value % 2
binary_num += str(x)
integer_value = integer_value // 2
return binary_num
def string_reverse(input_string):
str_to_list = list(input_string)
reverse_list = str_to_list[::-1]
list_to_str = ''.join(reverse_list)
return list_to_str
if __name__ == '__main__':
integer_value = int(input())
a = int_to_reverse_binary(integer_value)
print(string_reverse(a))
Q: Write a function driving_cost() with input parameters miles_per_gallon, dollars_per_gallon, and miles_driven, that returns the dollar cost to drive those miles. All items are of type float. The function called with arguments (20.0, 3.1599, 50.0) returns 7.89975.
Define that function in a program whose inputs are the car's miles per gallon and the price of gas in dollars per gallon (both float). Output the gas cost for 10 miles, 50 miles, and 400 miles, by calling your driving_cost() function three times.
Output each floating-point value with two digits after the decimal point, which can be achieved as follows:
print(f'{your_value:.2f}')
A:
def driving_cost(miles_per_gallon, dollars_per_gallon, miles_driven):
dollar_cost = (dollars_per_gallon/miles_per_gallon) * miles_driven
return dollar_cost
def two_input_parameters():
miles_per_gallon = float(input())
dollars_per_gallon = float(input())
miles_input = [10, 50, 400]
for i in miles_input:
cost_without_miles_driven = driving_cost(miles_per_gallon, dollars_per_gallon, i)
print(f'{cost_without_miles_driven:.2f}')
def fully_input():
cost = driving_cost()
return f'{cost:.2f}'
if __name__ == '__main__':
two_input_parameters()
Q: 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 as an integer.
Use floating-point arithmetic to perform the conversion.
A:
def feet_to_steps(user_feet):
return int(user_feet / 2.5)
if __name__ == '__main__':
user_feet = float(input())
step = feet_to_steps(user_feet)
print(step)
def modify(num_list):
num_list[1] = 99 # Modifying only the copy
my_list = [10, 20, 30]
modify(my_list[:]) # Pass a copy of the list
print(my_list) # my_list does not contain 99!
[10, 20, 30]
Mutable
def modify(num_list):
num_list[1] = 99
my_list = [10, 20, 30]
modify(my_list)
print(my_list) # my_list still contains 99!
[10, 99, 30]
def echo(text: str, repetitions: int = 3) -> str:
"""Imitate a real-world echo."""
echoed_text = ""
for i in range(repetitions, 0, -1):
echoed_text += f"{text[-i:]}\n"
return f"{echoed_text.lower()}."
if __name__ == "__main__":
text = input("Yell something at a mountain: ")
print(echo(text))
def kilo_to_pounds(kilos):
return (kilos * 2.204)
# Main part of the program starts here. Do not remove the line below.
if __name__ == '__main__':
kilos = float(input())
pounds = kilo_to_pounds(kilos)
print(f'{pounds:.3f} lbs')
student_scores = [75, 84, 66, 99, 51, 65]
def get_grade_stats(scores):
# Calculate the arithmetic mean
mean = sum(scores)/len(scores)
# Calculate the standard deviation
tmp = 0
for score in scores:
tmp += (score - mean )**2
std_dev = (tmp/len(scores))**0.5
# Package and return average, standard deviation in a tuple
return mean, std_dev
# Unpack tuple
average, standard_deviation = get_grade_stats(student_scores)
print('Average score:', average)
print('Standard deviation:', standard_deviation)
Average score: 73.33333333333333
Standard deviation: 15.260697523012796
Q: The * and ** characters in *args and **kwargs are the important symbols. Using "args" and "kwargs" is standard practice, but any valid identifier is acceptable (like perhaps using *condiments in the sandwich example).
One or both of *args or **kwargs can be used. They must come last (and in that order if both are used) in the parameter list, otherwise an error occurs.
Below is a practical example showing how to combine normal parameters and the **kwargs parameter. Operating systems like Windows or MacOS have a command line that can be used instead of clicking icons on a desktop. To start an application using the command line, a user types in the application name followed by some options (usually denoted with a double dash --), as in notepad.exe or firefox.exe --new-window=http://google.com --private-toggle=True. The example below uses a function call's arguments to generate a new command.
A:
def gen_command(application, **kwargs):
command = application
for argument in kwargs:
command += f' --{argument}={kwargs[argument]}'
return command
print(gen_command('notepad.exe')) # No options
print(gen_command('Powerpoint.exe', file='pres.ppt', start=True, slide=3))
def print_sandwich(bread, meat, *args):
print(f'{meat} on {bread}', end=' ')
if len(args) > 0:
print('with', end=' ')
for extra in args:
print(extra, end=' ')
print('')
print_sandwich('sourdough', 'turkey', 'mayo')
print_sandwich('wheat', 'ham', 'mustard', 'tomato', 'lettuce')
turkey on sourdough with mayo
ham on wheat with mustard tomato lettuce
def print_sandwich(meat, bread, **kwargs):
print(f'{meat} on {bread}')
for category, extra in kwargs.items():
print(f' {category}: {extra}')
print()
print_sandwich('turkey', 'sourdough', sauce='mayo')
print_sandwich('ham', 'wheat', sauce1='mustard', veggie1='tomato', veggie2='lettuce')
turkey on sourdough
sauce: mayo
ham on wheat
sauce1: mustard
veggie1: tomato
veggie2: lettuce
Q: Write 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.
Sample output with inputs: 5 6 4
506
400
A:
def number_of_pennies(dollars=0, pennies=0):
total_of_pennies = (dollars * 100) + pennies
return total_of_pennies
print(number_of_pennies(int(input()), int(input()))) # Both dollars and pennies
print(number_of_pennies(int(input()))) # Dollars only
if my_list == None: # Create a new list if a list was not provided
my_list = []
my_list.append(value)
return my_list
numbers = append_to_list(50) # default list appended with 50
print(numbers)
numbers = append_to_list(100) # default list appended with 100
print(numbers)
Output
[50]
[100]
def append_to_list(value, my_list=[]):
my_list.append(value)
return my_list
numbers = append_to_list(50) # default list appended with 50
print(numbers)
numbers = append_to_list(100) # default list appended with 100
print(numbers)
Output
[50]
[50, 100]
Q: Write a function swap that swaps the first and last elements of a list argument.
Sample output with input: 'all,good,things,must,end,here'
['here', 'good', 'things', 'must', 'end', 'all']
A:
def swap(values):
values[0], values[-1] = values[-1], values[0]
return
values_list = input().split(',') # Program receives comma-separated values like 5,4,12,19
swap(values_list)
print(values_list)
Q: Address the FIXME comments. Move the respective code from the while-loop to the created function. The add_grade function has already been created.
Note: split() and strip() are string methods further explained elsewhere. split() separates a string into tokens using any whitespace as the default separator. The tokens are returned in a list (i.e., 'a b c'.split() returns ['a', 'b', 'c']). strip() returns a copy of a string with leading and trailing whitespace removed.
A:
def add_grade(student_grades):
print('Entering grade. \n')
name, grade = input(grade_prompt).split()
student_grades[name] = grade
print(student_grades)
def delete_name(student_grades):
print('Deleting grade.\n')
name = input(delete_prompt)
del student_grades[name]
def print_grades(student_grades):
print('Printing grades.\n')
for name, grade in student_grades.items():
print(name, 'has a', grade)
student_grades = {} # Create an empty dict
grade_prompt = "Enter name and grade (Ex. 'Bob A+'):\n"
delete_prompt = "Enter name to delete:\n"
menu_prompt = ("1. Add/modify student grade\n"
"2. Delete student grade\n"
"3. Print student grades\n"
"4. Quit\n\n")
command = input(menu_prompt).lower().strip()
while command != '4': # Exit when user enters '4'
if command == '1':
add_grade(student_grades)
elif command == '2':
delete_name(student_grades)
elif command == '3':
print_grades(student_grades)
else:
print('Unrecognized command.\n')
command = input().lower().strip()
print(student_grades)
Q: The problem below uses the function get_numbers() to read a number of integers from the user. Three unfinished functions are defined, which should print only certain types of numbers that the user entered. Complete the unfinished functions, adding loops and branches where necessary. Match the output with the below sample:
Enter 5 integers:
0 5
1 99
2 -44
3 0
4 12
Numbers: 5 99 -44 0 12
Odd numbers: 5 99
Negative numbers: -44
A:
size = 5
def get_numbers(num):
numbers = []
user_input = input(f'Enter {num} integers:\n')
i = 0
for token in user_input.split():
number = int(token) # Convert string input into integer
numbers.append(number) # Add to numbers list
print(i, number)
i += 1
return numbers
def print_all_numbers(numbers):
# Print numbers
allnum = ''
for num in numbers:
number = str(num)
allnum += number + ' '
print('Numbers:', allnum)
def print_odd_numbers(numbers):
# Print all odd numbers
oddnum = ''
for num in numbers:
if num % 2 == 1:
number = str(num)
oddnum += number + ' '
print('Odd numbers:', oddnum)
def print_negative_numbers(numbers):
# Print all negative numbers
neg_num = ''
for num in numbers:
if num < 0:
number = str(num)
neg_num = number + ' '
print('Negative numbers:', neg_num)
nums = get_numbers(size)
print_all_numbers(nums)
print_odd_numbers(nums)
print_negative_numbers(nums)
def print_menu():
print("Today's Menu:")
print(' 1) Gumbo')
print(' 2) Jambalaya')
print(' 3) Quit\n')
quit_program = False
while not quit_program :
print_menu()
choice = int(input('Enter choice: '))
if choice == 3 :
print('Goodbye')
quit_program = True
else :
print('Order: ', end='')
if choice == 1 :
print('Gumbo')
elif choice == 2 :
print('Jambalaya')
print()
Q: Brute force equation solver
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.
Input:
8
7
38
3
-5
-1
Output: x = 3 , y = 2
Approach:
For every value of x from -10 to 10
For every value of y from -10 to 10
Check if the current x and y satisfy both equations. If so, output the solution, and finish.
Else, There is no solution
A:
x1 = 0
y1 = 0
for x in range(-10, 11):
for y in range(-10, 11):
if a * x + b * y == c:
if d * x + e * y ==f:
x1 = x
y1 = y
if x1 == 0 & y1 == 0:
print('There is no solution')
else:
print('x =', x1, ',', 'y =', y1)
Q: Convert to reverse binary
Write a program that takes in a positive integer as input, and outputs a string of 1's and 0's representing the integer in reverse binary. For an integer x, the algorithm is:
Note: The above algorithm outputs the 0's and 1's in reverse order.
A:
number = int(input())
number_list =[]
while number > 0:
number_list.append(number)
number = number // 2
for num in number_list:
if num % 2 == 0:
print('0', end='')
else:
num % 2 == 1
print('1', end='')
print('')
Or
number = int(input())
binary_string = ''
while(number > 0):
digit = number % 2
binary_string += str(digit)
number = number // 2
print(binary_string)
#if you want to correct the binary digit, add reversed[::-1]
number = int(input())
number_list =[]
while number > 0:
number_list.append(number)
number = number // 2
number_list_reversed = number_list[::-1]
for num in number_list_reversed:
if num % 2 == 0:
print('0', end='')
else:
num % 2 == 1
print('1', end='')
Q: Create a different version of the program that:
Calculates the number of times the sum of the randomly rolled dice equals each possible value from 2 to 12.
Repeatedly asks the user for the number of times to roll the dice, quitting only when the user-entered number is less than 1. Hint: Use a while loop that will execute as long as num_rolls is greater than 1.
Prints a histogram in which the total number of times the dice rolls equals each possible value is displayed by printing a character, such as *, that number of times. The following provides an example:
A:
import random
num_rolls = int(input())
two = ''
three = ''
four = ''
five = ''
six = ''
seven = ''
eight = ''
nine = ''
ten = ''
eleven = ''
twelve = ''
while num_rolls >= 1:
num_rolls -= 1
for i in range(num_rolls):
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
roll_total = die1 + die2
if roll_total == 2:
two += '*'
if roll_total == 3:
three += '*'
if roll_total == 4:
four += '*'
if roll_total == 5:
five += '*'
if roll_total == 6:
six += '*'
if roll_total == 7:
seven += '*'
if roll_total == 8:
eight += '*'
if roll_total == 9:
nine += '*'
if roll_total == 10:
ten += '*'
if roll_total == 11:
eleven += '*'
if roll_total == 12:
twelve += '*'
print('2s:', two)
print('3s:', three)
print('4s:', four)
print('5s:', five)
print('6s:', six)
print('7s:', seven)
print('8s:', eight)
print('9s:', nine)
print('10s:', ten)
print('11s:', eleven)
print('12s:', twelve)
2s:
3s:
4s:
5s:
6s: ***
7s: *
8s: *
9s: *
10s: **
11s: **
12s: *
number of names to print:
names = ['Janice', 'Clarice', 'Martin', 'Veronica', 'Jason']
num = int(input('Enter number of names to print: '))
for i in range(len(names)):
if i == num:
break
print(names[i], end= ' ')
else:
print('All names printed.')
origins = [4, 8, 10]
for index in range(len(origins)):
value = origins[index] # Retrieve value of element in list.
print(f'Element {index}: {value}')
Element 0: 4
Element 1: 8
Element 2: 10
origins = [4, 8, 10]
for value in origins:
index = origins.index(value) # Retrieve index of value in list
print(f'Element {index}: {value}')
Element 0: 4
Element 1: 8
Element 2: 10
The enumerate() function retrieves both the index and corresponding element value at the same time, providing a cleaner and more readable solution.
origins = [4, 8, 10]
for (index, value) in enumerate(origins):
print(f'Element {index}: {value}')
Element 0: 4
Element 1: 8
Element 2: 10
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(f'{user_name} is an acceptable Danish name. Congratulations.')
else:
print(f'{user_name} is not acceptable.')
for name in legal_names:
if user_name[0] == name[0]:
print(f'You might consider: {name},', end=' ')
break
else:
print('No close matches were found.')
print('Goodbye.')
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(f'Roll {i} is {roll_total} ({die1} + {die2})')
print('\nDice roll statistics:')
print('6s:', num_sixes)
print('7s:', num_sevens)
else:
print('Invalid number of rolls. Try again.')
Q: "Simon Says" is a memory game where "Simon" outputs a sequence of 10 characters (R, G, B, Y) and the user must repeat the sequence. Create a for loop that compares each character of the two strings. For each matching character, add one point to user_score. Upon a mismatch, end the loop.
A:
simon_pattern = input()
user_pattern = input()
user_score = 0
for i in range(10):
if simon_pattern[i] != user_pattern[i]:
break
user_score += 1
print('User score:', user_score)
What is the output of the following code?
c1 = 'a'
while c1 < 'b':
c2 = 'a'
while c2 <= 'c':
print(f'{c1}{c2}', end = ' ')
c2 = chr(ord(c2) + 1)
c1 = chr(ord(c1) + 1)
aa ab ac
c1 = 'a'
while c1 < 'b':
c2 = 0
while c2 <= 9:
print(f'{c1}{c2}', end = ' ')
c2 = c2 + 1
c1 = chr(ord(c1) + 1)
a0 a1 a2 a3 a4 a5 a6 a7 a8 a9
Q: Modify the program to include 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.
A:
letter1 = 'a'
letter2 = '?'
while letter1 <= 'z': # Outer loop
letter2 = 0
while letter2 <= 9: # Inner loop
print(f'{letter1}{letter2}.com')
letter2 += 1
letter1 = chr(ord(letter1) + 1)
Q:
"""
Program to print all 2-letter domain names.
Note that ord() and chr() convert between text and the ASCII or Unicode encoding:
- ord('a') yields the encoded value of 'a', the number 97.
- ord('a')+1 adds 1 to the encoded value of 'a', giving 98.
- chr(ord('a')+1) converts 98 back into a letter, producing 'b'
"""
A:
print('Two-letter domain names:')
letter1 = 'a'
letter2 = '?'
while letter1 <= 'z': # Outer loop
letter2 = 'a'
while letter2 <= 'z': # Inner loop
print(f'{letter1}{letter2}.com')
letter2 = chr(ord(letter2) + 1)
letter1 = chr(ord(letter1) + 1)
Two-letter domain names:
aa.com
ab.com
ac.com
ad.com
ae.com
…
zy.com
Zz.com
A for loop assigns the loop variable with a dictionary's keys
channels = {
'MTV': 35,
'CNN': 28,
'FOX': 11,
'NBC': 4,
'CBS': 12
}
for c in channels:
print(f'{c} is on channel {channels[c]}')
MTV is on channel 35
CNN is on channel 28
FOX is on channel 11
NBC is on channel 4
CBS is on channel 12
max = -1
val = Get next input
while val is not 0
If val > max
max = val
val = Get next input
input_year = int(input())
if input_year % 4 == 0 and input_year % 100 != 0 or input_year % 400 == 0:
print(input_year, '- leap year')
else:
print(input_year, '- not a leap year')
Q: The dates for each season in the northern hemisphere are:
Spring: March 20 - June 20
Summer: June 21 - September 21
Autumn: September 22 - December 20
Winter: December 21 - March 19
A:
month = input()
day = int(input())
if month not in ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']:
print('Invalid')
if month == 'March':
if day > 19 and day < 32:
print('Spring')
elif day < 1 or day > 31:
print('Invalid')
if month == 'April':
if day > 0 and day < 31:
print('Spring')
elif day < 1 or day > 30:
print('Invalid')
if month == 'May':
if day > 0 and day < 32:
print('Spring')
elif day < 1 or day > 31:
print('Invalid')
if month == 'June':
if day > 0 and day < 21:
print('Spring')
elif day < 1 or day > 30:
print('Invalid')
if month == 'June':
if day > 20 and day < 31:
print('Summer')
elif day < 1 or day > 30:
print('Invalid')
if month == 'July':
if day > 0 and day < 32:
print('Spring')
elif day < 1 or day > 31:
print('Invalid')
if month == 'August':
if day > 0 and day < 32:
print('Summer')
elif day < 1 or day > 31:
print('Invalid')
if month == 'September':
if day > 0 and day < 22:
print('Summer')
if month == 'September':
if day > 21 and day < 31:
print('Autumn')
elif day < 1 or day > 30:
print('Invalid')
if month == 'October':
if day > 0 and day < 32:
print('Autumn')
elif day < 1 or day > 31:
print('Invalid')
if month == 'November':
if day > 0 and day < 32:
print('Autumn')
elif day < 1 or day > 30:
print('Invalid')
if month == 'December':
if day > 0 and day < 21:
print('Autumn')
elif day < 1 or day > 31:
print('Invalid')
if month == 'December':
if day > 20 and day < 32:
print('Winter')
if month == 'January':
if day > 0 and day < 32:
print('Winter')
elif day < 1 or day > 31:
print('Invalid')
if month == 'February':
if day > 0 and day < 30:
print('Winter')
elif day < 1 or day > 29:
print('Invalid')
if month == 'March':
if day > 0 and day < 20:
print('Winter')
elif day < 1 or day > 31:
print('Invalid')
Q: Primary U.S. interstate highways are numbered 1-99. Odd numbers (like the 5 or 95) go north/south, and evens (like the 10 or 90) go east/west. Auxiliary highways are numbered 100-999, and service the primary highway indicated by the rightmost two digits. Thus, I-405 services I-5, and I-290 services I-90. Note: 200 is not a valid auxiliary highway because 00 is not a valid primary highway number.
Given a highway number, indicate whether it is a primary or auxiliary highway. If auxiliary, indicate what primary highway it serves. Also, indicate if the (primary) highway runs north/south or east/west.
A:
highway_number = int(input())
ones = highway_number % 10
tens = highway_number // 10 % 10
if highway_number < 100:
if ones == 0 and tens == 0:
print(highway_number, 'is not a valid interstate highway number.')
elif highway_number % 2 == 0:
print('I-', highway_number, ' is primary, going east/west.', sep='') ←— no space
else:
print('I-', highway_number, ' is primary, going north/south.', sep='')
if highway_number > 99 and highway_number < 1000:
if ones == 0 and tens == 0:
print(highway_number, 'is not a valid interstate highway number.')
elif highway_number % 2 == 0:
if tens == 0:
print('I-', highway_number, ' is auxiliary, serving I-', ones, ', going east/west.', sep='')
else:
print('I-', highway_number, ' is auxiliary, serving I-', tens, ones, ', going east/west.', sep='')
elif highway_number % 2 == 1:
if tens == 0:
print('I-', highway_number, ' is auxiliary, serving I-', ones, ', going north/south.', sep='')
else:
print('I-', highway_number, ' is auxiliary, serving I-', tens, ones, ', going north/south.', sep='')
if highway_number > 999:
print(highway_number, 'is not a valid interstate highway number.')