Home > Software engineering >  How would I go about defining a function which has a while loop within it and a try-except loop with
How would I go about defining a function which has a while loop within it and a try-except loop with

Time:11-30

I am trying to make a repeatable function which uses a while loop to repeatedly try a try-except loop, but I'm having trouble with some parts. Here's my current function:

def trytrytryagain(input):  
  ValueError 
  while ValueError:  
    try:  
      input() = int(input())  
    except ValueError:  
      print("You must enter a number")  
      input = int(input())  

When I run the code and input "a" (to test if it repeatedly asks the user to input a number) it always shows this Error Message after the first iteration.

Traceback (most recent call last):
  File "main.py", line 7, in trytrytryagain
    int(input())
ValueError: invalid literal for int() with base 10: 'a'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "main.py", line 16, in <module>
    trytrytryagain (times_table)
  File "main.py", line 10, in trytrytryagain
    int(input())
ValueError: invalid literal for int() with base 10: 'a'

Thus, I am finding it very hard to create this function. It is meant to keep running until the user inputs a number, and display the message "You must enter a number" after every iteration. I'm totally confused so this is the full code for context (it's a times table generator).

from time import sleep

def trytrytryagain(input):
  ValueError
  while ValueError:
    try:
      int(input())
    except ValueError:
      print("You must enter a number")
      int(input())



print("Please input the times table you wish to complete (1, 2, 3, etc.).")
times_table = input
trytrytryagain (times_table)
print("Would you like to go up to another times table (do the 1 to 12 times tables)? yes/no")
try:
    othertables = str(input()).lower()
except ValueError:
    print("You must enter either yes or no")
    othertables = str(input()).lower()

if othertables == "yes":
  print("Enter which time table you want to go up to.")
  try:
    other_times_table = int(input())
  except ValueError:
    print("You must enter a number")
    other_times_table = int(input())
  print("Enter the maximum table you would like to go up to. (if you do the 3 to 5 times tables, what times table would you like to finish on - type 12 for 5 x 12, 13 for 5 x 13, etc.)")
  try:
    max_value = int(input())
  except ValueError:
    print("You must enter a number")
    max_value = int(input())
  for x2 in range(times_table, other_times_table   1):
    for x in range(max_value   1):
      
      print(f"{x} x {x2} =")
      input()
      sleep(0.1)
  
else:
  print("Okay.")
  print("Enter the maximum table you would like to go up to. (if you do the 3 to 5 times tables, what times table would you like to finish on (type 12 for 5 x 12, etc.))")
  try:
    max_value = int(input())
  except ValueError:
    print("You must enter a number")
    max_value = int(input())
  for x in range(times_table, max_value   1):
    answer = x * times_table
    print(f"{x} times {times_table} is {answer}")
    sleep(0.1)

CodePudding user response:

You can make this much simpler, by just catching and ignoring errors and looping until there is no exception:

def trytrytryagain():  
    while True:
        try:
            print("You must enter a number")
            return int(input())
        except ValueError:
           pass

print("You entered:", trytrytryagain())

CodePudding user response:

This is because you are calling the input function inside of your exception handling.

On the first input the exception is caught, but on the second input we are inside of the handler and nothing is catching it.

If you must use exceptions, try this:

while True:  
    try:
        print("Please enter a number") 
        var = int(input())
        break      
    except ValueError:  
        pass 

CodePudding user response:

You can use something like this:

def function():
    while True:
        try:
            return int(input())
        except ValueError:
            print("You must enter a number")

input_value = function()
print(input_value)

CodePudding user response:

Here's a little function that may help you:

def getInput(prompt, t=str):
    while True:
        v = input(f'{prompt}: ')
        try:
            return t(v)
        except ValueError:
            print('Invalid input', file=sys.stderr)

Usage examples:

S = getInput('Enter an arbitrary string') # This will return a string
I = getInput('Enter an integer', int) # This will return an int
F = getInput('Enter a float', float) # This will return a float

Of course, the second parameter could be any function that takes a string as its input and does some kind of processing

  • Related