A7. Python I/O operations and import


In this tutorial we are going to learn simple ways to display output, and take input from users in python with examples.


Python Output

In Python, output refers to the information or data that a program displays to the user, either in the console or in a graphical user interface.

Output can be in the form of text, numbers, or other data types, and can be displayed using built-in Python functions or through external libraries.

The most common way to display output in Python is by using the print() function. This function takes one or more arguments and displays them on the console, separated by spaces. For example:

print("Hello world!")  # Output: Hello world!

In addition to text, the print() function can also display variables, numbers, and other data types. For example:

name = "John"
age = 27
print("My name is", name, "and I am", age, "years old.")  # Output: My name is John and I am 27 years old.

Python also provides other ways to display output, such as using the format() method or f-strings. These methods allow for more complex formatting of output and can make it easier to display variables and other data types. Here is an example using the format() method:

name = "John"
age = 27
print("My name is {} and I am {} years old.".format(name, age))  # Output: My name is John and I am 27 years old.

Overall, Python provides a variety of ways to display output to users, depending on the complexity and formatting needs of the program.

Syntax for Python Output

As we discussed the print() is used to display in python, now lets try and explore the syntax of print(). print() can take one or more arguments and display’s them on the console, separated by spaces. The basic syntax of the print() function is:

print(object(s), sep=separator, end=end, file=file, flush=flush)

Here is a brief explanation of each of the parameters:

  • object(s): A object or objects you want to display. You can pass one or more objects separated by commas.

  • sep: Stands for Separator between the objects you want to display. The default value is a space character.

  • end: This is the character or string that will be printed at the end. The default value is a newline character (\n), which means that each call to print() will end with a new line.

  • file: File object where you want to write the output. The default value is sys.stdout, which means that the output will be printed on the console. You can pass a different file object if you want to write the output to a file.

  • flush: If this parameter is set to True, the output buffer will be flushed. The default value is False.

Here are a few examples of using the print() function:

print("Hello, World!")  # Output: Hello, World! #1 
print("Hello", "World", sep="-")  # Output: Hello-World #2
print("Hello", end=" ")  # Output: Hello (without newline) #3
print("World")  # Output: World (on the same line) #4

In this example, we passed a single object to print(), which was a string for #1.

In the second example, we passed two objects separated by a hyphen as the separator.

In the third example, we used the end parameter to prevent the print() function from adding a newline character at the end.

Finally, in the fourth example, we printed the second part of the message on the same line as the first part by not using the end parameter.


Example for print() in python

Example 1 : Python Print Statement

print('Good Morning!')
print('Elon Musk')

OutPut :

Good Morning!
Elon Musk

In the given print() example, the statement only includes the object (the string) to be printed. It does not specify an end value. Therefore, the default end value of ‘\n’ (a newline) is used.

This results in the two printed strings being output on separate lines.

To print the strings on the same line, we can specify an end value of an empty string (end=’’) in the print() statement. This will prevent the newline from being added at the end of the first string, and the next string will be printed immediately after.

Example 2 : Python print() with end Parameter

The end parameter in the print() function in Python allows you to specify what character or string should be printed at the end of the output instead of the default newline character (\n).

Here is the basic syntax of the print() function with the end parameter:

print(object(s), sep=separator, end=end_character)

The end_character parameter specifies what should be printed at the end of the output instead of the default newline character. It can be any character or string.

Here are some examples of using the end parameter:

print("Hello", end=" ")
print("world!")  # Output: Hello world!

In this example, we used the end parameter to specify that a space character should be printed at the end of the first print() statement instead of a newline character. This allowed us to print the second print() statement on the same line as the first one.

for i in range(5):
    print(i, end="-")

In this example, we used the end parameter to specify that a hyphen character should be printed at the end of each iteration of the for loop. This allowed us to print the numbers on the same line separated by hyphens.

The end parameter can be useful when you want to control the formatting of the output in your program. You can use it to print output on the same line or to add any other character or string at the end of the output.

Example 3 : Python print() with sep parameter

The sep parameter in the print() function in Python allows you to specify what character or string should be used to separate the objects that you want to print. By default, print() separates objects with a space character.

Here is the basic syntax of the print() function with the sep parameter:

print(object(s), sep=separator, end=end_character)

The separator parameter specifies what should be used to separate the objects that you want to print. It can be any character or string.

Here are some examples of using the sep parameter:

