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 AssemblyAI tool

Challenge Submission: SpeechCraft - AI-Powered Speech Analysis for Better Communication

SpeechCraft is an advanced real-time speech analytics platform that transforms spoken words into actionable insights. Using cutting-edge AI technology from AssemblyAI, it provides instant transcription while analyzing multiple dimensions of speech performance.

Read full post

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay