-
Notifications
You must be signed in to change notification settings - Fork 0
Python Input
Many a time, in a program we need some input from the user. Taking inputs from the user makes the program feel interactive. In Python 3, to take input from the user we have a function input()
. Let's see some examples:
- When we just want to take the input:
# This will just give a prompt without any message
inp = input()
Run Code 🚀
- To give a prompt with a message:
prompt_with_message = input('<Your prompt message should appear here>')
# <Your prompt message should appear here> _
# The '_' in the output is the prompt
Run Code 🚀
- When we want to take an integer input:
number = int(input('Please enter a number: '))
Run Code 🚀
If you enter a non integer value then Python will throw an error ValueError
. So whenever you use this, please make sure that you catch it too. Otherwise, your program will stop unexpectedly after the prompt.
number = int(input('Please enter a number: '))
# Please enter a number: as
# Enter a string and it will throw this error
# ValueError: invalid literal for int() with base 10 'as'
- When we want a string input:
string = str(input('Please enter a string: '))
Run Code 🚀
Though, inputs are stored by default as a string. Using the str()
function makes it clear to the code-reader that the input is going to be a 'string'. It is a good practice to mention what type of input will be taken beforehand.
Learn to code and help nonprofits. Join our open source community in 15 seconds at http://freecodecamp.com
Follow our Medium blog
Follow Quincy on Quora
Follow us on Twitter
Like us on Facebook
And be sure to click the "Star" button in the upper right of this page.
New to Free Code Camp?
JS Concepts
JS Language Reference
- arguments
- Array.prototype.filter
- Array.prototype.indexOf
- Array.prototype.map
- Array.prototype.pop
- Array.prototype.push
- Array.prototype.shift
- Array.prototype.slice
- Array.prototype.some
- Array.prototype.toString
- Boolean
- for loop
- for..in loop
- for..of loop
- String.prototype.split
- String.prototype.toLowerCase
- String.prototype.toUpperCase
- undefined
Other Links