-1

i am trying to relearn the basics and i have this code,

try:
    n1 = float(input('enter a number: '))
except ValueError:
    print('invalid input!')
    n1 = float(input('enter a number: '))
        
    
try:
    n2 = float(input('enter a second number: '))
except ValueError:
    print('invalid input!')
    n2 = float(input('enter a second number: '))

this is part of a bigger program and this is the section designed to detect if the valid input (number) is entered, it is meant to repeat until a number is entered but it only loops once before an error occurs 'cant convert string to float'. i have tried to put a while loop around it but i cant get it to work. if anyone can help with a solution i would greatly appreciate it. thank you

i tried to add a while loop to this section of the program to make it loop until a number was entered but it still only loops once before an error message.

David
  • 208,112
  • 36
  • 198
  • 279
  • I see no loop in this code. Which line in the code shown is producing the error you describe? What exact input is being used when that happens? – David Jun 22 '23 at 18:23
  • @David OP clearly said they "tried to put a while loop around *this* section of code, and it didn't work". – Ryan Jun 22 '23 at 18:24
  • 3
    There's no loops in the snippet you've provided, so no wonder the looping doesn't happen :) Perhaps it would be more helpful if you showed your version with while loop that did not work. – Maria K Jun 22 '23 at 18:24
  • 2
    @Ryan: And the code shown clearly has no while loop. If *some other code* isn't working as expected, it would be best for the OP to share that code. – David Jun 22 '23 at 18:25
  • 1
    If you post the loop you tried, someone might be able to help you fix it. – Scott Hunter Jun 22 '23 at 18:27
  • @David Obviously, lol. It is abundantly clear that they mean that simply putting a while loop around this code makes the code not behave as intended. Why would any other code be involved? – Ryan Jun 22 '23 at 18:28
  • @Ryan: In general, if someone has written specific code which is failing in a specific way, they are encouraged to include that code as a [mcve] in their question. If the only question being asked is essentially "How do I write a loop in Python?" then the answer would be to start with some introductory tutorials on Python, which this community does not provide. To learn more about this community and how we can help each other, you are encouraged to start with the [tour] and read [ask] and its linked resources. – David Jun 22 '23 at 18:30
  • @David I'm aware - I've been on this platform for years. I dislike when users are condescending and patronizing to new users, so I think it's quite alright to have to read between the lines sometimes. – Ryan Jun 22 '23 at 18:34

5 Answers5

2
while True:
    try:
        n1 = float(input('enter a number: '))
        break
    except ValueError:
        print('invalid input!')

I think this is what you're looking for. If the input is successfully converted to a float, the break statement will hit and break you out of the while loop. If a value error is raised then the warning message will print and the loop will re run.

0

it does not work because once you hit an exception you ask again for input in that exception block that you try convert to float and that can create another exception. try:

while True:
    try:
        n1 = float(input('enter a number: '))
    except ValueError:
        print('invalid input!')
        continue
    else: break

while True:
    try:
        n2 = float(input('enter a second number: '))
    except ValueError:
        print('invalid input!')
        continue
    else: break

or better yet, make a function for input that you call twice.

richard
  • 144
  • 3
0

@Aidan Donohue's answer is a good, simple solution to your problem. You can repeat that code for both n1 and n2, if you want.

If you want to handle both variables in one loop (like you imply), you could do something like this:

n1 = None
n2 = None

while n1 is None or n2 is None:
    
    if n1 is None:
        try:
            n1 = float(input('enter a number: '))
        except ValueError:
            print('invalid input!')
            
            
    if n2 is None:
        try:
            n2 = float(input('enter a second number: '))
        except ValueError:
            print('invalid input!')

This will loop until both n1 and n2 are valid floats.

Ryan
  • 1,081
  • 6
  • 14
0

You'll want the while loop to repeat if the input isn't valid and stop repeating if the input is valid. Probably the most straightforward way to do this is to use a flag variable, aka a bool that you can use to switch the while loop on or off:

n=input('enter a number: ')
whileLoopSwitch=True
while whileLoopSwitch:
    whileLoopSwitch=False
    try:
        n = float(n)
    except ValueError:
        print('invalid input!')
        n = input('enter another number: ')
        whileLoopSwitch=True

You can also use the else condition with the try/except to have certain lines only run if the except ValueError: lines don't run. That way, you can keep the flag variable set to True until you get a valid input and just turn if off then, which might make things simpler:

invalidInput=True
while invalidInput:
    try:
        n=float(input('enter a number: '))
    except ValueError:
        print('invalid input!')
    else: invalidInput=False
Tiger Ros
  • 31
  • 3
0

I'd suggest using a while loop for each input. This way you're not repeatedly asking for both numbers even if one passes the conversion. You could make this a function such as:

def get_input(message, as_type = str):
    while True:
        try:
            return as_type(input(message))
        except ValueError:
            print(f"Expecting input as {as_type} type. Please provide a valid input")

And to use this you can do:

n1 = get_input("enter a number: ", float)
n2 = get_input("enter a second number: ", float)
Jab
  • 26,853
  • 21
  • 75
  • 114