Never ending While - python

In this code I try to call a function. On the other hand its not working the way I want it to work, for it is staying in the loop even though I am changing the loops condition options_secondscenario[0] from 0 to 1 at the end of the Loop. What I want this to do is to move to third_scenario() function. Thanks in advance.
options_secondscenario = ['Whats going on out there?', 'So what now?']
def third_scenario():
print "This is the third scenario"
choiceselection2 = raw_input("> ")
if choiceselection2 == 1:
print "stay"
else:
print "leave"
def dead():
print "You are dead"
exit()
def second_scenario():
print "Conversation 1"
print "Conversation 2"
print "Conversation 3"
print options_secondscenario
choices = options_secondscenario[0]
while choices == options_secondscenario[0]:
choiceselection = raw_input("> ")
if choiceselection == 'Whats going on out there?':
print "Conversation 4"
elif choiceselection == 'Whats up':
print "Nothing"
elif choiceselection == 'what is that':
print "I dont know"
elif choiceselection == 'is':
dead()
else:
third_scenario()
choices == options_secondscenario[1]
second_scenario()

You are trying to change your choices var AFTER the loop (check your indentation). So the while loop never gets a chance to reach this statement.
Also, you are using the compare operator == instead of the assignment operator = like so:
choices = options_secondscenario[1]
That line should be somewhere INSIDE your while loop. Check your indentation.

Related

