2

I'm a beginner in the language python and have occurred some issues writing code containing a while loop which i want to check multiple conditions with one of the conditions not being checked and issues with strings/integers.

The original code (2nd code sample) was what I first wrote but the issue with it was that after a key met the condition of the first loop it would move on to the second loop so that if i entered nothing into the program when its running it will just come up with an error instead of please enter a key. The only way i could think of to fix this was to alter the code so it checks for one of multiple conditions with one while loop. But i had some issues with the variable key for each condition being a different type (integer/string) and it wasn't fixed when i attempted to use int() and str(). Besides that the code doesn't seem to check for all of the conditions. A major drawback of the altered code is that it will no longer tell the user what exactly they did wrong e.g. didn't enter anything, entered a character that's not a number

The Code:

def Key(key):
    while len(key) < 1 or key.isalpha() == True or ((key > 25) or (key < -25)):
        print("The key must be a number between numbers 26 and -26")
        key = int(input("What is the key: "))
    print (key)

key = input("What is the key: ")
Key(key)

The Original Code:

def Key(key):
    while len(key) < 1:
        print("Please enter a key")
        key = int(input("What is the key: "))
    while key.isalpha() == True :
        print("Please enter a number!")
        key = int(input("What is the key: "))
    key=int(key)
    while (key > 25) or (key < -25):
        print("The key must be in between numbers 26 and -26")
        key = int(input("What is the key: "))
    print key

key = input("What is the key: ")
Key(key)

Any help, improvements and better way of doing this would be extremely helpful Sorry for the ridiculously long post Thankyou

Aslinnl
  • 47
  • 1
  • 7

3 Answers3

0

Problem lies here while taking input from user. key is expecting an int but if you enter characters it will fail. remove (int(...)) while taking the input

while len(key) < 1:
     print("Please enter a key")
     key = int(input("What is the key: "))

If you run the code in try...except, you will find this error

Python 3.3 programming. ValueError: invalid literal for int () with base 10

Demo of your working code

Community
  • 1
  • 1
sam
  • 2,033
  • 2
  • 10
  • 13
  • You are aware that this code does not work as intended? Imagine one enters as key 'a', which fulfils the condition len(key) < 1 of the first loop. This will end up stuck in the second loop, since its not a number. However the previous precondition (len(key) < 1) will not be checked any further in the program and hence the error message print("Please enter a key") won't be shown. – DJanssens Oct 15 '15 at 15:53
  • @DJanssens this is OP's code. I am just explaining where its wrong. If you click on Demo, you will see updated code – sam Oct 15 '15 at 15:54
0

Programmers should be lazy. The good kind of lazy. For instance follow the „Don't Repeat Yourself“ principle (DRY) and don't repeat data and/or code like the call and prompt for asking the user for a key.

Python has no DO … WHILE kind of loop, so this is usually written as an ”endless” loop which is left with break or return when the right condition is met.

def ask_for_key(lower_limit=-25, upper_limit=25):
    while True:
        try:
            result = int(raw_input('What is the key: '))
        except ValueError:
            pass  # Intentionally ignored.
        else:
            if lower_limit <= result <= upper_limit:
                return result
        print 'The key must be a number between {0} and {1}'.format(
            lower_limit, upper_limit
        )
BlackJack
  • 4,476
  • 1
  • 20
  • 25
-1

As you described yourself, there were some major problems with your original code. Namely the fact that you could pass a specific test, but later in a further while loop you could still end up with an incorrect input which was "checked' in a previous while loop.

Checking it all together is a good idea. I'd suggest to use a check function that checks if the key fits or not. It returns True if it does and False if it doesn't. This way you won't repeat yourself over and over and just need one while loop that keeps checking the input until it's correct.

Something like:

def check_key(key):
    if len(key) < 1:
        print("Please enter a key")
        return False
    if key.isalpha() == True :
        print("Please enter a number!")
        return False
    if (int(key) > 25) or (int(key) < -25):
        print("The key must be in between numbers 26 and -26")
        return False
    return True

def main():
    key = raw_input("What is the key: ")
    while check_key(key) == False:
        key = raw_input("What is the key: ")

if __name__ == "__main__":
    main()
DJanssens
  • 17,849
  • 7
  • 27
  • 42
  • I'm wondering why I got a down vote, OP asked for a solution that was able to output different error messages, so the user knows what went wrong. – DJanssens Oct 15 '15 at 15:43