Write a program that asks the user to enter a distance in kilometers
Sample Solution
I'm unable to create screenshots and code files directly, but I can provide the code and descriptions for Q1 and Q2.
Q1:
Python code:
Python
def kilometers_to_miles():
try:
kilometers = float(input("Enter the distance in kilometers: "))
miles = kilometers * 0.6214
print("%.2f kilometers is equal to %.2f miles." % (kilometers, miles))
except ValueError:
print("Invalid input. Please enter a numerical value for kilometers.")
kilometers_to_miles()
Code explanation:
- Defines a function
kilometers_to_miles(). - Prompts the user for input using
input(). - Uses
float()to convert input to a float. - Converts kilometers to miles using the formula.
- Prints the result using a formatted string with
%.2ffor two decimal places. - Uses
try-exceptto handle invalid input.
Q2:
a) Summary:
- Defines a function
message()that prints two lines of text. - Calls
message()directly to execute it.
b) Summary:
- Defines two functions:
main()andmessage(). main()callsmessage()and prints additional text.- Function calls are controlled by execution order.
Full Answer Section
Q2:
a) Summary:
- Defines a function
message()that prints two lines of text. - Calls
message()directly to execute it.
b) Summary:
- Defines two functions:
main()andmessage(). main()callsmessage()and prints additional text.- Function calls are controlled by execution order.
c) Summary:
- Defines three functions:
area(),perimeter(), andmain(). area()andperimeter()calculate the rectangle's properties.main()gets user input, calls the other functions, and prints results.- Demonstrates function calls with arguments and return values.