Stuck at 36th exercise of Learn Python the Hard Way [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 5 years ago.
This is the code I have written for Learn Python the Hard Way exercise 36. But I am not able to run the code in the door_1 function. If I choose 3 as an option and then left or right anything which is then stored in dir, the output is "lion ate you", no matter what I type.
from sys import exit #importing module from lib
def Tadaa():
print "This is a place where you will get a surprise"
next = int(raw_input("Enter any number from 1-10 :"))
if next <= 10:
if next % 2 == 0 :
print "You will be buying me a shake :)."
else :
print "You will be getting a shake by me."
else :
print "Do it correctly."
def door_1():
print "There are 3 doors . Choose any door from the the remaining three doors"
print "Lets hope for the best "
next = raw_input("Enter your option :")
if next == "1":
print "abc "
elif next == "2":
print "abc"
elif next == "3":
print "You have entered 3rd door ."
print "Here are 2 doors one on left and one on right."
dir = raw_input("Choose which door do you wnat to enter :")
if dir == "left" or "Left":
print "Lion ate you . You are dead ."
elif dir == "right" or "Right" :
print "You will be getting a surprise"
Tadaa()
else :
print "abc"
else :
print "abc"
def door_2():
print "There are two doors A and B which will decide your fate"
next = raw_input("Enter the door ")
if next == "A" or "a":
door_1()
elif next == "B" or "b":
print "You are back from where you have started"
start()
else :
print "I got no idea what that means."
exit(0)
def start():
print "You are in dark room"
print "There is a door to your right and left ."
print "Which one do you take"
next = raw_input("> ")
if next == "Right" or "right":
door_2()
elif next == "Left" or "left":
door_1()
else :
print "abc"
start()
The problem is your statement:
if dir=="left" or "Left":
What you want is
if dir=="left" or dir=="Left":
In effect, what just doing or "Left" is doing, is checking whether a string that you've just created exists or not. Put another way, its similar to:
x='Left'
if x:
X does exist, so if X is True.
The crux here is to always evaluate statements in quantum, and when you're using and in conjunction with or statements, make sure you use brackets to be explicit. if statement_one or statement_two.

an if Statement inside an if Statement?

FarmGround=input("Do you want to pat the animal? ") #this is the input
if FarmGround==("Yes") or FarmGround==("yes"): #this is if
print("You patted the animal") #print statement if you patted the animal it will go onto the next if statement
if print=("You patted the animal"):
elif FarmGround==("No") or FarmGround==("no"): #this is elif
print("You didn't patt the animal and it is triggered")
undescribed image
Your code is quite clear. What I understand is you want to ask another question if animal is patted.
FarmGround=input("Do you want to pat the animal? ") #this is the input
if FarmGround=="Yes" or FarmGround=="yes": #this is if
print("You patted the animal")
holy_field = input("Did you clear the field?")
if holy_field.lower() == "yes":
print("Do something else. Don't look at me.")
else:
print("When are you going to do it ?")
elif FarmGround== "No" or FarmGround== "no": #this is elif
print("You didn't patt the animal and it is triggered")
You can indent additional statements, including if statements inside your existing if block, just like you're indented the first print statement. It's not clear from your question what exactly you want to do, so I'll fill in some pseudo-code (which you can replace with whatever you actually want):
FarmGround=input("Do you want to pat the animal? ")
if FarmGround==("Yes") or FarmGround==("yes"):
print("You patted the animal")
some_other_answer = input("Some other question?") # here's more code inside the first if
if some_other_answer == "Foo": # it can include another if statement, if you want it to
print("Foo!")
elif FarmGround==("No") or FarmGround==("no"):
print("You didn't patt the animal and it is triggered")
Indentation matters in python. To nest an if statement in another if statement, just indent it below the first with 4 spaces.
If ( var1 == 1 ):
If ( var2 == 2 ):
print "Both statements are true."

Program Returning nothing

I saw this Flowchart and decided to make a program out of it. The problem is, it only returns "Go Outside" if I enter "no" the first time. All others return "None". Im using Python 2.7
def waitawhile():
print "Wait a while"
rain2 = raw_input("Is it still raining?")
if rain2.lower() == "no":
return "Go Outside"
elif rain2.lower() == "yes":
waitawhile()
def Raining():
print "Is it raining?"
rain = raw_input()
if rain.lower() == "no":
return "Go Outside"
elif rain.lower() == "yes":
print "Have Umbrella?"
umbrella = raw_input()
if umbrella.lower == "yes":
return "Go Outside"
elif umbrella.lower() == "no":
waitawhile()
print Raining()
The problem is with your calls to waitawhile (from both Raining and from waitawhile itself). After calling it, you're discarding the return value and returning nothing. To fix it, change the calls from:
waitawhile()
to:
return waitawhile()
Make sure that, for both functions, there is no way to reach the end of the function without executing a return statement.
Your program have three problem, in the following they are fixed:
def waitawhile():
print "Wait a while"
rain2 = raw_input("Is it still raining?")
if rain2.lower() == "no":
return "Go Outside"
elif rain2.lower() == "yes":
return waitawhile()
def Raining():
print "Is it raining?"
rain = raw_input()
if rain.lower() == "no":
return "Go Outside"
elif rain.lower() == "yes":
print "Have Umbrella?"
umbrella = raw_input()
if umbrella.lower() == "yes":
return "Go Outside"
elif umbrella.lower() == "no":
return waitawhile()
print Raining()
Works as below:
>>> ================================ RESTART ================================
>>>
Is it raining?
yes
Have Umbrella?
yes
Go Outside
>>> ================================ RESTART ================================
>>>
Is it raining?
yes
Have Umbrella?
no
Wait a while
Is it still raining?yes
Wait a while
Is it still raining?no
Go Outside
>>>
The problems in your program are logical error, so the interpreter will not show you a syntax error:
You used .lower instead of .lower() in the if condition, and it will be always false.
You ignored returns of waitawhile() method while you must return them to print method.

Code is looped again and again

I have the following code:
def begin_game():
print "You landed on planet and see three rooms."
door = int(raw_input("Pick number of door>>>"))
print "You approach and see that you need to enter password..."
password = raw_input("Enter your surname>>>")
if door == 1:
medical_room()
if door == 2:
library()
if door == 3:
basement()
else:
print "No room exists"
begin_game()
begin_game()
When I enter door number, I get medical_room function done but then else statement is executed and code starts again over and over.
My question is why else statement is executed? Shouldn't it stop on if statement, execute inside block and stop?
You need to use elif for the second and third if statements. else only considers the statement immediately before it.
Or since it seems that you're looking for switch statement which does not exist in python you could do something like this:
rooms = {
1: medical_room,
2: library,
3: basement,
}
chosen_room = rooms[door]
chosen_room()
You should be using elif, or else every time you input anything other than 3, the else block will be executed, as door != 3 and the else block only considers the preceding if or elif block.
def begin_game():
print "You landed on planet and see three rooms."
door=int(raw_input("Pick number of door>>>"))
print "You approach and see that you need to enter password..."
password=raw_input("Enter your surname>>>")
if door==1:
medical_room()
elif door==2:
library()
elif door==3:
basement()
else:
print "No room exists"
begin_game()
begin_game()
Currently, your code tests the first if condition (door==1) and associated actions, then it tests the second and third if conditions. Since the third if statement is False (door==1), it will perform the else statement.
You should use elif statements instead of repeated if statements.
def begin_game():
print "You landed on planet and see three rooms."
door=int(raw_input("Pick number of door>>>"))
print "You approach and see that you need to enter password..."
password=raw_input("Enter your surname>>>")
if door==1:
medical_room()
elif door==2:
library()
elif door==3:
basement()
else:
print "No room exists"
begin_game()

How to go back to first if statement if no choices are valid

How can I have Python move to the top of an if statement if no condition is satisfied correctly.
I have a basic if/else statement like this:
print "pick a number, 1 or 2"
a = int(raw_input("> ")
if a == 1:
print "this"
if a == 2:
print "that"
else:
print "you have made an invalid choice, try again."
What I want is to prompt the user to make another choice for this if statement without them having to restart the entire program, but am very new to Python and am having trouble finding the answer online anywhere.
A fairly common way to do this is to use a while True loop that will run indefinitely, with break statements to exit the loop when the input is valid:
print "pick a number, 1 or 2"
while True:
a = int(raw_input("> ")
if a == 1:
print "this"
break
if a == 2:
print "that"
break
print "you have made an invalid choice, try again."
There is also a nice way here to restrict the number of retries, for example:
print "pick a number, 1 or 2"
for retry in range(5):
a = int(raw_input("> ")
if a == 1:
print "this"
break
if a == 2:
print "that"
break
print "you have made an invalid choice, try again."
else:
print "you keep making invalid choices, exiting."
sys.exit(1)
You can use a recursive function
def chk_number(retry)
if retry==1
print "you have made an invalid choice, try again."
a=int(raw_input("> "))
if a == 1:
return "this"
if a == 2:
return "that"
else:
return chk_number(1)
print "Pick a number, 1 or 2"
print chk_number(0)
Use a while loop.
print "pick a number, 1 or 2"
a = None
while a not in (1, 2):
a = int(raw_input("> "))
if a == 1:
print "this"
if a == 2:
print "that"
else:
print "you have made an invalid choice, try again."

Categories