Python Taking Multiple Inputs
One way to take multiple inputs from users in Python is to use the split() method which breaks the given input by a specified separator (such as space, comma, etc.) and returns a list of strings. For example:
# Taking multiple inputs separated by space
a, b, c = input("Enter three numbers: ").split()
# a, b and c are strings
# Taking multiple inputs separated by comma
x, y, z = input("Enter three words: ").split(",")
# x, y and z are strings
Another way to take multiple inputs from users in Python is to use list comprehension which creates a list of values based on an expression. For example:
# Taking multiple integer inputs separated by space
a = [int(x) for x in input("Enter four numbers: ").split()]
# a is a list of integers
# Taking multiple string inputs separated by comma
b = [str(y) for y in input("Enter four words: ").split(",")]
# b is a list of strings
Python provides a simpler way to take multiple inputs using one line of code. You can also define multiple variables in one line.
x, y = input().split()# Interger Inputs
x, y = map(int, input().split())# Space Seperated Inputs
data = list(map(int, input().split()))
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment