7.Output and Input functions- print() and input()

Python Output Using print() function

We use the print() function to output data to the standard output device (screen)
An example of its use is given below.
>>>print('This is a sample output')
This is a sample output
Another example is given below:
>>>x = 5 
>>>print('The value of x is', x)
The value of a is 5

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).

>>>print(1, 2, 3, 4, sep='*') 
1*2*3*4
>>>print(1, 2, 3, 4, sep='#', end='&')
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 they are printed by using numbers (tuple index).
>>>print('I love {0} and {1}'.format('bread','butter'))
I love bread and butter
>>>print('I love {1} and {0}'.format('bread','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 also 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 %6.2f' %x)  # rounded to two decimal values
The value of x is 12.35 
>>> print('The value of x is %13.4f' %x)  # rounded to four decimal value
The value of x is       12.3457
>>>print('test{:5d}'.format(123)) # number takes 5 spaces equivalent to %5d in C , uses 5 field width 
test  123
>>> print("%6s"%"binu")
  binu
>>> print("%-6s"%"binu") # print the string left justified
binu  

Escape sequences
Escape sequences are the way Python express special characters in strings such as newline, tab and backspace etc.The back slash(\) is used for escape sequences, it must be escaped to appear as literal character in string. Thus print('\\') will print a single \ character. The following are some of the commonly used escape sequence in Python 3.
Escape Sequence   Meaning
\b                            Backspace
\n                            Newline
\t                             Horizontal tab
\\                            The \ character
\'                             Single quotation mark
\"                            Double quotation mark
\ooo                       Character with octal value ooo
\xhh                       Character with hex value hh

f-strings in Python

PEP 498 introduced a new string formatting mechanism known as Literal String Interpolation or more commonly as F-strings (because of the leading f character preceding the string literal). The idea behind f-strings is to make string interpolation simpler.
To create an f-string, prefix the string with the letter “ f ”. The string itself can be formatted in much the same way that you would with str.format(). F-strings provide a concise and convenient way to embed python expressions inside string literals for formatting.
example

#Python3 program introducing f-string
name = 'Binu'
age = 50
print(f"Hello, My name is {name} age is {age}")

Output:
Hello, My name is Binu age is 50

Example
import datetime
today = datetime.datetime.today()
print(f"{today:%B %d, %Y}")
Output
June 26, 2023
Note : F-strings are faster than the two most commonly used string formatting mechanisms, which are % formatting and str.format(). 

Python Input

Up until now, our programs were static. The value of variables was 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'
>>>type(num)
<class 'str'>

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
This same operation can be performed using the eval() function. But eval takes it further. It can evaluate even expressions, provided the input is a string
>>> int('2+3') 
Traceback (most recent call last): File "<string>", line 301, in runcode File "<interactive input>", line 1, in <module> ValueError: invalid literal for int() with base 10: '2+3'
 >>> eval('2+3') 
5

Comments

Popular posts from this blog

Python For Machine Learning - CST 283 - KTU Minor Notes- Dr Binu V P

46.Classes and Objects in Python- Accessors and mutators

KTU Python for machine learning Sample Question Paper and Answer Key Dec 2020