My Python code contains an infinite loop. How can I terminate the infinite loop?
colour = input("Which colour do you prefer? Y-R: ")
while colour not in {"Y", "R"}:
print("Please, you have to choose only Y - R.")
colour = input("Which colour do you prefer? Y-R: ")
while colour in {"Y", "R"}:
if colour == "Y":
print("First player: Y")
print("Second player: R")
else:
print("First player: R")
print("Second player: Y")
Use break
:
colour = input("Which colour do you prefer? Y-R: ")
while colour not in ["Y", "R"]:
print("Please, you have to choose only Y - R.")
colour = input("Which colour do you prefer? Y-R: ")
if colour in ["Y", "R"]:
if colour == "Y":
print("First player: Y")
print("Second player: R")
break
else:
print("First player: R")
print("Second player: Y")
break
However this is a better solution:
colour = input("Which colour do you prefer? Y-R: ")
while colour not in ["Y", "R"]:
print("Please, you have to choose only Y - R.")
colour = input("Which colour do you prefer? Y-R: ")
if colour == "Y":
print("First player: Y")
print("Second player: R")
else:
print("First player: R")
print("Second player: Y")
You really only need a single loop.
while True:
colour = input("Which colour do you prefer? Y-R: ")
if colour in {"Y", "R"}:
first, second = "YR" if colour == "Y" else "RY"
break
print("Please, you have to choose only Y - R.")
print(f"First player: {first}")
print(f"Second player: {second}")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.