Skip to main content

Command Palette

Search for a command to run...

Input and Output in Python

Published
β€’2 min readβ€’View as Markdown
Input and Output in Python

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.

Python

Part 5 of 9

Unlock Pythons power in our captivating series. From basics to advanced techniques, unleash your coding potential in a few episodes. Join us now and embark on a journey of learning and exploration.

Up next

Conditional Statements.

What are the Conditional Statements? Conditional statements in Python allow you to control the flow of your program based on certain conditions. They enable you to execute different blocks of code based on whether a condition is true or false. The tw...

More from this blog

Aksh Darji

19 posts