-1

I have to make a program using while that:

  1. Will ask for user to put 2 integer numbers and give back the addition and multiplication of those 2.

  2. Will check if the numbers are integers.

  3. Will close if the user uses the word stop.

I have made 1 and 2 but am stuck on 3. Here is what I wrote:

while True:
    try:
        x = int(input("Give an integer for  x"))
        c = int(input("Give an integer for  c"))
        if  x=="stop":
            break


    except:
        print(" Try again and use an integer please ")
        continue

    t = x + c
    f = x * c
    print("the result  is:", t, f)
AMC
  • 2,642
  • 7
  • 13
  • 35
marvin
  • 45
  • 1
  • 6
  • Your `if` will *always* be false (if `x` were `stop`, you'd get an exception when you try to convert it to an `int`). – Scott Hunter May 02 '20 at 21:43
  • _I have made 1 and 2 but am stuck on 3._ What is the issue with the program? Don't use a bare except like that, see https://stackoverflow.com/questions/54948548/what-is-wrong-with-using-a-bare-except. – AMC May 03 '20 at 00:40

2 Answers2

1

Your code isn't working because you are starting off by defining x as an integer, and for it to equal "stop", it needs to be a string.

What you therefore want to do is allow x to be input as a string, and then convert it to an integer if it isn't stop:

while True:
    try:
        x = input("Give an integer for  x")
        if  x=="stop":
            break
        else:
            x = int(x)
        c = int(input("Give an integer for  c"))



    except:
        print(" Try again and use an integer please ")
        continue

    t = x + c
    f = x * c
    print("the result  is:", t, f)
c_n_blue
  • 182
  • 2
  • 10
0

Just a slight change is required (and you can be slightly more structured using else in your try block.

You need to input the first value as a string so that you can first test it for "stop" and only then try to convert it to an integer:

while True:
    try:
        inp = input("Give an integer for x: ")
        if inp == "stop":
            break
        x = int(inp)
        c = int(input("Give an integer for  c: "))
    except:
        print("Try again and use an integer please!")
    else:
        t = x + c
        f = x * c
        print("the results are", t, f)

I have also fixed up some spacing issues (i.e. extra spaces and missing spaces in your strings).

Booboo
  • 38,656
  • 3
  • 37
  • 60
  • How does the `else` help? – Scott Hunter May 03 '20 at 00:15
  • @ScottHunter It's not a big deal but you no longer have to have a `continue` statement in the `except` block and it more clearly shows the alternate code to be executed when you don't get an exception. In the end. – Booboo May 03 '20 at 01:09