Input output

Input output

In Python, input and output can be performed using the input() and print() functions, respectively.

The input() function allows you to get input from the user. It takes an optional string argument, which is used as a prompt to the user. For example:

pythonCopy codename = input("Enter your name: ")
print(f"Hello, {name}!")

In this example, the user is prompted to enter their name, and the input is stored in the name variable. The print() function is then used to output a greeting message.

The print() function is used to output text to the console. It takes one or more arguments, which are separated by commas, and prints them to the console. For example:

pythonCopy codex = 42
y = 3.14
z = "hello"
print(x, y, z)  # prints "42 3.14 hello"

In this example, the values of x, y, and z are printed to the console separated by spaces.

You can also format output using the print() function by using format strings or using the format() method. For example:

pythonCopy codename = "Alice"
age = 25
print(f"My name is {name} and I'm {age} years old.")
# or
print("My name is {} and I'm {} years old.".format(name, age))

In both cases, the output will be “My name is Alice and I’m 25 years old.”

In addition to the console, you can also write output to a file using the open() function and file object methods. For example:

pythonCopy codewith open("output.txt", "w") as f:
    print("Hello, world!", file=f)

In this example, the open() function is used to create a new file named “output.txt” in write mode, and the print() function is used to write the text “Hello, world!” to the file. The with statement ensures that the file is closed when we are done writing to it.

Apply for Python Certification!

https://www.vskills.in/certification/certified-python-developer

Back to Tutorials

Get industry recognized certification – Contact us

Menu