Skip to main content

Python Input and Output | Usage of input and output

 Python Output Using print() function


We use the print() function to output data to the standard output device (screen).

print('This sentence is output to the screen')

# Output: This sentence is output to the screen


a = 5


print('The value of a is', a)

# Output: The value of a is 5

output

This sentence is output to the screen

The value of a is 5

In the second print() statement, we can notice that a space was added between the string and the value of variable a.This is by default, but we can change it. The actual syntax of the print() function is

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Here, objects is the value(s) to be printed. The sep separator is used between the values. It defaults into a space character. After all values are printed, end is printed. It defaults into a new line. The file is the object where the values are printed and its default value is sys.stdout (screen). Here are an example to illustrate this.



print(1,2,3,4)

# Output: 1 2 3 4


print(1,2,3,4,sep='*')

# Output: 1*2*3*4


print(1,2,3,4,sep='#',end='&')

# Output: 1#2#3#4&

output

1 2 3 4

1*2*3*4

1#2#3#4&

Output formatting

Sometimes we would like to format our output to make it look attractive. This can be done by using the str.format() method. This method is visible to any string object.

>>> x = 5; y = 10

>>> print('The value of x is {} and y is {}'.format(x,y))

The value of x is 5 and y is 10

Here the curly braces {} are used as placeholders. We can specify the order in which it is printed by using numbers (tuple index).

print('I love {0} and {1}'.format('bread','butter'))

# Output: I love bread and butter


print('I love {1} and {0}'.format('bread','butter'))

# Output: I love butter and bread

output

I love bread and butter

I love butter and bread

We can even use keyword arguments to format the string.

>>> print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name = 'John'))

Hello John, Goodmorning



We can even format strings like the old sprintf() style used in C programming language. We use the % operator to accomplish this.


>>> x = 12.3456789 >>> print('The value of x is %3.2f' %x) The value of x is 12.35 >>> print('The value of x is %3.4f' %x) The value of x is 12.3457



Python Input

Up till now, our programs were static. The value of variables were defined or hard coded into the source code. To allow flexibility we might want to take the input from the user. In Python, we have the input() function to allow this. The syntax for input() is

input([prompt])



where prompt is the string we wish to display on the screen. It is optional.

>>> num = input('Enter a number: ')
Enter a number: 10
>>> num
'10'

Here, we can see that the entered value 10 is a string, not a number. To convert this into a number we can use int() or float() functions.

>>> int('10')
10
>>> float('10')
10.0

Ref: Learn python:Python tutorial app

App by Avrram piperidas

Most Popular Course:Data Science of Harvard, MIT, IBM.... 

John Academy: 97% Off on Popular Online Courses



Amazon Best Seller in Baby Products

This same operation can be performed using the eval() function. But it takes it further. It can evaluate even expressions, provided the input is a string

>>> int('2+3')
Traceback (most recent call last):
  File "", line 301, in runcode
  File "", line 1, in 
ValueError: invalid literal for int() with base 10: '2+3'
>>> eval('2+3')
5

Python Import

When our program grows bigger, it is a good idea to break it into different modules. A module is a file containing Python definitions and statements. Python modules have a filename and end with the extension .py. Definitions inside a module can be imported to another module or the interactive interpreter in Python. We use the import keyword to do this. For example, we can import the math module by typing in import math.

import math
print(math.pi)

output

3.141592653589793

Now all the definitions inside math module are available in our scope. We can also import some specific attributes and functions only, using the from keyword. For example:

>>> from math import pi
>>> pi
3.141592653589793

While importing a module, Python looks at several places defined in sys.path. It is a list of directory locations.

>>> import sys
>>> sys.path
['', 
 'C:\\Python33\\Lib\\idlelib', 
 'C:\\Windows\\system32\\python33.zip', 
 'C:\\Python33\\DLLs', 
 'C:\\Python33\\lib', 
 'C:\\Python33', 
 'C:\\Python33\\lib\\site-packages']

We can add our own location to this list as well.

Comments

Popular posts from this blog

Python Package

  Python Package We don't usually store all of our files in our computer in the same location. We use a well-organized hierarchy of directories for easier access. Similar files are kept in the same directory, for example, we may keep all the songs in the "music" directory. Analogous to this, Python has packages for directories and modules for files. As our application program grows larger in size with a lot of modules, we place similar modules in one package and different modules in different packages. This makes a project (program) easy to manage and conceptually clear. Similar, as a directory can contain sub-directories and files, a Python package can have sub-packages and modules. A directory must contain a file named __init__.py in order for Python to consider it as a package. This file can be left empty but we generally place the initialization code for that package in this file. Importing module from a package We can import modules from packages using the dot (....

Python Exception Handling | Learn python

  Python Exception Handling - Try, Except and Finally Python has many built-in exceptions which forces your program to output an error when something in it goes wrong. When these exceptions occur, it causes the current process to stop and passes it to the calling process until it is handled. If not handled, our program will crash. For example, if function A calls function B which in turn calls function C and an exception occurs in function C. If it is not handled in C, the exception passes to B and then to A. If never handled, an error message is spit out and our program come to a sudden, unexpected halt. Catching Exceptions in Python In Python, exceptions can be handled using a try statement. A critical operation which can raise exception is placed inside the try clause and the code that handles exception is written in except clause. It is up to us, what operations we perform once we have caught the exception. Here is a simple example. # import module sys to get the type of except...