So I am currently learning how to code Python right now. I decided to do a little program where it requires the user to input a word to command the program to do certain things. I have been having the issue though with putting in every variant of capitalization of the word into the code. My question is, how can I prevent this? Any help would be appreciated. Please keep in mind I am learning Python still and may not understand everything. Here is my code:
#This is the main program.
if choice == '1':
print ("Not Availble Yet")
print (" ")
time.sleep(2.5)
main()
#This is if you wish to quit.
if choice =='2':
end = input ("Are you sure you'd like to quit? ")
#These are all the "I'd like to quit" options.
if end == 'yes':
print ("Closing Program in 5 seconds").lower
time.sleep(5)
quit
if end == 'Yes':
print ("Closing Program in 5 seconds").lower
time.sleep(5)
quit
if end == 'yEs':
print ("Closing Program in 5 seconds").lower
time.sleep(5)
quit
if end == ("yeS"):
print ("Closing Program in 5 seconds").lower
time.sleep(5)
quit
if end == ("YES"):
print ("Closing Program in 5 seconds").lower
time.sleep(5)
quit
#These are all the "I wouldn't like to quit" options.
if end == 'no':
print ("Continuing Program").lower
time.sleep(2.5)
main()
Thank you!
Lowercase the input:
end = input ("Are you sure you'd like to quit? ")
end = end.lower()
Then check for "yes" and "no" only.
(This is an instance of a general principle called "input normalization", a very common way to simplify programs.)
Related
If I print a capital letter instead writing everything in small letters, the function doesn´t give me the correct output.
I would like to have the output "good bye", when I write: Quit quit QuIt
This is the Output right now if I take Quit or quit as an Input
Quit
This is not a valid option. Please try again.
quit
good bye
quit = True
help = ("""
start- to start the car
stop - to stop the car
quit - to exit
""")
print(help)
while quit:
operation = input(">")
if operation == "start":
print("Car started")
elif operation == "stop":
print("Car stopped")
elif operation == "quit":
print("good bye")
break
else:
print("This is not a valid option. Please try again.")
Use .lower() function on the input string to transform your text into lowercase.
So use operation = input(">").lower()
Here you can find a small docs
Convert your input to lower case.
operation = input(">").lower()
I am attempting to create a loop which a user can stop at the end of the program. I've tried various solutions, none of which have worked, all I have managed to do is create the loop but I can't seem to end it. I only recently started learning Python and I would be grateful if someone could enlighten me on this issue.
def main():
while True:
NoChild = int(0)
NoAdult = int(0)
NoDays = int(0)
AdultCost = int(0)
ChildCost = int(0)
FinalCost = int(0)
print ("Welcome to Superslides!")
print ("The theme park with the biggest water slide in Europe.")
NoAdult = int(raw_input("How many adults are there?"))
NoChild = int(raw_input("How many children are there?"))
NoDays = int(raw_input("How many days will you be at the theme park?"))
WeekDay = (raw_input("Will you be attending the park on a weekday? (Yes/No)"))
if WeekDay == "Yes":
AdultCost = NoAdult * 5
elif WeekDay == "No":
AdultCost = NoAdult * 10
ChildCost = NoChild * 5
FinalCost = (AdultCost + ChildCost)*NoDays
print ("Order Summary")
print("Number of Adults: ",NoAdult,"Cost: ",AdultCost)
print("Number of Children: ",NoChild,"Cost: ",ChildCost)
print("Your final total is:",FinalCost)
print("Have a nice day at SuperSlides!")
again = raw_input("Would you like to process another customer? (Yes/No)")
if again =="No":
print("Goodbye!")
return
elif again =="Yes":
print("Next Customer.")
else:
print("You should enter either Yes or No.")
if __name__=="__main__":
main()
You can change the return to break and it will exit the while loop
if again =="No":
print("Goodbye!")
break
Instead of this:
while True:
You should use this:
again = True
while again:
...
usrIn = raw_input("Would you like to process another customer? y/n")
if usrIn == 'y':
again = True
else
again = False
I just made it default to False, but you can always just make it ask the user for a new input if they don't enter y or n.
I checked your code with python 3.5 and it worked after I changed the raw_input to input, since input in 3.5 is the raw_input of 2.7. Since you're using print() as a function, you should have an import of the print function from future package in your import section. I can't see no import section in your script.
What exactly doesn't work?
Additionally: It's a good habit to end a command line application by exiting with an exit code instead of breaking and ending. So you would have to
import sys
in the import section of your python script and when checking for ending the program by the user, do a
if again == "No":
print("Good Bye")
sys.exit(0)
This gives you the opportunity in case of an error to exit with a different exit code.
Change this code snippet
if again =="No":
print("Goodbye!")
exit() #this will close the program
elif again =="Yes":
print("Next Customer.")
exit()#this will close the program
else:
print("You should enter either Yes or No.")
import random
import time
name=input("Welcome to the game what is your name")
print(("This is a numbers game"),(name),
("You will be playing against the computer"))
print
("The idea of the game is to get closer than the computer to 21 without
going over 21")
,ready="N"
ready = input("Are you ready to play the game?").lower
if ready == "yes" or ready =="y":
score=0
The Error is coming up and saying its the line above this
while(score)<21 and(ready=="Y" or ready == "Yes"
or ready =="YES" or ready ==
"yes" or ready =="y"):
player1=random.randint(1,21)
score=(score+player1)
time.sleep(3)
print(("You have scored"),(score))
if score<21:
ready=input("Do you want to add more to your score")
if score>21:
print("Sorry Over 21 You Went Bust The Computer Wins")
else:
print("Ok well done lets see what the computer gets")
(Ignore this line please)
computerscore=0
while(computerscore)<21 and (computerscore)<(score):
computer=random.randint(1,21)
computerscore=(computerscore+computer)
time.sleep(3)
print(("The Computer Has Scored"),(computerscore))
if(computerscore)<=21 and (computerscore)>(score):
print("sorry the computer wins")
else:
print("You win well done")
break
I ran it in the CMD
You have to indent the blocks after your conditions lines, that's how python understands if you're still in the condition or not.
if a>b:
print b
print "I'm still in the case a>b"
else:
print a
Use tab or 4 spaces to indent.
I am attempting to exit a program without using sys.exit()
The user is asked whether they wish to continue and if they input "Yes" a message saying so is printed and the program continues to run. If they input anything else a message saying they chose to exit is printed and then the program is meant to exit.
def keep_going():
answer = raw_input("Do you wish to continue?")
if answer == "yes":
print "You have chosen to continue on"
else:
print "You have chosen to quit this program"
What I am struggling with is what to add to ELSE to return something to my main which will cause the program to exit and how to go about writing that in code.
If you are so much keen about not using sys.exit() you could directly use raise SystemExit. Well this exception is technically raised when you call sys.exit() explicitly. In this way you don't need to import sys at all.
def keep_going():
answer = raw_input("Do you wish to continue?")
if (answer == "yes"):
print ("You have chosen to continue on")
else:
print "You have chosen to quit this program"
raise SystemExit
This answer will give you the alternate possible ways.
Try this:
def main():
while keep_going():
keep_going()
def keep_going():
answer = raw_input("Do you wish to continue?")
if answer == "yes":
print "You have chosen to continue on"
return True
else:
print "You have chosen to quit this program"
return False
if __name__ == "__main__":
main()
The program will continue calling keep_going() as long as it returns true, that is when a user answers "yes"
An even shorter solution would be to call keep_going() after the "yes" condition:
def keep_going():
answer = raw_input("Do you wish to continue?")
if answer == "yes":
print "You have chosen to continue on"
keep_going()
else:
print "You have chosen to quit this program"
Just, return something, and if that is returned, then let your main function exit, either by falling off the end, by using a return statement, or calling sys.exit()/raise SystemExit.
As an example, I'm here returning a string (a different one based on what the user answered):
def keep_going():
answer = raw_input("Do you wish to continue?")
if answer == "yes":
print "You have chosen to continue on"
return "keep going"
else:
print "You have chosen to quit this program"
return "please exit"
Now, in main, I can test which of these strings keep_going() returned:
def main():
while keep_going() != 'please exit':
# your code here
if __name__ == "__main__":
main()
While strings will work for this purpose, other values are more commonly used for such a task. If keep_going() returned True (instead of "keep going") or False (instead of "please exit"), then main could be written like
def main():
while keep_going():
# your code here
This also reads pretty naturally ("while keep going do your code"). Note that in this case I'm not comparing the return value to something since True and False are truthy variables - and Python's branching control structures (like if and while) know how they work, i.e. there is no need to write keep_going() == True, and indeed it is considered un-pythonic to do so.
You can try this
def keep_going():
answer = raw_input("Do you wish to continue?")
if answer == "yes":
print "You have chosen to continue on"
else:
print "You have chosen to quit this program"
quit()
I am making a quiz game for a school project and I want to make it so that when the user inputs an invalid command, it goes back and tries the input to goto that menu again and brings up the exact same input box and tries the code again. I will post a part where I want this to happen.
#---->TO HERE
if userinput == str("help"):
print ("This is the help menu")
print ("This is how you play")
else:
print ("Invalid Command")
#This is where I want the user to go back and try entering a command again to get the same code to run through again.
#FROM HERE <----
while True:
userinput = input()
if userinput == 'help':
print('This is the help menu')
print('This is how you play')
break
else:
print('Invalid command')
The while loop is used for situations like these. The break statement allows you to 'break' out of a while or for loop. A while True loop will loop forever, unless it encounters the break statement.
There is also a continue statement which allows you to skip the rest of the loop and go back to the beginning, but there's no need to use it here.
See the docs for further reading.
I'm not a fan of infinite loops with breaks, so here's something that I like better:
validCommands = ['help']
userInput = None
while userInput not in validCommands:
userInput = input("enter a command: ").strip()
handleInput(userInput)
def handleInput(userInput):
responses = {'help':['This is the help menu', 'This is how you play']
}
print('\n'.join(responses[userInput]))
questions = {
'quiz_question_1': quiz_question_1,
'quiz_question_2': quiz_question_2
}
def runner(map, start):
next = start
while True:
questions = map[next]
next = questions()
# whatever room you have set here will be the first one to appear
runner(questions, 'quiz_question_1')
def quiz_question_1():
a = raw_input(">")
if a == "correct answer"
return "quiz_question_2"
if a == "incorrect answer"
return "quiz_question_1"
you can add more "rooms" to the in the squiggly brackets. Just make sure that the last room
does NOT have a comma, and that they are in order in which they appear in the code.