Take input from user in Python
In this tutorial, you will learn how to take input from a user in Python.
A simple program to ask for the name in Python
yourName = input("enter the name: ") print("hello",yourName)
output:
enter the name: user hello user
I have taken a variable yourName
to store the string entered by the user.
It’s a good practice to wrap your input()
method with str
, if you are taking string input. str(input(“enter the name: “))
But you might wonder what will be the data type of your input. It will always be str means string. It does not matter if your input is a number or a string. It will be always a str type.
yourName = input("enter the name: ") print(type(yourName))
Output:
enter the name: 7 <class 'str'>
Take integer / number input only in Python
If you want to take only integer input through input()
method you can follow this:
myValue = int(input("enter the name: ")) print(myValue) print(type(myValue))
Output:
enter the name: hi ValueError: invalid literal for int() with base 10: 'hi'
As it will allow only integer-type input.
Take floating point input from the user
myValue = float(input("enter the name: ")) print(myValue) print(type(myValue))
Output:
enter the name: 7 7.0 <class 'float'>
Ask the user to enter a name in Python using a function
Let’s create our simple custom Python function and then call it:
def hello(): name=str(input("enter the name : ")) print("hello " + str(name)) return hello()
Run this code online
And the output will be like you can see below:
enter the name : user hello user
conclusion
I hope that I have demonstrated the program using function and in a simple way for your understanding.
Also read:
Easy to understand
you are doing great,make most of it da
didn’t work i done this before i done this in php and shell not with this exact line of code but similar, mostly.
Thanks so much your website has helped my research a lot
Write a function hello(lastname, firstname ), in the sense if called with hello(‘Adam’,
‘Cloud’), will print two lines:
Hey Cloud Adam
Hey Adam Cloud
fname=str(input(“enter first name: “))
lname=str(input(“enter lastname: “))
print(“Hey”, fname, “”, lname,)
print(“Hey”, lname, “”, fname,)