Tuesday, June 12, 2018

Input and Output Function in Python

Input() Function

Python has many built-in function in which one is input function.

Input function which lets you ask a user for enter some input.

The program will once resume once the user presses the ENTER Key.

Python 2.x using raw_input() .

Now Python 3.x use input().


name = input(“what is your name?”) # Out: What is your name? _

The function takes a string argument, which displays it as a prompt and returns a string. 

The above code provides a prompt, waiting for the user input.

If the user types “john” and hits enter, the variable name will be assign to the string “john” 

name = input("What is your name? ") # Out: What is your name? john

print(name) # Out: john

Note that the input is always of type str , which is important if you want the user to enter numbers. Therefore, you need to convert the str before trying to use it as a number:

x = input("Write a number:") # Out: Write a number: 10

x / 2 #ERROR!!! Out: TypeError: unsupported operand type(s) for /: 'str' and 'int' 

float(x) / 2 # Out: 5.0

print() Function

To Output data to the standard output device we use print function.

Example: print(‘Hello World!’) # Output: Hello World!

Using variables in print function

a = ‘Hello World!’

print(a)# Output: Hello World!

print(“The first program on any language is”, a) # The first program on any language is Hello World! 

X = 10

Y = 20

print(“value of x is {} and y is {}”, format(X,Y)) # Output: value of x is 10 and y is 20”.

Formatting using indexing

print(“value of x is {0} and y is {1}”, format(10,20)) # Output: value of x is 10 and y is 20”. 

print(“value of x is {1} and y is {0}”, format(10,20)) # Output: value of x is 20 and y is 10”. 

Keyword arguments print('Hello {name}, {message}'.format(message = 'Good morning', name = 'John'))

#Output: Hello John, Good morning 

Prev: Type Conversion In Python

Next: Operators in Python

No comments:

Post a Comment

Google+ Followers