Reputation: 15
I want to add up the numbers in the row (w, x, y, z are all a part of a row) that the user gives me. I tried doing this:
(w, x, y, z) = input("Enter values: ").split()
row = w + x + y + z
print(row)
but it does not work.
Upvotes: 0
Views: 63
Reputation: 858
input returns strings not integer or float value. You need to convert the strings you get to integers.
w, x, y, z = input('Enter values: ').split()
row = int(w) + int(x) + int(y) + int(z)
or you can loop through the digits:
numbers = input('Enter values: ').split()
for integer in numbers:
total += integer
Keep in mind that with this code if the user enters anything other than 4 digits the code will not work. You can fix that by implementing try and except blocks or checks when receiving the input like so:
run = True
While run:
try:
w, x, y, z = input('Enter values: ').split()
row = int(w) + int(x) + int(y) + int(z)
run = False
except Exception as e:
print(e)
print("Please enter 4 digits seperated by a single space")
This will make the code loop until the user follows the instructions.
Upvotes: 0
Reputation: 1
Hey try this out!
row = input("Enter Values: ")
row = row.split()
n = 0
for num in row:
n += int(num)
print(n)
This way you can have as much as values as you want!
Upvotes: 0
Reputation: 342
w, x ,y ,z = input("Enter values: ").split()
print(w + x + y + z)
Make sure you insert exactly 4 values or else you will get an error
Upvotes: 0
Reputation: 23
(w, x, y, z) = input("Enter values: ").split()
row = int(w) + int(x) + int(y) + int(z)
print(row)
This code should do the job. You must remember that the input function returns a string which needs to be converted into integer using the int() function.
In your code, it gets concatenated since the numbers are considered as strings.
Cheers!
Upvotes: 0
Reputation:
the values you tried adding, are string, so you need to map them into integers, and unpack them as such.
w, x, y, z = list(map(int, input("Enter values: ").split()))
row = w + x + y + z
print(row)
Upvotes: 1