Home > Mobile >  while gets stuck in def function
while gets stuck in def function

Time:11-09

I'm a bit of a noob so i struggle generalising the previous solutions that were posted to adapt them into my programme.

the task is the following: Given three integers. Determine how many of them are equal to each other. The program must print one of the numbers: 3 (if all are same), 2 (if two of them are equal to each other and the third one is different) or 0 (if all numbers are different).

i figured i could do a def function to check if the inputs are all integers and not floats or strings. While the programme works if only integers are input, it gets stuck on my except if another type is input

def valuecheck(checker):
  loopx = True
  while loopx:
    try:
      #first it checks if the input is actually an integer
      checker = int(checker)
      loopx = False 
      return(checker)
      #if input isn't an integer the below prompt is printed
    except:
     input("Value isn't a valid input, try again: ")

varA = input("please input an integer: ")
varA = valuecheck(varA)
x = varA

varB = input("please input anther integer: ")
varB = valuecheck(varB)
y = varB

varC = input("please input another integer: ")
varC = valuecheck(varC)
z = varC

if x == y == z:
  print(3,"of the integers are of the same value")
elif x == y or y == z or x == z:
  print(2,"of the integers are of the same value")
else: 
  print(0, "of the integers are of the same value")

my code so far. it should be able to tell the user if anything other than an integer is input and allow them to try again.

CodePudding user response:

If checker is not a valid int you'll reach the except block and call for another input, but you missed assigning that value back to checker:

def valuecheck(checker):
  loopx = True
  while loopx:
    try:
      #first it checks if the input is actually an integer
      checker = int(checker)
      loopx = False 
      return(checker)
      #if input isn't an integer the below prompt is printed
    except:
      checker = input("Value isn't a valid input, try again: ") # Here!

CodePudding user response:

I think you need, checker = input("Value isn't a valid input, try again: "). Otherwise the value is not assigned.

CodePudding user response:

def valuecheck(value):
    if isinstance(value, int):
        return value
    else:
        while(True):
            value = input("Value isn't a valid input, try again: ")
            try:
                value = int(value)
                return val
            except:
                pass
  • Related