0

The code doesn't stop even if 0 is fed as value. what could be the possible reason? see my code below:

x = -1
num = -9

print("For exit press 0")

while (x != 0):
    num = input("Enter a number  :")
    print("You entered: ", num)
    x = num
    if x == 0:
        break


print("Good bye!")

Thanks!

4
  • 2
    Please clarify what language you're using. Looks like Python. Commented Mar 29, 2017 at 5:49
  • For me this works (if this is Python code). My Python 2.7.6 (OSX). Commented Mar 29, 2017 at 5:52
  • it worked with me, I just copied the code and run it and it works as expected, I'm on python 2.7 Commented Mar 29, 2017 at 5:52
  • 1
    Python 2 and 3 probably treats string comparison differently. Commented Mar 29, 2017 at 5:54

1 Answer 1

2

The problem is that you're comparing string to integer; Python is weakly typed, so no warning is given.

Additionally, input() casts the input in Python 2, but not Python 3. This is why the code works as intended in Python 2.

Notes: You don't need parentheses for while condition. Formatting the string is recommended for outputting things.

x = -1

print("To exit press 0")

while x != 0:
    num = input("Enter a number:")
    print("You entered: {}".format(num))
    x = int(num)
    if x == 0:
        break

print("Good bye!")
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I figured out that the only line I had to modify based on the clue from above answer is as follows: x = int(num) I just added int() so that the numeric value goes into variable x, and it worked.

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.