Python(Page-3)

 12345678910

Page-3

Input and Output

To Make the Program interactive for the users, it is necessary to make it possible that a program takes User Input and works accordingly. 

For this purpose, we use the input() Function in Python. The Syntax for the input function is -

input([prompt])

Prompt is optional and is used to print a string before the user enters a value. 

Example-

input("enter a number")

In this example, the string "enter a number" is a prompt that is displayed before the user enters a number. 

if we don't use this prompt, the program will run flawlessly but the user will not see any message like this. 


We need to save the value entered by the user in a variable. So, we will write a variable on the left-hand side of the input() function. 

Example-

num1=input("enter a number")

Also, input() function considers all input from the user as a string, so, we should use be careful while using it. 

In the above example, the num1 variable will contain the string entered by the user. if the user enters number 2, it will be converted into a string and will be saved in variable num1. 

Further, we should explicitly convert the num1 into a number to do some calculations. 


type() Function

type() function returns the type of the value passed to it. 

Example-

print(type("hello"))

Output-

<class 'str'>

Example-

print(type(2.0))

Output-

<class 'float'>

Type Conversion

The Data Type of a value can be changed to another data type in two ways-
1)Explicit conversion- In Explicit Type conversion, the programmer forces the value to change its type. 
Example-

num=int(input("enter a number"))

In the above statement, when the user enters a number, it is a string by default as the input function takes only a string. but, the programmer forced it to change it to an integer by using the int() function. 
Similarly, float(x) function converts x in a float and str(x) converts the x into a string. 

2) Implicit Conversion-Implicit type conversion happens when python does it by itself. 

Example-

num1=10
num2=5.0
print(num1+num2)

Output- 15.0

Here, python makes the output as a float adding an integer and float value. 



 12345678910


No comments:

Post a Comment