Syntax Error When Making Python Chatbot Using Conditional - python

Error comes up here in line six:
import time
askingage=input("Are you over the age of 18? ").lower()
if askingage == "yes":
{
time.sleep(2)
print("Wow, you're a fully mature adult!")

Even if it's a very standard\simple code at least I suggest you to explore further way to prevent user inputs errors - such as: define a list of accepted answer (only "yes" seems a bit too restrictive), and prevent the routine goes bananas with a try\catch (my example is just vanilla but you can easily add further checks to prevent the user give undesidered answers).
Also, time.sleep(2) is affecting UX, I suggest to use lower (or zero) pauses for such basic questions. If you'd like to prompt until a right answer is given, explore while loops.
good luck with your implementation and keep struggling! it's the best way to learn
import time
accepted = ["yes", "y", "sure"]
askingage=input("Are you over the age of 18? ").lower()
try:
if askingage in accepted:
time.sleep(0.5)
print("Wow, you're a fully mature adult!")
else:
print("Sorry, you need to be 18 at least to proceed.")
except Exception as e:
print ("Sorry, something went wrong there. Can you Try again?")

Related

I just started programming and am having problem with both of these while loops

I've just starting a programming course and im making an adventure game.
I've gotten up to this "path" where the user must choose between the market or the blacksmith.
If they choose either they have two choices and if they dont say either choice I want to re-ask and go through the loop again. currently if I type everything in first try it works but if I fail to provide a valid answer it prompts to re-enter then doesn't go through the loop again.
How do I write this to take my:
else:
print ("Choice must be (Sword / Platemail)...")
answer = input ("").lower().strip()
and
else:
print ("Choice must be (Bread / Cabbage)...")
answer = input("").lower().strip()
return to the top of the loop with the "answer" in order to have the if and elif statments do what they need to do?
Any help recommendations would be amazing please keep in mind im brand new to programming.
Picture of code in question
The pattern is like this:
while True:
answer = input("Choice?").lower().strip()
if answer in ('sword','platemail'):
break
print("Choice must be Sword or Platemail")
For cleaner code, you might want to put this into a function, where you pass the possible answers and return the validated one.

Trying to end a script based on users answer (at a particular point) within a multiple choice scenario

I've created a basic, multiple choice, interactive calculator in Python. I want the user to be able to have the option to stop the programme running by answering "No" when asked whether they want to test out my calculator.
I want to be able to print("Ok, no problem") which you can see is already there but I need something extra to stop the programme running if this is the answer that the user picks.
Code is below. See lines 12-13.
name = input("Hi There. What is your name? ")
print("Well Hi " + name + ", it sure is nice to meet you")
age = input("So how old are you anyway? ")
print("Wow, you're " + age + " huh? ")
print(name + " I would like you to try out the companies new calculator. Would you be
happy to do that? ")
answer = input("Please answer Yes or No ")
if answer == "Yes":
print("Thank you, I appreciated that. Let's begin")
elif answer == "No":
print("Ok, no problem")
else:
print("Sorry I didn't quite get that. Please answer yes or no")
import math
number_1 = int(input("Please pick a number "))
order = (input("Ok, now please pick either: +, -, / or * "))
number_2 = int(input("Great, now please pick a second number "))
if order == "+":
print(number_1 + number_2)
elif order == "-":
print(number_1 - number_2)
elif order == "/":
print(number_1 / number_2)
elif order == "*":
print(number_1 * number_2)
else:
print("Sorry that is not +, -, / or *. Please enter a relevant order")
Any help that you can give me would be much appreciated.
You can use sys.exit to terminate the program:
import sys
#...
elif answer == "No":
print("Ok, no problem")
sys.exit()
Here is an answer for you which helped me out:
Let me give some information on them:
quit() raises the SystemExit exception behind the scenes.
Furthermore, if you print it, it will give a message:
>>> print (quit)
Use quit() or Ctrl-Z plus Return to exit
>>>
This functionality was included to help people who do not know Python. After all, one of the most likely things a newbie will try to exit Python is typing in quit.
Nevertheless, quit should not be used in production code. This is because it only works if the site module is loaded. Instead, this function should only be used in the interpreter.
exit() is an alias for quit (or vice-versa). They exist together simply to make Python more user-friendly.
Furthermore, it too gives a message when printed:
>>> print (exit)
Use exit() or Ctrl-Z plus Return to exit
>>>
However, like quit, exit is considered bad to use in production code and should be reserved for use in the interpreter. This is because it too relies on the site module.
sys.exit() raises the SystemExit exception in the background. This means that it is the same as quit and exit in that respect.
Unlike those two however, sys.exit is considered good to use in production code. This is because the sys module will always be there.
os._exit() exits the program without calling cleanup handlers, flushing stdio buffers, etc. Thus, it is not a standard way to exit and should only be used in special cases. The most common of these is in the child process(es) created by os.fork.
Note that, of the four methods given, only this one is unique in what it does.
Summed up, all four methods exit the program. However, the first two are considered bad to use in production code and the last is a non-standard, dirty way that is only used in special scenarios. So, if you want to exit a program normally, go with the third method: sys.exit.
Or, even better in my opinion, you can just do directly what sys.exit does behind the scenes and run:
raise SystemExit
This way, you do not need to import sys first.
However, this choice is simply one on style and is purely up to you.

Code that consistently asks a question until proper input that can be repeated many times + the ability to accept multiple inputs? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
Firstly, sorry for the long title.
So... I am making a text adventure game in Python for learning purposes. I spent most of last night trying to squash a bug in my game where no matter what you typed it would take you 'north'. I could input "sadjbfl" and it would just take me "north" instead of giving an error. (But I could also put "south" and it would take me south...)
I figured out a "while True" loop by searching for how to do this online but then I ran into another couple of problems with it, the first being that I could not make it accept multiple inputs. I could not allow it to accept "'north' OR 'n'"; it would then just accept literally anything as the first choice. The second problem is that I believe I would need a "while True" loop for every choice in the game.
The other way I have tried to accomplish this is a simple "ask for 'north' or 'n' and if it's none of that then print 'error'" but when it prints an error the program stops running when I need it to re-ask the question.
"Solution" 1:
# this code works perfectly fine
# if you don't type what it wants
# it keeps asking the question again
while True:
user_input = input("Enter 'test': ")
if user_input.lower() == "test":
print("\nCorrect input!")
break
else:
print ("\nInvalid input!")
"Solution" 1b (problem):
while True:
user_input = input("Enter 'test': ")
# With '"test" or "t"', it allows ANY input;
# it does not give an error and just prints
# 'Correct!'.
if user_input.lower() == "test" or "t":
print("\nCorrect input!")
break
else:
print ("\nInvalid input!")
"Solution" 2:
# "ch" means "choice".
# (naming scheme for less space)
ch_1 = input("\nGo north or south? ")
if ch_1.lower() in ["north", "n"]:
print("\nYou went north!")
elif ch_1.lower() in ["south", "s"]:
print("\nYou went south!")
# if this 'else' prints it ends the program instead of re-asking
# the question of 'which way to go?'
else:
print("I don't know what that means.")
EDIT: Nothing I've read on this site has actually helped me concerning this problem, not even the "duplicate" of this one (which I read before posting this).
My problem:
When I use the "while True" loop, my code becomes incredibly restrictive.
Every single choice using this method needs to be wrapped in an "while True" statement and it limits my options severely. It works perfectly if I only have one choice/path in that block BUT as soon as I add another choice/path, the new path experiences the same exact problem that I made this post for to begin with.
If there's some way to just always spit out a predefined message saying "ERROR! Check for misspellings!" or whatever every time the user does not put in what I want them to then that would be fantastic. (The "duplicate" of this post had something like this (I think) but it didn't work. /shrug)
But in the meantime I just cannot figure this out. Maybe I should just go back to the basics for a while.
In solution 2 only the loop is missing:
while True:
# name your variables correctly and no comment is needed.
choice = input("\nGo north or south? ")
if choice.lower() in ["north", "n"]:
print("\nYou went north!")
break
elif choice.lower() in ["south", "s"]:
print("\nYou went south!")
break
else:
print("I don't know what that means.")
You can write a function to reuse the loop:
def ask(question, answers):
while True:
choice = input(question).lower()
if choice in answers:
break
print("I don't know what that means.")
return choice
choice = ask("\nGo north or south? ", ["north", "n", "south", "s"])
if choice[0] == "n":
print("\nYou went north!")
else: # the only other choice is "south"
print("\nYou went south!")

Python Else won't work with Modules imported?

I've been testing stuff with modules specifically time module,
and I tried doing "Else", but I just get a syntax error over the "Else", I've looked over the internet a lot, and on here, and I can't find anything, so I decided to ask Myself, I'm probably going to sound like the stupidest person on earth because of this.
Here's my code,
import time
input ("Hello, would you like to sleep?")
if input == "Yes":
time.sleep(0.5)
print("Sleeping.")
print("Sleeping..")
print("Sleeping...")
print("You have awoken!")
else:
print("Alright.")
Your program should be like,
import time
inputString = input("Hello, would you like to sleep?")
if inputString.lower() == "yes":
time.sleep(0.5)
print("Sleeping.")
print("Sleeping..")
print("Sleeping...")
print("You have awoken!")
else:
print("Alright.")
input is a keyword in python, you can use that to refer something else, but it is highly discouraged. Also, input() returns string in python 3.x and eval(input()) in python 2.x
You know, indentation is very important in Python.
You may need to review your indentation for this. Remember, Python uses whitespace to denote code blocks. It may be that the editor has mangled your code, but it should look like:
import time
inputString = input("Hello, would you like to sleep?")
if input == "Yes":
print("Sleeping.")
print("Sleeping..")
print("Sleeping...")
time.sleep(0.5)
print("You have awoken!")
else:
print("Alright.")
Note that the if and the else are at the same level of indentation, and everything inside of there block is indented one level.

Run statement in terminal if user enters a certain key otherwise continue with raw_input in python

I would like to be able to have the terminal ask questions to the user but I also want the user to be able to enter an alternate character which would be able to print something out and I was wondering how to do this throughout several user inputs. Thanks this is a chunk of my code.
user_choice = []
if user_choice == "b":
print "we have: strawberry, chocolate, vanilla, and mint."
else:
# run the code like normal
user_choice.append( raw_input("would you like some ice cream?: "))
if user_choice[-1] =="yes":
print "Here you go."
user_choice.append( raw_input("would you like some cake?: "))
if user_choice[-1] =="yes":
print "Ooh it looks like we just ran out of cake."
Personally, I would make a function that computes your responses based on the current question and the user input. You can also have a separate function which handles the convoluted process of asking questions so you don't need to repeat your code much. It makes it easy to extend your code this way.
import sys
def getResponse(question, userInput):
# User giving input that doesn't answer the question, but still
# invokes an appropriate response
if userInput == 'b':
return ("We have: strawberry, chocolate, vanilla, and mint.", False)
# Finally, if the user gives input that answers your question
# default case for unhandled input is included
else:
return {
("would you like some ice cream?: ", "yes") :
("Here you go.", True),
("would you like some cake?: ", "yes") :
("Ooh it looks like we just ran out of cake.", True)
}.setdefault((question, userInput), ("", False))
def askQuestion(question):
sys.stdout.write(question)
answered = False
while not answered:
response, answered = getResponse(question, raw_input())
if response: print response
# Ask questions
askQuestion("would you like some ice cream?: ")
askQuestion("would you like some cake?: ")
The functionality you ask for can be easily handled through the use of flow control based on conditionals. Notice how I only used an if statement and a while loop to find the solution. I also used an anonymous dictionary, but this is not necessary, another if statement could have easily done the trick. if statements and while loops are examples of flow control.
You can find more information on flow control in Chapter 3 of the Python tutorial.

Categories