04python 04 Getting Inputs From The User in Python
04python 04 Getting Inputs From The User in Python
• Using the input() function, users can give any information to the
application in the strings or numbers format.
In Python 3, we have the input() built-in functions to handle input from
a user.
• input(prompt): To accept input from a user.
The prompt argument is optional. The prompt argument is used
to display a message to the user. For example, the prompt is,
“Please enter your name.”
When the input() function executes, the program waits until a
user enters some value.
Next, the user enters some value on the screen using a keyboard.
Finally, The input() function reads a value from the screen,
converts it into a string, and returns it to the calling program.
Python Example to Accept Input From a User
Let see how to accept employee information from a user.
1. First, ask employee name, salary, and company name from the user
2. Next, we will assign the input provided by the user to the variables
3. Finally, we will use the print() function to display those variables on
the screen.
Program 2: Taking two values as input and
Outputting their Sum
a=input("Enter no1")
b=input("Enter no 2")
sum=a+b
print(sum)
print(type(a))
print(type(b))
As you know whatever you enter as input, the input() function always
converts it into a string.
Take an Integer Number as input from User
• We need to convert an input string value into an integer using an int()
function.
TypeCasting
• The process of converting the value of one data type (integer, string,
float, etc.) to another data type is called Type-Conversion or
TypeCasting.
• For example:
age=21.6
age_without_months= int(age)
print(float(age_without_months))
Types of TypeCasting
• Implicit Type Conversion:
In Implicit type conversion, Python automatically converts one data type
to another data type. This process doesn't need any user involvement.
a=1
b=10.3
a+b // output will be 11.3 (float value) as Python promotes the
conversion of the lower data type (integer) to the higher data type
(float) to avoid data loss.
Types of TypeCasting
• Explicit Type Conversion
In Explicit Type Conversion, users convert the data type of an object to
required data type.
The predefined functions like int(), float(), str(), etc. are used to perform
explicit type conversion.
a=10
b=“11”
a+b // output?
a+int(b)
Practice Programs
• Python Program to Swap Two Variables
• What will be the output of following python code:
a=3
b=1
print(a, b)
a, b = b, a
print(a, b)