DEV Community

Cover image for Learn Python: Getting user input
Rishi
Rishi

Posted on • Edited on

Learn Python: Getting user input

input()

input() prompts the user for an input then passes the captured value(s) to a variable as a string.


question = "Hello, what is your name?"
print(question)

username = input("Enter your name: ")

welcome_message = f"Hello {username}, Welcome!"
print(welcome_message);
Enter fullscreen mode Exit fullscreen mode

Formatting input

By default, the input is of type string.
If we attempt an arithmetic calculation on this input (string multiplied by an integer), we'll end up having an 'interesting' result 😂

age = input("Enter your age: ")
message = f"You have lived for {age * 12} months."
print(message)
Enter fullscreen mode Exit fullscreen mode

To avoid this we'll need to convert the string into an integer.

age = input("Enter your age: ")
age_number = int(age)
message = f"You have lived for {age_number * 12} months."
print(message)
Enter fullscreen mode Exit fullscreen mode

Simplifying... but not good practice.

age = int(input("Enter your age: "))
message = f"You have lived for approximately {age * 365} days."
print(message)
Enter fullscreen mode Exit fullscreen mode

It is good practice to keep the calculations separate from the message template.
It makes the code easier to understand, debug & maintain.

age = int(input("Enter your age: "))

# constants
DAYS_IN_YEAR = 365
HOURS_IN_A_DAY = 24
MINUTES_IN_AN_HOUR = 60
SECONDS_IN_A_MINUTE = 60

#calculation
age_in_seconds = age * DAYS_IN_YEAR * HOURS_IN_A_DAY * MINUTES_IN_AN_HOUR *  SECONDS_IN_A_MINUTE

message = f"You have lived for approximately {age_in_seconds} seconds."
print(message)
Enter fullscreen mode Exit fullscreen mode



Top comments (0)