Quick Reach
The input method of Python
Taking user input from the keyboard is generally required in programming languages. For example, a calculator, currency converter etc. that asks users to enter some value from the keyboard or keypad. Python comes up with an input() method that allows programmers to take the user input.
Before 3.x version of Python, the raw_input() function was used to take the user input. The raw_input function of Python is removed in the latest version. From version 3.x, this is replaced with Python input() function. While simply using the raw_input() will generate an error.
Examples of Python input() method
Following are a few examples of using the input function.
Simple example of python user input
In the following example, the program asks the user name and age and then displays it by using the Python input method.
1
2
3
4
5
6
7
|
name = input(“Enter your name? “)
age = input(“Enter your age? “)
print (“Hello, %s.” % name)
print (“Your age is %s” % age)
|
Suppose if you entered name as [your name] and age = 35
It will display that information after taking input.
The output will be:
Hello, [your name].
Your age is 35
Input python with Leap year example
This example asks a user to enter a Year in four digits (2000, for example) and the program will display if the entered year is a leap year or not.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
leap_yr = input(“enter year: “)
leap_yr =int(leap_yr)
if not leap_yr%400:
print (leap_yr, ” is a leap year.”)
elif not leap_yr%100:
print (leap_yr, ” is a leap year.”)
elif not leap_yr%4:
print (leap_yr, ” is a leap year.”)
else:
print (leap_yr, ” is not leap year.”)
|
Also see: Python File Open
Leave A Comment?