7. Python Basic Input and Output

Take Input From User:

input() allows flexibility to take input from the user. Reads a
line of input as a string.

username = input() #Take input from user

But you taken input Data type so Syntax is

Take input = Data type(input())
#like
Age = int(input())

Printing the Output: print() function prints the message to the screen or any other standard output device.

print(username) # Ajay

Syntax of print()

In the above code, the print() function is taking a single parameter. However, the actual syntax of the print function accepts 5 parameters

print(object= separator= end= file= flush=)

Here,

  • object – value(s) to be printed
  • sep (optional) – allows us to separate multiple objects inside print().
  • end (optional) – allows us to add add specific values like new line "\n", tab "\t"
  • file (optional) – where the values are printed. It’s default value is sys.stdout (screen)
  • flush (optional) – boolean specifying if the output is flushed or buffered. Default: False

Example 1: Python Print Statement with Object

print('Good Morning!')
print('It is rainy today')
#Output
Good Morning!
It is rainy today

Example 2: Python print() with end Parameter

# print with end whitespace
print('Good Morning!', end= ' ')

print('It is rainy today')
#Output
Good Morning! It is rainy today

Notice that we have included the end= ' ' after the end of the first print() statement. Hence, we get the output in a single line separated by space.

Example 3: Python print() with sep parameter

print('New Year', 2023, 'See you soon!', sep= '. ')

Output

New Year. 2023. See you soon!

In the above example, the print() statement includes multiple items separated by a comma. Notice that we have used the optional parameter sep= ". " inside the print() statement. Hence, the output includes items separated by . not comma.

Example: Print Concatenated Strings:

We can also join two strings together inside the print() statement. For example,

print('Programiz is ' + 'awesome.')

output

Programiz is awesome.

Here,

  • the + operator joins two strings 'Programiz is ' and 'awesome.'
  • the print() function prints the joined string

Leave a comment

Blog at WordPress.com.

Design a site like this with WordPress.com
Get started