print("apple", "banana", "orange")  # Output: apple banana orange

In this example, we printed three objects separated by the default space character.

print("apple", "banana", "orange", sep=", ")  # Output: apple, banana, orange

In this example, we used the sep parameter to specify that a comma followed by a space character should be used to separate the objects instead of the default space character.

print(1, 2, 3, 4, 5, sep="-")  # Output: 1-2-3-4-5

In this example, we used the sep parameter to specify that a hyphen character should be used to separate the objects.

The sep parameter can be useful when you want to control the formatting of the output in your program. You can use it to separate objects with any character or string that you want, such as a comma, a hyphen, a semicolon, or any other character or string.

Example 4 : Print Python Variables and Literals

Here are some examples of printing variables and literals using the print() function:

# Printing a string literal
print("Hello, World!")  # Output: Hello, World!

# Printing an integer variable
age = 27
print(age)  # Output: 27

# Printing a floating-point variable
pi = 3.14159
print(pi)  # Output: 3.14159

# Printing multiple variables and literals
name = "John"
score = 85
print("Name:", name, "Score:", score)  # Output: Name: John Score: 85

In the first example, we printed a string literal directly by passing it as an argument to the print() function.

In the second and third examples, we print integer and floating-point variables respectively by passing them as arguments to the print() function.

In the fourth example, we print multiple variables and literals by passing them as arguments to the print() function, separated by commas. The print() function automatically adds a space character between each argument.

Example 5 : Output formatting in Python

You can also use the format() method or f-strings to format the output of variables and literals. Here is an example using the format() method:

name = "John"
age = 27
print("My name is {} and I am {} years old.".format(name, age))  # Output: My name is John and I am 27 years old.

In this example, we used the format() method to format the output of the variables name and age inside a string literal. The curly braces {} are placeholders for the values of the variables, which are passed as arguments to the format() method.

Overall, the print() function is a versatile tool for printing variables and literals in Python, and can be combined with other functions and methods to format the output as needed.

Example 6 : Python Concatenation of strings

In Python, you can concatenate strings using the + operator or by using string formatting methods such as the format() method or f-strings. Once you have concatenated the strings, you can print them using the print() function.

Here are some examples of concatenating and printing strings in Python:

# Concatenating strings using the + operator
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)  # Output: John Doe

# Using the format() method
age = 27
print("My name is {} and I am {} years old.".format(full_name, age))  # Output: My name is John Doe and I am 27 years old.

# Using f-strings
score = 85
print(f"{full_name} scored {score} points.")  # Output: John Doe scored 85 points.

In the first example, we concatenated the strings first_name, a space character, and last_name using the + operator to create a new string full_name. We then printed the value of full_name using the print() function.

In the second example, we used the format() method to format a string literal that includes the values of the variables full_name and age. The curly braces {} are placeholders for the values of the variables, which are passed as arguments to the format() method.

In the third example, we used an f-string to format a string literal that includes the values of the variables full_name and score. An f-string is a string literal that is prefixed with the letter “f” and includes expressions inside curly braces {} that are evaluated at runtime.

Python Input

The input() function is used to take input from the user through the console. It displays a prompt to the user and waits for the user to enter some text followed by the Enter key. The text entered by the user is then returned as a string.

Here is an example of using the input() function:

name = input("What's your name? ")
print("Hello, " + name + "!")

In this example, we used the input() function to prompt the user to enter their name. The text “What’s your name?” is displayed to the user as the prompt. When the user enters their name and presses Enter, the text entered by the user is returned as a string and assigned to the variable name. We then used the print() function to display a greeting message that includes the value of the name variable.

You can use the input() function to take input from the user for any purpose, such as asking for a number or a password. However, keep in mind that the input() function always returns a string, so you may need to convert the input to a different data type if you want to perform arithmetic or other operations.

Below example of using the input() function to take input and convert it to an integer:

age = input("How old are you? ")
age = int(age)
print("You were born in " + str(2023 - age) + "!")

In above example, we used the input() function to prompt the user to enter their age.

The text entered by the user is returned as a string and assigned to the age variable. We then use the int() function to convert the string to an integer so that we can perform arithmetic operations on it, Checkout type Conversion on how to convert data types in python.

We then subtract the age from the current year (2023) to calculate the year the user was born, and then used the str() function to convert the result to a string so that we can concatenate it with other strings in the print() function.