warrawind
warrawind

Reputation: 25

If condition with boolean function call is always True in Python

I have written a program and at the end I have written a code for the user to rate my program, but it has some issues please help:

while True:
    RR = input("What would you rate this program(?/5): ")
    if RR.isnumeric:
        rating = int(RR)
        if rating >= 5:
            print("Looks like you are highly satisfied with this program :D")
            break
        elif rating == 4 or rating == 3:
            print("Ohh! Next time I'll try my best to change this '",rating,"' into 5 ;D")
            break
        elif rating == 1 or rating == 2:
            print("I am sorry if I wasn't good, I'll try my best next time :|")
            break
    else:
        print("Invalid Rating, Try again...")
        continue

Result

What would you rate this program(?/5): g
ValueError: invalid literal for int() with base 10: 'g'

What I want is that if someone enters a text instead of a number then it tells that it's an invalid input and continues the loop. How can I get this?

Upvotes: 1

Views: 687

Answers (2)

jaaq
jaaq

Reputation: 1256

Your code has two problems.

  1. Your if condition checks str(RR).isnumeric which is always True, since that function exists for all string objects. Change it to RR.isnumeric().

  2. In your inner if you might want to put in an else:contine to not bypass the voting system, when a value smaller than 1 is entered.

Here's code that should do what you want:

while True:
    RR = input("What would you rate this program(?/5): ")
    if RR.isnumeric():
        rating = int(RR)
        if rating >= 5:
            print("Looks like you are highly satisfied with this program :D")
            break
        elif rating in [3, 4]:
            print("Ohh! Next time I'll try my best to change this '",rating,"' into 5 ;D")
            break
        elif rating in [1, 2]:
            print("I am sorry if I wasn't good, I'll try my best next time :|")
            break
        else:
            print("Invalid Rating, Try again...\nPlease enter a value from 1 to 5")
    else:
        print("Invalid Rating, Try again...\nPlease enter a value from 1 to 5")

You should tell the user what they should do imo, and you don't need a continue in a while True if you don't need to skip any code anyway. Also a list comparison to check if your rating is within a set of numbers is nicer to read. Another very enjoyable way to compare ranges in Python is like this:

if 0 < x < 7:
    pass
elif 6 < x < 10:
    pass

But for small ranges like in your case, I prefer using lists.

HTH

Upvotes: 1

Jonti
Jonti

Reputation: 55

Your if condition is not a function call, but rather a reference to the function. It is not yet called.

It should be if RR.isnumeric() not if RR.isnumeric.

Upvotes: 1

Related Questions