an if Statement inside an if Statement? - python

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."

Related

How do I clear an "if" condition

I'm trying to figure out how to clear an "if" condition and how to fix the result = print(x) part of my code. I'm trying to create a little search code based on the variable data, but I can't figure a few things out:
import time
def start():
data = ["Lucas_Miguel", "João_Batista", "Rafael_Gomes", "Bruna_Santos", "Lucas_Denilson"]
print("1" + " - Check Name")
print("2" + " - Register a New Name")
option = input("Choose an option: ")
if option == "1":
def other():
name = input("Type the first name: ")
for x in data:
if name in x:
result = print(x)
while True:
print("Yes " "or " "No")
confirm = input("Is the name you want in the options?: ")
if confirm == "Yes":
break
if confirm == "No":
print("Yes", " or", " No")
try_again = input("Do you want to write again?: ")
if try_again == "Yes":
return other()
other()
else:
print("Option not available")
time.sleep(1)
return start()
start()
The first problem is in the result = print(x) part. It works, but when the answer is more than one name, only the first one appear and I don't know how to fix it.
The second problem is in the "confirm = input" part. Basically, if the person answered with "No", when they go back, the answer will still be saved and the input will run twice, the first time with the saved answer and the second with the new answer. So I want to be able to clear that before the person answer it again.
I want to apologize already if the code is ugly or weird, but I started a few days ago, so I'm still learning the basics. Also thanks in advance for the help.
There is quite a bit here to unpack and like the comment on the question suggests you should aim to look at how to ask a more concise question.
I have some suggestions to improve your code:
Split the other into its own function
Try to use more accurate variable names
As much as you can - avoid having multiple for loops happening at the same time
Have a look at list comprehension it would help a lot in this case
Think about whether a variable really belongs in a function or not like data
What you're asking for is not immediately clear but this code should do what you want - and implements the improvements as suggested above
import time
data = ["Lucas_Miguel", "João_Batista", "Rafael_Gomes", "Bruna_Santos", "Lucas_Denilson"]
def other():
name_input = input("Type the first name: ")
matches = [name for name in data if name_input in name]
if len(matches) == 0:
print ("No matches")
for name in matches:
print(name)
while True:
print("Yes " "or " "No")
confirm = input("Is the name you want in the options?: ")
if confirm == "Yes":
break
if confirm == "No":
print("Yes", " or", " No")
try_again = input("Do you want to write again?: ")
if try_again == "Yes":
return other()
else:
return
def start():
print("1" + " - Check Name")
print("2" + " - Register a New Name")
option = input("Choose an option: ")
if option == "1":
other()
else:
print("Option not available")
time.sleep(1)
return start()
start()
The first problem will be solved when you remove 8 spaces before while True:.
The second problem will be solved when you add return (without arguments) one line below return other() at the indentation level of if try_again == "Yes":
Everybody can see that you are just learning Python. You don't have to apologize if you think, your code is "ugly or weird". We all started with such small exercises.

Why is this if-else statement not working?

So, if the person answers "nutella", it prints "That's correct!" How do I get it to say "You're wrong!" if they answer anything else.
nutella = input
input("What's the best food in the world?")
if nutella:
print("That's correct!")
else:
print("You're wrong!")
Firstly, it seems you should look into if statements since you don't know how to use them yet, but this is how you do it, I'll try to explain as well
choice = input("What's the best food in the world?")
if choice == "Nutella":
print("That's correct!")
else:
print("You're wrong!")
So the first line assigns what the person types to the variable choice and then in the next line it checks if the value of the variable equals/is "nutella", if it is it will print "That's correct!", if it isn't it will print "You're wrong!".
The if statement in Python for a string is true whenever the string isn't empty. What you want is to compare the nutella variable with the expected string. Such as:
nutella = input("What's the best food in the world?")
if nutella == "nutella":
print("That's correct!")
else:
print("You're wrong!")

New Programmer, How do you use If and Elif and Else statements? Its giving me NameError: name 'No' is not defined

answer = input('Hi! Would you like to say something? (No or Yes)')
if answer == No or no:
print('Okay then, have a good day!')
elif answer == Yes or yes:
answertwo = input('What would you like to say?')
print(answertwo, 'Hmmmmmm, Intresting.')
**if answer == No or no:
NameError: name 'No' is not defined**
I would suggest you using .lower() for every input. This ensures that if some types "nO" or "YeS" it takes the lowercase equivalent. Example:
ui = input("Type \"Hi\"").lower()
Next, you should really add an else option to your code. This is for answers you don't want them to type. This should be held in a while loop Example:
while(True):
ui = input("Type \"Hi\"").title()
if(ui == "Hi"):
print("Hello")
break
else:
print("That isn't a choice!")

How can I restart my python 3 script?

I am making a program on python 3. I have a place that I need the script to restart. How can I do this.
#where i want to restart it
name= input("What do you want the main character to be called?")
gender = input("Are they a boy or girl?")
if gender == "boy":
print("Lets get on with the story.")
elif gender == "girl":
print("lets get on with the story.")
else:
print("Sorry. You cant have that. Type boy or girl.")
#restart the code from start
print("Press any key to exit")
input()
It's a general question about programming an not specific to Python ... by the way you can shorten your code with the two conditions on boy and girl...
while True:
name= input("What do you want the main character to be called?")
gender = input("Are they a boy or girl?")
if gender == "boy" or gender == "girl":
print("Lets get on with the story.")
break
print("Sorry. You cant have that. Type boy or girl.")
print("Press any key to exit")
input()
Simple but bad solution but you get the idea. I am sure, you can do better.
while True:
name= input("What do you want the main character to be called?")
gender = input("Are they a boy or girl?")
if gender == "boy":
print("Lets get on with the story.")
elif gender == "girl":
print("lets get on with the story.")
else:
print("Sorry. You cant have that. Type boy or girl.")
#restart the code from start
restart = input("Would you like to restart the application?")
if restart != "Y":
print("Press any key to exit")
input()
break
Don't have the program exit after evaluating input from the user; instead, do this in a loop. For example, a simple example that doesn't even use a function:
phrase = "hello, world"
while (input("Guess the phrase: ") != phrase):
print("Incorrect.") //Evaluate the input here
print("Correct") // If the user is successful
This outputs the following, with my user input shown as well:
Guess the phrase: a guess
Incorrect.
Guess the phrase: another guess
Incorrect.
Guess the phrase: hello, world
Correct
or you can have two separate function written over, It's same as above(only it's written as two separate function ) :
def game(phrase_to_guess):
return input("Guess the phrase: ") == phrase_to_guess
def main():
phrase = "hello, world"
while (not(game(phrase))):
print("Incorrect.")
print("Correct")
main()
Hope this is what you are looking for .

Never ending While

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.

Categories