DEV Community

Cover image for Learn Python: Getting user input
Rishi
Rishi

Posted on • Edited on

2 1

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



Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more