Reputation: 63
i am learning python 3.6 while writing my script i come across a problem:
below are my codes
from sys import exit
print("Welcome to the official game designed by Prince Bhatia")
print("Copywrite @princebhatia")
def list1():
loop = 5
while loop == 5:
print("Game starts here")
list1 = ["Rahul", "Prince", "Sam", "Sonu"]
print("which Player do you choose?")
print("Now the game starts")
name1 = input()
if "Rahul" in name1 or "rahul" in name1:
print("Rahul Enters the room1")
elif "Prince" in name1 or "prince" in name1:
print("Prince Enters the room2")
elif "Sam" in name1 or "sam" in name1:
print("Sam Enters the room3")
elif "Sonu" in name1 or "sonu" in name1:
print("Sonu Enters the room4")
else:
print("Please enter the valid name")
loop = 6
list1()
print("""-------------------------------------""")
but problem is whenever i enter the defined names it works fine but when i enter the wrong name it stops, but what i want it should keep me asking "please enter valid name " until i enter valid name. any suggestion. python 3.6
intend space is given here to give enter code
Upvotes: 0
Views: 127
Reputation: 2191
First of all, your indentation is wrong.
To the problem: You are setting loop = 6 anyways, independent of whether you got a matching answer or not.
Here a slightly different suggestion:
print("Game starts here")
print("which Player do you choose?")
print("Now the game starts")
while True:
name1 = input()
if "Rahul" in name1 or "rahul" in name1:
print("Rahul Enters the room1")
break
elif "Prince" in name1 or "prince" in name1:
print("Prince Enters the room2")
break
elif "Sam" in name1 or "sam" in name1:
print("Sam Enters the room3")
break
elif "Sonu" in name1 or "sonu" in name1:
print("Sonu Enters the room4")
break
else:
print("Please enter the valid name")
This way we break the loop once we get a valid input, otherwise we keep looping indefinitely.
Upvotes: 1
Reputation: 10356
You can assign 5 to loop
in the else
and move up the assignment of 6 to the same variable:
from sys import exit
print("Welcome to the official game designed by Prince Bhatia")
print("Copywrite @princebhatia")
def list1():
loop = 5
while loop == 5:
print("Game starts here")
list1 = ["Rahul", "Prince", "Sam", "Sonu"]
print("which Player do you choose?")
print("Now the game starts")
name1 = input()
loop = 6
if "Rahul" in name1 or "rahul" in name1:
print("Rahul Enters the room1")
elif "Prince" in name1 or "prince" in name1:
print("Prince Enters the room2")
elif "Sam" in name1 or "sam" in name1:
print("Sam Enters the room3")
elif "Sonu" in name1 or "sonu" in name1:
print("Sonu Enters the room4")
else:
print("Please enter the valid name")
loop = 5
list1()
print("""-------------------------------------""")
Anyway, it is a nice idea improving the name of this variable and the value. It would be better use a boolean variable here with a name like isInvalidName. So you while
would be: while isInvalidName:
Upvotes: 1