Learning Python: If condition executing all the time

后端 未结 5 1507
情深已故
情深已故 2021-01-21 05:33

I am learning python and i can\'t figure out why the following program is printing your number is greater than what i thought even when the guessed number is sm

相关标签:
5条回答
  • 2021-01-21 06:30

    Here datatype of guess is string where as datatype of number is integer,

    guess = raw_input ("Guess:")
    

    so both are not same, hence if statement is executed every time

    if guess > number:
    

    as string datatype is considered greater than integer datatype in python.

    Therefor you need to change the datatype of guess to int.

    Following code will help you do this

    guess = int(raw_input ("Guess:"))
    
    0 讨论(0)
  • 2021-01-21 06:32

    Catching an exception might help as well if you are guessing a large number and you accidentally hit a letter you don't really want your program to bail out.

    while guess != number:
    
        if guess > number:
            print("Your guess is greater than i thought")
    
        else:
            print("Your guess is smaller than i thought")
        try:    
            guess = int(raw_input ("Another Guess:"))
            tries = tries+1
        except ValueError:
            print "Input must be numeric"
    print "You guess it right in %d turns." %tries
    
    0 讨论(0)
  • 2021-01-21 06:34

    I didn't know this until just now, but as it turns out, a string will always be "greater than" an integer in Python:

    >>> "0" > 1
    True
    

    All you need to do is replace

    guess = raw_input ("Guess:")
    

    with

    guess = int(raw_input ("Guess:"))
    
    0 讨论(0)
  • 2021-01-21 06:35

    I think this is because raw_input is considered a string, so Python assigns it a value based on the char values. Try writing int(raw_input("text")) and see if it solves your problem.

    0 讨论(0)
  • 2021-01-21 06:39

    raw_input will return a string. You need to parse it into a number for the compare to work properly. I think that's just int(raw_input(...))

    0 讨论(0)
提交回复
热议问题