Tom
Tom

Reputation: 13

inconsistent string to int error and response

I've made a simple program where the users adds as many numbers as they would like then type 'exit' to stop it and print the total but sometimes it says the converting the string to int fails, and sometimes it does convert but then it has the wrong out put e.g I type 1 + 1 but it prints 1

def addition():
    x = 0
    y = 1
    total = 0

    while x < y:
        total += int(input())

        if input() == "exit":
            x += 1

    print(total)

addition()

I have tryed converting it to a float then to an int but still has inconsistency, I did start learning python today and am finding the syntax hard coming from c++ / c# / Java so please go easy on the errors

Upvotes: 1

Views: 122

Answers (4)

Wondercricket
Wondercricket

Reputation: 7872

Maybe this is what you are looking for:

def addition():
    total = 0

    while True:
        value = input()

        if value == "exit":
            break
        else:
            try:
                total += int(value)
            except:
                print('Please enter in a valid integer')

    print(total)

EDIT


There are two reasons why the code isn't working properly:

First, the reason why it is failing is because you are trying to cast the word "exit" as an integer.

Second, as user2357112 pointed out, there are two input calls. The second input call was unintentionally skipping every other number being entered in. All you needed to do was one input call and set the entered value into a variable.

Upvotes: 2

Joran Beasley
Joran Beasley

Reputation: 113948

def safe_float(val):
    ''' always return a float '''
    try:
       return float(val)
    except ValueError:
       return 0.0

def getIntOrQuit():
    resp = input("Enter a number or (q)uit:")
    if resp == "Q":
       return None
    return safe_float(resp)


print( sum(iter(getIntOrQuit,None)) )

is another way to do what you want :P

Upvotes: 0

shaktimaan
shaktimaan

Reputation: 12092

These are a few ways you can improve your code:

  1. Run the loop forever and break out of it only if the user enters "exit"
  2. To know when the user entered "exit" check if the input has alphabets with isalpha()

Making the above changes:

def addition():
    total = 0
    while True:
        user_input = input()
        if user_input.strip().isalpha() and user_input.strip() == 'exit':
            break
        total += int(user_input)

    print(total)

addition()

Upvotes: 0

Weafs.py
Weafs.py

Reputation: 22992

You can break the while loop, without using x and y.

def addition():
    total = 0
    while True:
        total += int(input())
        if input() == "exit":
            break

    print(total)

addition()

Upvotes: 1

Related Questions