Python Basics
- Introduction to Python
- Installing Python in Windows
- Python Values, Variables and Types
- Python Variable Names and Keywords
- Python Statements
- Python Operators and Expressions
- Take input from User in Python
- Python Comments
- Python Conditional Execution
- Python Functions
- Python Loops
- Python Strings
- Python Lists
- Python Dictionaries
Take input from User in Python
Sometimes you would like to take input for a particular variable from the user via keyboard. In python, input() function is a built-in function for taking input from user. When this function is called, the program stops and waits for receiving a input. When the user presses Return or Enter, the program resumes and input returns what the user typed as a string.
i = input()
print(i)
Output:
>>> input = input()
MakeMeAnalyst
>>> print(input)
MakeMeAnalyst
>>>
It is a better to print a prompt telling the user what is the input they should enter . You can pass a string to input to be displayed to the user before pausing for input:
>>> name = input('Enter your name?\n')
Enter your name?
Mr. X
>>> print(name)
Mr. X
>>>
The sequence \n at the end of the prompt represents a newline, which is a special character that causes a line break. That’s why the user’s input appears below the prompt.
Take an integer as an Input:
If you expect the user to type an integer, you can try to convert the return value to int using the int() function:
prompt = 'What is your age?\n'
i=input(prompt)
print(i)
print(type(i)) #It returns a string
i=int(i) #Convert it to integer.
print(i)
Output:
>>>
What is your age?
30
30
<class ‘str’>
30
>>>