Input and Output in Python

Input and Output in Python

·

2 min read

What is Input Function?

The input() function in Python is used to read input from the user. It prompts the user for input and waits for the user to enter a value. The entered value is then returned as a string.

Example:

name = input("Enter your name: ")
print("Hello, " + name)

The input() function in Python always returns a string data type by default. It reads the user input as a string, regardless of the actual input provided by the user.

Type casting

To convert the input from a string to a different data type, you can use type casting or conversion functions. Here are a few examples:

  1. Converting input to an integer:
age = input("Enter your age: ")
age = int(age)
print("After conversion:", age, type(age))
  1. Converting input to a floating-point number:
weight = input("Enter your weight in kilograms: ")
weight = float(weight)
print("After conversion:", weight, type(weight))
  1. Converting input to a boolean:
choice = input("Enter your choice (True/False): ")
choice = bool(choice)
print("After conversion:", choice, type(choice))

It's important to note that if the user provides input that cannot be converted to the desired data type, a ValueError will occur. To handle this, you can use exception-handling techniques like try-except blocks.

What is Print Function?

The print() function in Python is used to display output to the console or terminal. It can be used to print strings, variables, expressions, or a combination of them. The print() function automatically adds a new line character at the end by default, but this can be changed by using the end parameter.

Example:

name = "Aksh"
age = 21
print("Name:", name)
print("Age:", age, end=" ")
print("years old")

Output:

Name: Aksh
Age: 21 years old

The print() function is a versatile tool for displaying information and debugging during program execution.