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



Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs