In Part One we wrote a code to convert distances from kilometres to miles. We could alter the program to convert from miles to kilometres. Now that we have learned about if and else statements, we can update our code to perform both conversions in a single program.
This was the code we had before
print('A PROGRAM TO CONVERT KILOMETERS TO MILES')
print('*' * 45)
print()
km = float(input('Enter distance in kilometers: '))
mi = km * 0.621
print('-' * 35)
print(km,'Kilometers in miles is',mi,'miles')
print()
print(f'{km} kilometers in miles is {mi} miles')
We would improve the program by including some if and else statements to our code.
You can compare with my solution below:
First of all, we would want the user to choose to enter the distance in kilometres or miles. If the user chooses kilometres, then the program uses the condition to calculate the conversion to miles and if the user enters the distance in miles, then the program uses the condition to calculate the conversion to kilometres.
We would request the user to enter the distance. After the user enters the distance, we would add a line to ask the user if it is in kilometres or miles
Now we would set up the condition if the user enters k (lower case), then the code executes to convert from kilometres to miles and prints out the result.
Else If the user enter m (lower case), then the code executes to convert from miles to kilometres.
Else, if the user enters any other value, we should remind the user to enter either k or m.
Here is my code below:
print('A PROGRAM TO CONVERT KILOMETRES TO MILES OR MILES TO KILOMETRES')
print('*' * 65)
print()
dist = float(input('Enter distance: '))
km_mi = input('Enter "k" for kilometres or "m" for miles: ')
if km_mi.lower() == 'k':
print(dist,'Kilometers in miles is',dist * 0.621,'miles')
elif km_mi.lower() == 'm':
print(dist,'Miles in kilometres is',dist / 0.621,'kilometres')
else:
print('Wrong Input - Enter either "k" or "m" for distance')
No comments:
Post a Comment