7.Output and Input functions- print() and input()
Python Output Using print() function
>>>x = 5
The actual syntax of the print() function is:
>>>print(1, 2, 3, 4, sep='*')
Output formatting
We can even use keyword arguments to format the string.
>>>print('test{:5d}'.format(123)) # number takes 5 spaces equivalent to %5d in C , uses 5 field width
#Python3 program introducing f-string
name = 'Binu'
age = 50
print(f"Hello, My name is {name} age is {age}")
# Taking a simple string input
name = input("Enter your name: ")
print("Hello, " + name + "!")
# Taking an integer input
age = int(input("Enter your age: "))
print("You are " + str(age) + " years old.")
# Taking a floating-point input
price = float(input("Enter the price: "))
print("The price is " + str(price))
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 5The 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, 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).
flush: Whether to forcibly flush the stream.
1*2*3*4
1#2#3#4&>>>print(1, 2, 3, 4, sep='#', end='&')
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 breadWe 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
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
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, 2023Note : F-strings are faster than the two most commonly used string formatting mechanisms, which are % formatting and str.format().
Python input() function for reading data
To allow flexibility, we might want to take the input from the user. In Python, we have the input() function to allow this. The input() function is used to take input from the user. By default, it reads the input as a string.
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
name = input("Enter your name: ")
print("Hello, " + name + "!")
# Taking an integer input
age = int(input("Enter your age: "))
print("You are " + str(age) + " years old.")
# Taking a floating-point input
price = float(input("Enter the price: "))
print("The price is " + str(price))
Summary
Input: Use input() to get user input. Convert it to the required type using functions like int() and float().
Output: Use print() to display output. Customize the output using parameters like sep and end.
String Formatting: Use f-strings, format() method, or % operator for formatted output.
Understanding these input and output mechanisms is essential for interacting with users and handling data efficiently in Python programs.
Example program: Finding the sum of two integers
# Read the first number from the user
num1 = int(input("Enter the first number: "))
# Read the second number from the user
num2 = int(input("Enter the second number: "))
# Add the two numbers
result = num1 + num2
# Print the result
print(f"The sum of {num1} and {num2} is {result}")
Comments
Post a Comment