TransWikia.com

while loop printing everything twice, Python --checking if an input is an intiger AND in range (0-10)--

Stack Overflow Asked by makif on December 16, 2020

I am doing an excercise, created a while loop but it is printing everything twice. I’m pretty new at programming, so excuse me if this is some kind of stupid easy mistake.

def user_choice():

    choice = "wrong"
    within_range = False

    while choice.isdigit() == False or within_range == False:
    
        choice = input("Please enter a number (0-10): ")
    
        if choice.isdigit() == False:
            print("Please enter a digit!")
    
        if within_range == False:
            print("Please enter a number in range (0-10)")
    
        if choice.isdigit() == True:
            within_range = int(choice) in range(0,10)
    
    
    
    return int(choice)

2 Answers

You are evaluating the responses in the wrong order to be handled by the while statement. Here is one way:

def user_choice():
    choice_is_digit = False
    within_range = False

    while choice_is_digit == False or within_range == False:

        choice = input("Please enter a number (0-10): ")

        choice_is_digit =  choice.isdigit()

        if choice_is_digit == False:
            print("Please enter a digit!")
            continue  # skip rest of loop

        within_range = int(choice) in range(0,10)

        if within_range == False:
            print("Please enter a number in range (0-10)")

    return int(choice)

Answered by RufusVS on December 16, 2020

Having multiple if statements means that it's possible the code will hit all 3 depending on the conditions.

Changing them to an if else block means it can only use one of them.

It's checks for a condition match from the top down so if it finds the conditions match in the first if then It would skip the remaining 2 options.

Your way, it would check the first if, and if it evaluates to True it would fire the code in the if block and then check the second if statement etc etc and so on.

Try this:

`def user_choice():

choice = "wrong"
within_range = False

while choice.isdigit() == False or within_range == False:

    choice = input("Please enter a number (0-10): ")

    if choice.isdigit() == False:
        print("Please enter a digit!")

    elif within_range == False:
        print("Please enter a number in range (0-10)")

    elif choice.isdigit() == True:
        within_range = int(choice) in range(0,10)



return int(choice)`

Answered by Lewis Morris on December 16, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP