1.10 Activity 3 - Strings and I - O
1.10 Activity 3 - Strings and I - O
1.10 Activity 3 - Strings and I - O
Write a program that outputs a times table from a given (user entered)
integer value. It should start at 2 and output only the EVEN multiples. If
the user entered the value 13, the even times table would be outputted in
the following format:
if user_input.lower() == "exit":
break
try:
number = int(user_input)
generate_even_times_table(number)
except ValueError:
print("Invalid input. Please enter a valid number.")
Exercise two
In the sample code given for 'Iteration' in 1.1, there is a program for
printing out a left-sided triangle of stars.
*
* * ***
** ** *****
*** *** ***
**** **** *
Left-sided Right-sided Diamond
My Solution:
def print_left_triangle(symbol, size):
for i in range(1, size+1):
print(symbol * i)
# Menu
print("Pattern Generator")
print("1. Print Left Triangle")
print("2. Print Right Triangle")
print("3. Print Diamond")
if choice == "1":
print_left_triangle(symbol, size)
elif choice == "2":
for i in range(1, size+1):
spaces = size - i
print(" " * spaces, end="")
print(symbol * i)
elif choice == "3":
print_diamond(symbol, size)
else:
print("Invalid choice.")
Exercise three
Write a program that outputs a calendar, given two values inputted by the
user. If the user inputs the values of 30 and 7, the following structure
will be produced, where 30 generates the number of days in the month and 7
(Sunday) indicates which day of the week the calendar starts on. The user
should only be able to input a valid range of numbers, and regardless of
the values entered the calendar should always output 7 lines (even if some
of them are blank).
My Solution:
def generate_calendar(days_in_month, starting_day):
# Validate input
if days_in_month < 28 or days_in_month > 31 or starting_day < 1 or
starting_day > 7:
print("Invalid input.")
return
# Define weekdays
weekdays = ["M", "T", "W", "Th", "F", "S", "Su"]
# Print header
for weekday in weekdays:
print(f"{weekday:3s}", end="")
print()
# Generate calendar
generate_calendar(days_in_month, starting_day)