PYTHON(DAY4)
Input and Output in python
INPUT FUNCTION
Input function is used to take input from the user (or) to provide input to the program.
How to Take Input from User in Python
Sometimes a developer wants to take input from the user at some point in the program. To do this Python provides an input() function.
Syntax:
input('xyz')
where xyz is an optional string that is displayed on the string at the time of taking input.
Example 1: Getting input from user
x = input('Enter your Name:')
print(x)
here, we get the output as:
Enter your Name: xyz
type() function:
To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.
Example 2: using type function
y = 'hi'
print(type(y))
here, we get the output as:
<class ‘str’>
Python takes all the input as a string input by default. To convert it to any other data type we have to convert the input explicitly. For example, to convert the input to int or float we have to use the int() and float() method respectively.
How to take integer as an input
we need to use int(input()) to convert the input from string to integer
Example 3: using int() function
x = int(input('enter a number:'))
print(x)
here, we get the output as:
enter a number: 10
How to take Multiple Inputs from user
Sometimes, the developers also need to take the multiple inputs in a single line.However, Python provides the method that help us to take multiple values or input in one line.
- Using split() method
Syntax:
input().split(separator, maxsplit)
Parameters
The separator parameter breaks the input by the specified separator. By default, whitespace is the specified separator.
The split() method is used to split the Python string, but we can use it to get the multiple values too.
a,b,c = input('enter three values:')
print('enter first name:',a)
print('enter last name:',b)
print('enter school name:',c)
here, we get output as:
enter three values: raj kumar nirmal
enter first name: raj
enter last name: kumar
enter school name: nirmal
OUTPUT FUNCTION
In python, we just simply use the print() function to print out
Example:
print('hi')
print('hello')
here, we get output as:
hi
hello
what if we use “end” parameter in print statement, let see the difference between the above print statement and this statement
By default end takes space to print the outputs in single statement seperated by space
print('hello', end = ' ')
print('world)
here, we get output as:
hello world