I am working on a project where I must ask the user to make a selection, I must limit their answers between 1-4 and have the program inform them when they have made a unacceptable selection. My issue comes when I try to modify the limiter to not crash when the user enters a empty space as a input.
No matter how I alter this code below, I receive a invalid syntax error. Any suggestions on how to fix this error? I do not know if it has anything to do with the boolean not, but that is the part of the code I added which causes the error. The original limiter was given to the entire class by the instructor.
def questionHairstyle():
while True:
hairchoice = ()
questionsH = (" 1, for bald;" "\n" " 2, for crew-cut;"
"\n" " 3, for curly;" "\n" " 4, for wearing a hat;")
print("Please enter a hairstyle:")
print(questionsH)
hairchoice = input("--> ", )
print()
if hairchoice[0] >= "1" and hairchoice[0] <= "4"
and not hairchoice[0] == " " and len(hairchoice) ==1:
break
print("Choice must be, between 1-4, not ", hairchoice + ".")
print("Try again.")
The exact error message.
File "C:\Python34\Projects\sketch\sketch4.py", line 34
if hairchoice[0] >= "1" and hairchoice[0] <= "4"
^
SyntaxError: invalid syntax
I Have improvised code from @FunkySayu.
def questionHairstyle():
while True:
questionsH = [" 1, for bald;",
" 2, for crew-cut;",
" 3, for curly;",
" 4, for wearing a hat"
]
print("Please enter a hairstyle:")
print("\n".join(questionsH))
hairchoice = raw_input("-->") #This will take even spaces
print()
if hairchoice in ["1", "2", "3", "4"]:
break
elif hairchoice == " ": #This part checks for space as input from user
print ("Space is encountered ")
print("Choice must be, between 1-4, not ", hairchoice, ".")
# This part of code can be extended for other user input also
print("Try again.")
questionHairstyle()
output:
Please enter a hairstyle:
1, for bald;
2, for crew-cut;
3, for curly;
4, for wearing a hat
-->
()
Space is encountered
('Choice must be, between 1-4, not ', ' ', '.') #You can see the ' ' space is identified well in the output.
Try again.
Please enter a hairstyle:
1, for bald;
2, for crew-cut;
3, for curly;
4, for wearing a hat
-->