This part of my code is giving me problems with the raw_input. The thing is, the terminal does not detect any problems and the program runs, however it never asks the user for input, the program just prints what it has to print at the beginning and then exits for some odd reasons, everything inside the while is not executed. Thanks in advance.
Heres the code:
options_secondscenario = ['Whats going on out there?', 'So what now?']
def second_scenario():
print "Conversation 1"
print "Conversation 2"
print "Conversation 3"
print options_secondscenario
option = options_secondscenario[1]
while next == option:
choice_secondscenario = raw_input("> ")
if next == 'Whats going on out there?':
print "Conversation 4"
elif next == 'So what now':
third_scenario()
else:
dead()
second_scenario()
next == option is never true, because next is a built-in function and is never equal to a string. In fact, this would actually be an error in Python 3. So your while loop is never entered.
Related
I am working on ROS and I have written a code in Python 2.7 and in the menu I am asking the user to select either option 1 or 2. After the task is accomplished, when I press Ctrl+c, instead of exiting the code, it displays the menu again, instead of exiting. Here again if I choose between 1 or 2, it keeps printing the menu again and again.
What changes in the code would be suggested in order to exit the code as soon as I press Ctrl+c instead of displaying the menu again and again?
The code and the screen shot of the problem are below:
if __name__=='__main__':
while(True):
try:
print "***********"
print "1. Continuous"
print "2. Single Step"
print "***********"
try:
choice = int(raw_input('Choose a number between 1 & 2: '))
number = choice
move_group_python_interface()
except ValueError:
print "ERROR! Choose a number between 1 and 2"
except rospy.ROSInterruptException:
break
Without looking at move_group_python_interface() it is very difficult to say.
Examining your error screen shot (in the future, include the error text in the question), you were hitting ^C as part of the flow when move_group_python_interface() was triggered.
If move_group_python_interface() entails starting a new process, then you exited that process.
Try hitting ^C as part of the menu flow. It seems to exit fine for me.
If you are curious about how to capture ^C and respond accordingly
Check this out
if __name__=='__main__':
while(True):
try:
print "***********"
print "1. Continuous"
print "2. Single Step"
print "***********"
try:
choice = int(raw_input('Choose a number between 1 & 2: '))
number = choice
move_group_python_interface()
except ValueError:
print "ERROR! Choose a number between 1 and 2"
except KeyboardInterrupt:
print "Bye bye"
break
when executed prints
bash > python infloop.py
***********
1. Continuous
2. Single Step
***********
Choose a number between 1 & 2: ^CBye bye
(Sorry but I don't got ROS)
I found the issue. The problem was with while(True):. Once I comment it out, it exits without any problem.
The second rule for If-Statements here, which has me confused states that:
If this else should never run because it doesn't make sense, then you must use a die function in the else that prints out an error message and dies, just like we did in the last exercise. This will find many errors.
Here's the code from the last exercise:
def dead(why):
print why, "Good job!"
exit(0)
def start():
print "You are in a dark room."
print "There is a door to your right and left."
print "Which one do you take?"
choice = raw_input("> ")
if choice == ‘left’:
bear_room()
else:
dead(‘You stumble around the room until you starve.’)
Is it essentially saying that you must successfully terminate the program if a condition is not met?
Yes, the idea is:
import sys
def die(msg):
print msg
sys.exit(1)
if condition:
# do stuff
else:
die('This cannot happen!')
You could also use an assert instead, or raise an exception, or anything else that would fail catastrophically. This helps you validate at runtime that the clause you didn't expect to execute, really didn't run.
IMHO you shouldn't get too hung up on how this die is done, exactly. The important point the referred text tries to make is that when you're sure some condition is true, you might as well assert it forcefully so that you can catch runtime bugs.
The guide is trying to show you that you can see the choice that a user gives when it's something that you don't check for in your if statement. If your else looks like:
else:
dead(choice)
You will be able to see what the user input that you didn't expect.
The problem is that the syntax only allows for "Left", when the prompt allows entry of anything. In other words, if I enter "Bob", I will starve. I should be trapping for anything that isn't appropriate and "die"ing at that point (or helping the user make an appropriate decision).
This is an attempt at teaching error handling and die. You would rewrite it such that you allow accurate entry or die (no exit). If you don't choose left, there is no other choice even though the prompt states there are two choices.
If you truly expect only 'left' to be added, a better way of checking for unexpeted input would be
if choice != ‘left’:
dead(‘You stumble around the room until you starve.’)
bear_room()
That way you still validate that the input is what you expected, but it saves indentation and space for the main logic.
The purpose of this function is to check the input of the user, determine if its in the list, and, if not, tells the user to ''Select one of the given options''.
The issue with it is that it asks me for input twice. When I select option ''Approach exit door'' it loops again and asks for input, when I enter the same option again thats when I get the result (which leads to dead() function not copied here to keep this short). Tried several things, like adding a condition that closes the loop and tries to make the While False so it stops, but it didnt work. Also, thanks to user khelwood who provided me with this alternative and simplified my program.
too long didnt read? Loop asks for input twice, cant fix it.
Heres the code.
s2option_list =['Approach exit door', 'Check for vital signs']
def sget_choice(s2option_list):
while True:
print s2option_list
choice = raw_input('> ')
for i, opt in enumerate(s2option_list):
if opt in choice:
return i
else:
print "You need to select one of the given options."
def scenario2(response):
print response
print "Conversation"
print "Conversation"
print "Conversation"
sget_choice(s2option_list)
if sget_choice(s2option_list)==0:
dead("Conversation")
else:
print "Conversation"
sget_choice2(s2option_list2)
def scenario2(response):
print response
print "Conversation"
print "Conversation"
print "Conversation"
res = sget_choice(s2option_list) # call it once save return value in a variable
if res == 0: # now you are checking the value from the previous call not calling again
dead("Conversation")
else:
print "Conversation"
sget_choice2(s2option_list2)
I am creating a text-RPG taking inspiration from older text adventures where the player enters an English command; such as 'pick up sword' and the like.
I have established a simple; enter 'A' to do this and enter 'B' to do this, but I would like to expand my system for more freedom.
I need to create a system that; when the player types in a command the program picks out key words.
I assume this would be achievable via the 'in' command.
Here is my code:
print "What would you like to do??"
input_loop_sleep = str('')
choice_sleep = raw_input(str('>>>'))
loop_sleep = False
table_time = False
bed_time = False
error_time = False
while loop_sleep == False:
if str('sleep') in choice_sleep or str('bed') in choice_sleep or str('goodnight') in choice_sleep or str('Sleep') in choice_sleep or str('tired') in choice_sleep:
while bed_time == False:
print "you decide to go back to sleep"
time.sleep(1)
print "..."
time.sleep(1)
print ""
time.sleep(1)
print "darkness"
time.sleep(1)
print ""
print "you wake up..."
time.sleep(1)
print "it is now 9:15am"
time == int(9.15)
time.sleep(1)
print "You are standing in your room, slightly more refreshed."
time.sleep(1)
print "there is a table with some things on it, stairs, and a wardrobe... with the doors wide open..."
time.sleep(1)
print "that's strange... you swear that they were shut when you went to sleep..."
break
else:
bed_time == True
break
bed_loop_choice = raw_input('>>>')
elif str('bedside') in choice_sleep or str('table') in str(choice_sleep):
while table_time == False:
print "You rub your eyes and pick up some belongings from a"
print "bedside table."
time.sleep(1)
print "Map added!"
time.sleep(1)
print "100 gold added!"
time.sleep(1)
print "Leather Bag added!"
cash == int(100)
time.sleep(1)
Map == str('map of', str(province))
Inventory == [str(Map)]
container == str('leather bag')
print "your", str(container), str("contains a"), str(Map), str('and'), str(cash)
break
else:
table_time == True
break
else:
print "invalid command!"
when I run the code, no matter what I type in it always goes with the 'sleep' option.
I probably just made some simple mistake!
can you please help me with what I did wrong and how I can fix it.
To answer your question about why the sleep loop is repeated all the time:
You're controlling the loop via
while bed_time == False:
but you never set bed_time to True in your loop (only in the else clause, but that clause is only executed when the loop exits normally, not when it's exited via break, as you're now doing - therefore bed_time will never change).
Furthermore, direct comparisons to a boolean value are usually frowned upon. The idiomatic way (in most languages, not just Python) would be while not bedtime:.
You should probably read some beginners' programming books and/or the Python tutorial before embarking on such a big project. There are several issues in your code that convey the impression that you really need to get a grasp on some basic programming principles and Python idioms.
For example,
int(9.15)
is not a good way to store a time - the result will be 9.
You're then using time == int(9.15), which means "compare the module time to the integer 9". I guess you meant time = int(9.15) which is already bad for the reasons stated above, but there would be even another problem: You would be overwriting the module name time, which will cause the subsequent time.sleep(1) command to fail with an AttributeError.
There's no need for most str() calls in your code because you're using it on objects that already are strings. Where you're not, it's incorrect: str('map of', str(province)) will raise TypeError (str takes only one argument).
You're using uppercase variable names for objects that aren't class instances.
Etc., etc...
I think this should be sufficient to sort out the problem
In [1]: str('bed') in "bedside"
Out[1]: True
So when you write bedside it gets inside the sleep option if condition and hence you are getting wrong answer .
You should write :
if str('bed') == choice_sleep or *other conditions* :
then got inside the sleep option
P.S: I am assuming you have imported the time module .
P.P.S: I checked the code with entering table it is working fine .
I use the IronPython Console when I feel like programming, but it does some wacky stuff. For example:
If a=("X")
it says "Unexpected token '=.'
Or this:
If a is ("X"):
print ("Y")
else:
print ("Z")
But it should end after that, it still puts in "...". Why?
First question:
if a=("X"):
is not valid Python code. You probably meant:
if a == ("X"):
For the second one, the REPL (read-eval-print loop - the shell) doesn't know when you're going to end a block until it sees an empty line. For example:
>>> if a == "X":
... print "Y"
... else:
... print "Z"
...
You might still want to enter another statement on the next line. If you leave it blank, the REPL knows that you're done that block and want to start a new one. This is a side-effect of Python's significant whitespace.
It should be:
if x==('x'):
print('x')
This is because the = is an assignment. == is a comparison.