So, instead of Python basically following the cascading script as it usually does is it possible where it will never end unless you type "end" and you can ask it any question over & over again?
I'm basically creating a bot where you basically activate it by typing 'Cofo, activate' and it will reply 'Cofo activated, how may I help you today?' and from there you can ask it things like 'What's the weather today' and 'what's 9 + 4' etc, etc. A little like Jarvis but without actual speech, more text based.
Sorry I haven't given a very good explanation, I can't really explain what I want but hopefully you understand.
the way to do this with a while loop:
while True:
user_data = raw_input('What do you want? ')
if user_data == 'quit': break
else:
print 'I can\'t do "{}" yet.'.format(user_data)
All this script does is echo back your input, so ignore the details - the main thing is that the loop runs until the user enters 'quit' (or whatever word you want to specify).
As noted by #cricket_007, you need a while loop. Check the tutorial for a simple introduction and the docs for a formal syntax definition.
Asking indefinitely for user input is a common pattern, be sure to check out this canonical question about a related issue: asking for user input until a valid response is provided.
Related
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.
I am learning Python online on YouTube. And I have came across a piece of code that is confusing me. I would really appreciate if someone could help me out. Here is the code:
command = ""
started = False
while True:
command = input("> ").lower()
if command == "start":
if started:
print("car already started")
else:
started = True
print("car started")
What I didn't understand is how does Python execute double ifs? And how does it know it is already executed once and if typed start again it would give me another message. Any help would highly appreciated.
The ifs are nested. The second if and else are only checked if the first condition is true. This is apparent, since they are indented after the first if.
The first if checks if the command is to start. If it is, then it checks if the car has already been started. If it has, there is no need to start it again. If not, then it starts the car.
Here's an attempt to "transcribe" the code in English:
car has not started, no command received yet
start an infinite loop (meaning that the steps below will repeat forever, until you terminate/exit the program)
take a command from the user, turn it into lowercase, and store it
check the command entered by the user. If the command is "start", then check whether the car has started, and start it if it hasn't been already, then go back to step 3. If the user input is not "start", then don't check anything and return directly to step 3.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I tried to run this Python program that I found it in this website but when I run it nothing happens, how can I run this code? Do I need to add anything to the code? I am using this website to run it repl.it: Thank you very much.
................
#! /usr/bin/env python3
# The following is a database of problems, keywords, and solutions.
PROBLEMS = (('My phone does not turn on.',
{'power', 'turn', 'on', 'off'},
('Smack it with a hammer.',
'Wrap your phone in duck tape.',
'Throw it into the ocean.')),
('My phone is freezing.',
{'freeze', 'freezing'},
('Dowse it in a petroleum-based product.',
'Light a match or find a suitable flame source.',
'Barbecue your phone until it is well done.')),
('The screen is cracked.',
{'cracked', 'crack', 'broke', 'broken', 'screen'},
('Find some super glue.',
'Spread the super glue over the screen of the phone.',
'Either sit on the phone or place a 100 pounds over it.')),
('I dropped my phone in water.',
{'water', 'drop', 'dropped'},
('Blow dry your phone with air below zero degrees Celsius.',
'Bake it in your oven at three hundred degrees Celsius.',
'Leave your phone on your roof for one week.')))
# These are possible answers accepted for yes/no style questions.
POSITIVE = tuple(map(str.casefold, ('yes', 'true', '1')))
NEGATIVE = tuple(map(str.casefold, ('no', 'false', '0')))
def main():
"""Find out what problem is being experienced and provide a solution."""
description = input('Please describe the problem with your phone: ')
words = {''.join(filter(str.isalpha, word))
for word in description.lower().split()}
for problem, keywords, steps in PROBLEMS:
if words & keywords:
print('This may be what you are experiencing:')
print(problem)
if get_response('Does this match your problem? '):
print('Please follow these steps to fix your phone:')
for number, step in enumerate(steps, 1):
print('{}. {}'.format(number, step))
print('After this, your phone should work.')
print('If it does not, please take it to a professional.')
break
else:
print('Sorry, but I cannot help you.')
def get_response(query):
"""Ask the user yes/no style questions and return the results."""
while True:
answer = input(query).casefold()
if answer:
if any(option.startswith(answer) for option in POSITIVE):
return True
if any(option.startswith(answer) for option in NEGATIVE):
return False
print('Please provide a positive or negative answer.')
if __name__ == '__main__':
main()
On that site repl.it, before the final if I added print(__name__) and got output builtins. So we see that when running on repl.it, the program fails the very important condition that __name__ == 'main'.
You can revise the program to make it work on repl.it just by replacing those final two lines of the program with just this call to function main:
main()
If you are running that script on that website you need to call the main function yourself. In the right column please type:
main()
That you make the main function execute. This was compiled into byte code and on that site you basically started the interpreter and imported the script but you still need need to call the function.
If you are in a computer that has a python interpreter installed you can actually type python name_of_file.py and that will run the script by executing the last if statement there.
After you do what Aaron Mansheim says, you will need to provide some input.
Click on 'input' at the upper right of the screen, then key in one of the alternatives mentioned in the script such as,
My phone does not turn on.
yes
then click on 'Set input'. Then run the code again.
And incidentally, this is perhaps one of the slowest ways I can imagine to learn how to work with Python code. You should install Python on your machine and use it in that form. My two cents.
I'm currently in the process of trying to add a while loop to my code that is shown below. The theory behind what I'm attempting to do is as follows:
As you can see at the very bottom of my code, I confirm the user's reservation and ask if he/she would like to create another. If the user enters 'yes", I would like the program to re-run. If no, then the program should terminate. I'm aware the best way to accomplish this is using a while loop, but I'm having a little difficulty executing this as my textbook is a little confusing on the subject.
I know it's supposed to look something like this (or something along the lines of it):
while True:
expression
break
Though I can't seem to get it to compile. Any suggestions? Below is my code:
user_continue = str(raw_input("Your reservation was submitted successfully. Would you like to do another?"))
if user_continue != 'yes':
print('Thank you for flying with Ramirez Airlines!')
Here's a simple example that shows how to use a while loop:
import time
while True:
print time.ctime()
print 'Doing stuff...'
response = raw_input('Would you like to do another? ')
if response != 'yes':
break
print 'Terminating'
Note that the code inside the while loop must be indented, unlike the code in your first code block. Indentation is very important in Python. Please always ensure that code in your questions (and answers) here is properly indented.
FWIW, the raw_input() input function returns a string, so str(raw_input()) is unnecessary clutter.
The end of your code should look something like:
user_continue = raw_input("Your reservation was submitted successfully. Would you like to do another?")
if user_continue != 'yes':
break
print('Thank you for flying with Ramirez Airlines!')
...
Your print statements are a bit funny. Since you're using Python 2.7 you don't need to do
print ('The total amount for your seats is: $'),user_people * 5180
you can just do
print 'The total amount for your seats is: $', user_people * 5180
or if you wish to use Python 3 style, put everything you're printing inside the parentheses, like this:
print ('The total amount for your seats is: $', user_people * 5180)
However, the output will look a bit messy since there will be a space between the $ and the amount. Please read the python docs to learn how to fix that.
...
Also, you have import time inside your loop. Don't do that. Generally, import statements should be at the top of your script before any other executable code.
Sorry for the non descriptive question I had no idea how to word it.
I'm trying to write a program (GUI) where I ask the users questions and then in return they answer and see if they are correct however when I enter the correct answer it's still showing as being incorrect.
My code looks something like this.
prompt for question 1
txtQuestion = Text(Point(5,8), "Question 1")
txtQuestion.setTextColor("red")
txtQuestion.setSize(16)
txtQuestion.setStyle("bold")
txtQuestion.draw(win)
txtAnswer = Text(Point(1.5,4), "Answer 1: ")
txtAnswer.setTextColor(color_rgb(255,127,80))
txtAnswer.setSize(14)
txtAnswer.setStyle("bold")
txtAnswer.draw(win)
txtAnswer2 = Text(Point(1.5,3), "Answer 2: ")
txtAnswer2.setTextColor(color_rgb(255,127,80))
txtAnswer2.setSize(14)
txtAnswer2.setStyle("bold")
txtAnswer2.draw(win)
txtAnswer3 = Text(Point(1.5,2), "Answer 3: ")
txtAnswer3.setTextColor(color_rgb(255,127,80))
txtAnswer3.setSize(14)
txtAnswer3.setStyle("bold")
txtAnswer3.draw(win)
txtAnswer4 = Text(Point(1.5,1), "Answer 4: ")
txtAnswer4.setTextColor(color_rgb(255,127,80))
txtAnswer4.setSize(14)
txtAnswer4.setStyle("bold")
txtAnswer4.draw(win)
txtEnterAn = Text(Point(8,3), "Enter your answer below: ")
txtEnterAn.setTextColor("black")
txtEnterAn.draw(win)
entAnswer = Entry(Point(8,2), 3)
entAnswer.draw(win)
Answer1 = entAnswer.getText()
win.getMouse()
#loop for answer
if Answer1 == "A":
txtCorrect = Text(Point(5,9), "Correct!")
txtCorrect.setTextColor("black")
txtCorrect.draw(win)
else:
txtCorrect = Text(Point(5,9), "Inorrect!")
txtCorrect.setTextColor("black")
txtCorrect.draw(win)
Now I'm not sure why every time I enter "A" it still shows as incorrect I know in another program I had to float the entAnswer variable but I figured this time I wouldn't have to since it's a string.
I must be overlooking the situation but I can't lay my finger down on it, any help would be appreciated, thanks!
p.s. I didn't put it in with the code but I do have the variables up top initialized such as Answer1 = " " and so forth
The problem here seems to be that you're misunderstanding how GUIs work. It's not like the sequential print/read code that most programming instruction starts with. The GUI widgets only create themselves, draw to the screen and wait for events.
This line:
Answer1 = entAnswer.getText()
will end up setting Answer1 to an empty string, because at that point, the user hasn't entered anything in the text box. Instead, you have to create a callback function that will be called by the GUI when the user hits a button to score the answer. Then in that function you will be able to read the user's answer and mark it correct or incorrect.
I recommend going through your GUI library's tutorial again to get a feel for the event-driven style of GUI programming.
I'd recommend that you abstract that user interface detail away from the problem of showing questions, obtaining answers, and determining correctness. You can sort all of that out with nothing more than a command line, text based user interface. Once you have that, then you can proceed with the user interface design with confidence, knowing that the logic behind the questionnaire is sound.
This idea goes by several names: layering, MVC, etc. I'd recommend it for this problem, because it'll help you learn the idea for those more difficult problems to come where it'll be indispensable.
i don't see a reason the logic would fail, but are you sure you are pressing "A" and not "a" .
I can't say anything about this particular problem, but I would do a
print "'" + answer + "'"
print answer.__class__
I have encountered wrapper classes (in OTHER situations) which behave like strings
but are not actually strings. Furthermore spaces and newlines can be added everywhere :)