Home > Mobile >  Problem with "while not loop" in Python code
Problem with "while not loop" in Python code

Time:02-15

I create a simple code in Phyton, it demands two numbers and until are given you´re in a loop (because the code checks if an int number is given). After that, you have to choose a certain operation. But my code can´t break the loop. I don´t know what´s wrong, if it is the indentation? If I shouldn't use a loop in this, the syntax?

dataRight = False

#Check if the data are int numbers

while not dataRight:
  print("Convert LightYears and Parsecs, enter the data:")
  dataParsec = input("Parsecs Number: ")

  try:
    dataParsec = int(dataParsec)

  except:
    dataParsec = "Error1"

  dataLight = input("LightYear Númber: ")
  try:
    dataLight = int(dataLight)

  except:
    dataLight = "Error2"
    if dataParsec != "Error1" and dataLight != "Error2":
        dataRight = True

#After the data given is right, choose the operation to make.

question = input("Choose, A)-LightYear to Parsecs, B)-Parsecs to LightYear: ")
question = question.upper()
lightYear = 3.26156

if question == "A":
  convertlightYear = dataParsec / lightYear
  print("Convert to Parsecs: ", str(convertlightYear))
elif question == "B":
  convertParsec = dataParsec * lightYear
  print("Convert to LightYear: ", str(convertParsec))
else:
  print("Data entered is wrong")

Can someone help me? It's been days and I can´t see what´s wrong.

CodePudding user response:

Code:

  • As far as I understood, your problem is non-terminating while loop. It's just because of indentation.
while not dataRight:
  print("Convert LightYears and Parsecs, enter the data:")
  dataParsec = input("Parsecs Number: ")

  try:
    dataParsec = int(dataParsec)

  except:
    dataParsec = "Error1"

  dataLight = input("LightYear Númber: ")
  try:
    dataLight = int(dataLight)

  except:
    dataLight = "Error2"
  # This must be outside the except that's all
  if dataParsec != "Error1" and dataLight != "Error2":
    dataRight = True

Output:

Convert LightYears and Parsecs, enter the data:
Parsecs Number: l
LightYear Númber: 5
Convert LightYears and Parsecs, enter the data:
Parsecs Number: 2
LightYear Númber: 5
Choose, A)-LightYear to Parsecs, B)-Parsecs to LightYear: A
Convert to Parsecs:  0.613203497712751

CodePudding user response:

If you want it to stay in the loop until the user enters a number, try something along these lines

dataParsec = input("Parsecs Number: ")
while dataParsec.isdigit() == False:
  print("Convert LightYears and Parsecs, enter the data:")
  dataParsec = input("Parsecs Number: ")
  • Related