Our goal is to study sample Python codes that takes an input from the user, computes some formula and outputs the computed value to the user.
Before we proceed, we shall introduce the command input(). This command allows Python to get an input from the user. Any input from the user is treated as a string.
The code below converts a user-input Celsius (C) temperature to Fahrenheit (F) following the formula F = C*9/5 + 32.
user_in = input("Enter temperature in Celsius: ")
celsius = float(user_in)
fahrenheit = celsius * 9 / 5 + 32
farenheit = round(fahrenheit, 2)
print("Temperature in Fahrenheit is ", farenheit)
Enter temperature in Celsius: 10 Temperature in Fahrenheit is 50.0
In the first line, the command input() is used to get a user-input. The string inside input() is a prompt message displayed to the user before taking an input. The user-input is then assigned to the variable user_in.
In the second line, the value of user_in is converted to float to tell Python that the input by the user is a real number (not a string). This is an example of a technique called type conversion. Here, we use the command float().
The converted value is then assigned to the variable celsius.
In the third line, fahrenheit is computed following the known formula.
In the fourth line, the value of fahrenheit is updated by rounding it up to two decimal digits.
Finally, in the fifth line, the computed value of fahrenheit rounded up to two decimal digits is displayed to the user.
The code below simply adds up two user-input integers and outputs the resulting sum.
# take a user-input and then directly convert it to an integer data type and then assign it to addend1
addend1 = int(input("Enter a number: "))
addend2 = int(input("Enter another number: "))
sum = addend1 + addend2
print("Sum of the two integers is", sum)
Enter a number: 69 Enter another number: 23 Sum of the two integers is 92
What is noteworthy in the code above is lines 1 and 2.
In these lines, instead of creating a variable to store the result of the command input(), the result is directly passed to the command int() where it is directly converted to integer. The integer value is then assigned to a variable.
The code below simply extends the initial problem we explored earlier.
This time, the code asks for a user input representing the number of days and then outputs its the equivalent number of seconds.
days = int(input("Enter number of days: "))
seconds = days*24*60*60
print("Equivalent number of seconds: ", seconds)
Enter number of days: 1 Equivalent number of seconds: 86400
We are able to: