Search code examples
pythonstringloopsintegerraw-input

Integer and string conflicts


Currently I'm working on an assignment that requires that I create a program in which the user enters a number between 0-4. The program then checks which number the user inputs and outputs a specific string. For example if the user enters 4, the program will output "80 or above: Level 4"

The problem is that the user should also be able to quit the program. I decided to create the program so if the user inputs something that is not blank (while input != "":) the program will run, but if they decide to hit enter the program will end.

This is the code I've come up with so far:

def get_level():
    level = raw_input("Enter a number from 0-4 (Press <Enter> to quit): ")
    return level

def check_mark(level):
    if int(level) == 4:
        print "80 or above: Level 4"
    elif int(level) == 3:
        print "70 - 79: Level 3"
    elif int(level) == 2:
        print "60 - 69: Level 2"
    elif int(level) == 1:
        print "50 - 59: Level 1"
    elif int(level) == 0:
        print "Below 50: Level 0"
    else:
        print "ERROR: out of range"

def output(level):
   while level != "":
        level = raw_input("Enter a number from 0-4 (Press <Enter> to quit): ")
        check_mark(level)
        print

def main():
    user_level = get_level()
    user_mark = check_mark(user_level)
    print
    program_output = output(user_level)

main()

I'm pretty aware that the problem has to do with the fact that raw_input only accepts strings which is what activates the "while level != "":" statement. I tried working around this by placing int() operators before each level. The problem is that it conflicts with the input if the user enters blank since it checks whether the input is an integer. Something like that anyways.

So I was hoping someone could guide me to finding a way around this. It would be much appreciated!


Solution

  • You probably want the next looping code:

    def output(level):
       level = raw_input("Enter a number from 0-4 (Press <Enter> to quit): ")
       while level != "":
            check_mark(level)
            level = raw_input("\nEnter a number from 0-4 (Press <Enter> to quit): ")