Monday, June 26, 2023

Possibilities of printing output

Notice the difference in print command in the case (I) and (II). Both print the same message.

1. The string message and variable values are separated by commas.

qty = int(input("How many apples do you have? : "))

price = float(input("What is the total cost? : "))

value_of_one = price/qty

print(qty,' apples cost ',price,' therefore one apple costs

',value_of_one,'.')

Output:

How many apples do you have? : 50

What is the total cost? : 250

50 apples cost 250.0 therefore one apple costs 5.0 .

>>>

2. The values of variables are inserted inside the string using format() method.

int(input("How many apples do you have? : "))

price = float(input("What is the total cost? : "))

value_of_one = price/qty

print('{} apples cost {} therefore one apple costs

{}.'.format(qty,price,value_of_one))

The first value in the parenthesis, that is, qty is embedded in the first curly bracket. The second value price is embedded in the second curly bracket and the last value, value_of_one is inserted in the last curly bracket.

Output:

How many apples do you have? : 20

What is the total cost? : 800

20 apples cost 800.0 therefore one apple costs 40.0.

>>>

You can change the order in which the variables are inserted in the string by numbering the curly brackets.

3.

qty = int(input("How many apples do you have? : "))

price = float(input("What is the total cost? : "))

value_of_one = price/qty

print('{2} will be the cost of one apple if {0} apple cost

{1}.'.format(qty,price,value_of_one))

Output:

How many apples do you have? : 10

What is the total cost? : 500

50.0 will be the cost of one apple if 10 apple cost 500.0.

>>>

By default whitespace acts as a separator between the arguments to print() function in Python.

print('What would you like to have?')

print('Rice','lentils','veggies','?')

Output:

What would you like to have?

Rice lentils veggies?

If you want any other separator instead of whitespace, you can mention that in the print function using sep parameter as follows:

print('What would you like to have?')

print('Rice','lentils','veggies','?',sep='/')

Output:

What would you like to have?

Rice/lentils/veggies/?

Share:

0 comments:

Post a Comment