I need this code to only accept “y” or “n” for the sYesOrNo
input. If user enters invalid input, I need it to re-display the sYesOrNo
input prompt.
It repeats the loop if user enters “y” and breaks out of the loop if user enters “n” like it’s supposed to.
But it also breaks out of the loop with invalid input.
I cannot use functions for this. It can only be a loop.
sYesOrNo = "y"
while sYesOrNo == "y" :
fSalesPrice = getFloatInput("Enter property sales value: ")
fProperty_Values.append (fSalesPrice)
sYesOrNo = input("Enter another value Y or N: ").lower()
if sYesOrNo == "n" :
break
RLA is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
0
Maybe you could rewrite your while condition like this:
sYesOrNo = "y"
while True:
if sYesOrNo == "y":
fSalesPrice = getFloatInput("Enter property sales value: ")
fProperty_Values.append (fSalesPrice)
sYesOrNo = input("Enter another value Y or N: ").lower()
if sYesOrNo == "n":
break
… so that you won’t need to nest your code in two loops and make it O(n^2)
, and have difficulties trying to get out of more than one loop with the break
.
1
You already have a function that (apparently) handles acquisition of float values so why not have something similar to manage yes/no input?
How about:
from sys import stdout
def beep() -> None:
# will emit BEL to stdout which, depending on the terminal, may make a sound
stdout.write("a")
def getFloatInput(prompt: str) -> float:
while True:
try:
return float(input(prompt))
except ValueError:
beep()
def getYesNoInput(prompt: str) -> str:
while True:
if (v := input(prompt)) in set("ynYN"):
return v.lower()
beep()
fProperty_Values: list[float] = []
while True:
fSalesPrice = getFloatInput("Enter property sales value: ")
fProperty_Values.append(fSalesPrice)
if getYesNoInput("Enter another value Y or N: ") == "n":
break
print(fProperty_Values)