0

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.

3
  • Your tuple holds String values, not int. Commented Jul 21, 2020 at 16:59
  • 2
    What have you tried, what results do you get, what results do you expect? Commented Jul 21, 2020 at 16:59
  • you can sum your values like you want after converting them to either integers or floats, a pythonic way of this would be sum(int(num) for num in input('Enter Values: ').split()) Commented Jul 21, 2020 at 17:03

5 Answers 5

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

(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!

Comments

0
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

Comments

0

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!

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.