Getting an Integer Input in a Range

后端 未结 5 471
鱼传尺愫
鱼传尺愫 2021-01-03 11:30

I\'m trying to take a raw input and detect whether it is in a range.
Here\'s my code.

def gold_room():
    print \"This room is full of gold. How much          


        
相关标签:
5条回答
  • 2021-01-03 12:07

    Since raw_input returns a string, you need to convert to an int first. Try replacing the line with this:

    if int(next) in range(50):
    
    0 讨论(0)
  • 2021-01-03 12:07

    The test "next == int in range(50)" evaluates to "(next == int) and (int in range(50))" which is fairly meaningless and always equates to false.

    Instead you could try

    try:
        how_much = int(next)
        if not (0<=how_much<50):
           print 'Too greedy'
    except ValueError:
        dead("Man, learn how to type a number.")
    
    0 讨论(0)
  • 2021-01-03 12:09

    Using try .. except will allow you to make sure entered value is an int. # raise is a place holder for your handling a non-int contition:

    try:
        next = int(raw_input("> "))
    except ValueError:
        # raise
    
    if not 0 <= next <= 50:
        print 'Too greedy'
    
    0 讨论(0)
  • 2021-01-03 12:23

    The result of raw_input() will be a string, so first you need to check to see if next is all digits. There are a few ways to do this, the easiest is to use the str.isdigit() function:

    next = raw_input("> ")
    if next.isdigit():
        how_much = int(next)
    else:
        dead("Man, learn how to type a number.")
    

    Note that you do not need to check to see if the value for next is in the range from 0 to 50, since your next if statement already checks to see if the value is less than 50 and negative numbers will be excluded by next.isdigit().

    0 讨论(0)
  • 2021-01-03 12:30

    If you want to "get an integer input in a range", you'll need two things:

    1. Check if the input is an int
    2. Check if it's in your range

    Check if the input is an int

    try/except will be perfect here:

    n = raw_input('> ')
    try:
        n = int(n)
    except ValueError:
        dead() # or what you want
    

    Why this is good?
    Because if n is an int you'll have it convert it to an integer and if it's not an exception get raised and you can call your dead() funcion.

    Check if it's in your range

    If you get to this point it means that the exception before it was not raised and n was converted to an integer.

    So you just need to do:

    if 0 <= n <= 50:
        print 'You win'
    else:
        print 'You lose'
    

    Don't do:

    if n in range(50):
        # ...
    

    Beacuse it will build a list of 50 numbers for nothing.

    Note: don't use next as a variable, beacuse it'll shadow the built-in next()

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