Home > OS >  User input numbers and assign them to different variables using loop in python
User input numbers and assign them to different variables using loop in python

Time:05-09

I tried my best to find it on different forums so excuse me if it is an easy one.

I want to take different inputs from the user and assign them to different variables. Using split() we can only enter the inputs in one line.

w,x,y,z = (input('Enter the number :').split(','))

But how can we ask for inputs in different line and assign them to the variables without typing the input function again.

I want the same output as below code but without typing input function multiple times.

w= int(input('Enter the number :'))
x= int(input('Enter the number :'))
y= int(input('Enter the number :'))
z= int(input('Enter the number :'))

CodePudding user response:

One solution can be input 4 numbers to array and then assign them to variables. For example:

numbers = [int(input("Enter the number : ")) for _ in range(4)]
w, x, y, z = numbers

print(f"{w=} {x=} {y=} {z=}")

Prints:

Enter the number : 2
Enter the number : 3
Enter the number : 4
Enter the number : 5
w=2 x=3 y=4 z=5

Or:

w, x, y, z = [int(input("Enter the number : ")) for _ in range(4)]
  • Related