python code running else statement even after if statement is true - python

I am learning python programming and was going through If Else conditions. Even if the If statement is true, my code executes else condition.
Please check the code below:
age = int(input("Enter your Age (in years)"))
sex = input("Enter you Sex(M/F)")
if(sex == 'M'):
if(age < 20):
print("You are just a teen.")
if(age >= 20 and age < 25):
print("You are a young man now.")
elif(age >=25 and age < 30):
print("You are a mature man now")
else:
print("You are getting old")
if(sex == 'F'):
if(age < 20):
print("You are just a teen.")
if(age >= 20 and age < 25):
print("You are a young woman now.")
elif(age >=25 and age < 30):
print("You are a lady now")
Over here, if i enter the age as 2 and sex as M, the code goes in first condition and prints the message
"You are just a team"
Along with it, the code also run the else condition and prints
You are getting old
I don't understand this behaviour. I checked for indentation and all indentations are correct.

You accidentally made it a double if which would cause both statements to execute.
age = int(input("Enter your Age (in years)"))
sex = input("Enter you Sex(M/F)")
if(sex == 'M'):
if(age < 20):
print("You are just a teen.")
elif(age >= 20 and age < 25): # notice now it is one if-elif block
print("You are a young man now.")
elif(age >=25 and age < 30):
print("You are a mature man now")
else:
print("You are getting old")
if(sex == 'F'):
if(age < 20):
print("You are just a teen.")
elif(age >= 20 and age < 25): # same here
print("You are a young woman now.")
elif(age >=25 and age < 30):
print("You are a lady now")

Switch
if(age < 20):
print("You are just a teen.")
if(age >= 20 and age < 25):
print("You are a young man now.")
with
if(age < 20):
print("You are just a teen.")
elif(age >= 20 and age < 25):
print("You are a young man now.")
What's happening is that your second if statement inside of if sex == 'M' isn't getting fulfilled because the age is not between 20 and 25. Since the elif isn't fulfilled either, whats inside the else block runs.

In the code snippet you've given, the else is connected to the second if statement: if(age >= 20 and age < 25):. The first "if" executes fine, but then when the second "if" fails it executes the "else". This can be fixed by changing the second "if" to an "elif":
if(sex == 'M'):
if(age < 20):
print("You are just a teen.")
elif(age >= 20 and age < 25):
print("You are a young man now.")
elif(age >=25 and age < 30):
print("You are a mature man now")
else:
print("You are getting old")

It is printing correct output. First, it is checking that age is less than 20 years, which is correct, it then print "You are just a teen.".
if(sex == 'M'):
if(age < 20):
print("You are just a teen.")
After that it checks second 'if' statement, then 'elif' and then it goes to 'else' and print that statement as there was no match previously.
if(age >= 20 and age < 25):
print("You are a young man now.")
elif(age >=25 and age < 30):
print("You are a mature man now")
else:
print("You are getting old")
You may have made a typo here:
if(age >= 20 and age < 25):
print("You are a young man now.")
Possibly, you are trying to use 'if' instead of 'elif' here.

Related

Rollercoaster Project

I am supposed to filter the ages of the users through the following rule: if users >=120 cm then print("You can ride the rollercoaster!"), if users <=119 cm then print ("Sorry, you must grow taller, see you next time.")
Everything is going ok with the code when users are <=119, output:
> Welcome to the rollercoaster! Enter your height in cm, please: 52
> Sorry, you must grow taller, see you next time.
But when users are >=120, this happens:
> Welcome to the rollercoaster! Enter your height in cm, please: 178 You
> can ride the rollercoaster! Enter your age, please: 80 You are more
> than 70 years old, you won a free ride, enjoy.!
> Sorry, you must grow taller, see you next time.
As you can see, the last output line it should not be happening.
Is there some way to break the if statement? I've tried the break function and I got a:
SyntaxError: 'break' outside loop
This is the whole code:
print("Welcome to the rollercoaster!")
height = int(input("Enter your height in cm, please: "))
if height >= 120:
print("You can ride the rollercoaster!")
age = int(input("Enter your age, please: "))
if age < 12:
print ("Please pay $5. Enjoy!")
elif age <= 18:
print("Please pay $7. Enjoy!")
elif age >= 18 and age <= 44:
print("Please pay $12. Enjoy!")
elif age >= 45 and age <=55:
print ("Everything is going to be ok. Have a free ride on us!")
elif age <= 69:
print ("Please pay $9. Enjoy!")
else:
print (f"You are more than 70 years old, you won a free ride, enjoy.!")
if height >= 300:
print ("For security reasons, you are reasigned to the next rollercoaster.")
age = int(input("Enter your age, please: "))
if age < 12:
print ("Please pay $5. Enjoy!")
elif age <= 18:
print("Please pay $7. Enjoy!")
elif age >= 18 and age <= 44:
print("Please pay $12. Enjoy!")
elif age >= 45 and age <=55:
print ("Everything is going to be ok. Have a free ride on us!")
elif age <= 69:
print ("Please pay $9. Enjoy!")
else:
print (f"You are more than 70 years old, you won a free ride, enjoy.!")
else:
print ("Sorry, you must grow taller, see you next time.")
You missed an elif statement in the main condition.
Try this:
print("Welcome to the rollercoaster!")
height = int(input("Enter your height in cm, please: "))
if height >= 120 and height <300:
print("You can ride the rollercoaster!")
age = int(input("Enter your age, please: "))
if age < 12:
print ("Please pay $5. Enjoy!")
elif age <= 18:
print("Please pay $7. Enjoy!")
elif age >= 18 and age <= 44:
print("Please pay $12. Enjoy!")
elif age >= 45 and age <=55:
print ("Everything is going to be ok. Have a free ride on us!")
elif age <= 69:
print ("Please pay $9. Enjoy!")
else:
print (f"You are more than 70 years old, you won a free ride, enjoy.!")
elif height >= 300:
print ("For security reasons, you are reasigned to the next rollercoaster.")
age = int(input("Enter your age, please: "))
if age < 12:
print ("Please pay $5. Enjoy!")
elif age <= 18:
print("Please pay $7. Enjoy!")
elif age >= 18 and age <= 44:
print("Please pay $12. Enjoy!")
elif age >= 45 and age <=55:
print ("Everything is going to be ok. Have a free ride on us!")
elif age <= 69:
print ("Please pay $9. Enjoy!")
else:
print (f"You are more than 70 years old, you won a free ride, enjoy.!")
else:
print ("Sorry, you must grow taller, see you next time.")
See the difference?

Can I change the value of a boolean when my while loop hits a certain condition to activate a second "outcome"? - Python beginner

I almost feel bad for asking a question already, given that I barely started my Python adventure.
However I can't seem to figure out the issue.
My code, me playing around with while, conditions, self assignment, etc., looks like this atm:
age = 14
drivers_license = False
while age <= 17 and drivers_license == drivers_license:
print(f"You are {age} years old, so you are still too young to drive!")
age += 1
if age == 18:
print(f"Now that you are {age}, you can get your drivers license!")
drivers_license = True
elif age >= 18 and drivers_license == True:
print("You are allowed to drive now!")
'''
As you can see, I am trying to change drivers_license from False to True after the age reaches 18 and enable the last print.
I don't get errors but when I run the code I don't get the "You are allowed to drive now!" printed to the console.
'''
You can write your code like this to find your solution!
age = 14
drivers_license = False
while age <= 18:
if age == 18:
print(f"Now that you are {age}, you can get your drivers license!")
drivers_license = True
else:
print(f"You are {age} years old, so you are still too young to drive!")
if drivers_license == True:
print("You are allowed to drive now!")
age += 1
age = 14
while age <= 17:
print(f"You are {age} years old, so you are still too young to drive!")
age += 1
if age == 18:
print(f"Now that you are 18, you can get your drivers license!")
print("You are allowed to drive now!")
break #ends the while loop
Anything else is useless.
Notice this:
if drivers_license == drivers_license: #Always True
and this...
if drivers_license == True: # is equivalent to...
if drivers_license:
...and this:
if drivers_license == False: # is equivalent to...
if not drivers_license:

How do I ask for an input from a user and check that value within a range to give me the correct response

So my professor for python assigned an exercise which was to create a program to accept a user input or "score" and create an if else loop with an if else nested loop inside the first loop to check if the score is greater than or equal to 80. If that's satisfied, print a statement saying "you passed." and if the score is equal to 90 or more, then it should say"you got an A." and if the score is below an 80, it should say "you failed."
so far, this is the code I was able to come up with. And it runs up until the score entered is anything equal to or more than 90.
userScore = int(input('enter score:\n'))
if userScore < 80:
userScore = int(input('you failed. Try again:\n'))
if userScore == 80 or userScore > 80:
print(f'good job, you got a B.')
elif userScore >= 90:
print('you got an A')
else:
print('enter a differnt score')
as per your question your code should be :
score = int(input("Please enter your score: "))
if score >= 80:
print("You passed.")
if score >= 90:
print("You got an A.")
else:
print("You failed.")
while(1):
score = int(input("Please enter your score: "))
if score >= 80:
print("You passed.")
if score >= 90:
print("You got an A.")
break
else:
print("You failed.")
while(1):
score = int(input("Please enter your score pal: "))
if score >= 80:
print("You passed the exam.")
if score >= 90:
print("You got an A in the exam.")
break
else:
print("You failed the exam.")

Beginner question regarding if-elif-if-if chain

Very recently started to learn Python (2 weeks ago) and have been enjoying working through the Python Crash Course book. I've written some code for an exercise in the book. The code works as I expected it to but I don't quite understand why.
Exercise: Write a program for a cinema that asks the user for inputs of their age and then tells them what price their ticket will be, using a while loop.
Here is the code I first wrote:
print("Welcome to Cathrine's Cinema!\n")
no_tickets = 0
total_cost = 0
while True:
if no_tickets == 0:
ticket = input("Would you like to buy a ticket? (Yes/No) ")
if ticket.lower() == 'yes':
no_tickets += 1
age = input("Great! How old is the person that this ticket is "
"for? ")
age = int(age)
if age < 3:
print("The ticket is free, enjoy!")
continue
elif age <= 12:
print("That'll be £10 please.")
total_cost += 10
continue
elif age > 12:
print("That'll be £15 please.")
total_cost += 15
continue
elif ticket.lower() == 'no':
print("Ok, thanks for coming by!")
break
else:
print("Please answer 'Yes' or 'No'")
continue
if no_tickets > 0:
ticket = input("Would you like to buy another ticket? (Yes/No) ")
if ticket.lower() == 'yes':
no_tickets += 1
age = input("Great! How old is the person that this ticket is "
"for? ")
age = int(age)
if age < 3:
print("The ticket is free, enjoy!")
continue
elif age <= 12:
print("That'll be £10 please.")
total_cost += 10
continue
elif age > 12:
print("That'll be £15 please.")
total_cost += 15
continue
elif ticket.lower() == 'no':
print(f"Cool, you have purchased {no_tickets} tickets for a total"
f" cost of £{total_cost}.")
break
else:
print("Please answer 'Yes' or 'No'")
continue
I thought it was quite awkward having two big almost identical if statements just so the initial message (Would you like to buy a/another ...) and the goodbye message was right, so I wrote it again a bit differently.
print("Welcome to Cathrine's Cinema!\n")
no_tickets = 0
total_cost = 0
while True:
if no_tickets == 0:
message = "Would you like to buy a ticket? (Yes/No) "
bye_message = "Ok, thanks for coming by."
elif no_tickets > 0:
message = "Would you like to buy another ticket? (Yes/No) "
bye_message = (f"Cool, you have purchased {no_tickets} tickets for a "
f"total cost of £{total_cost}.")
ticket = input(message)
if ticket.lower() == 'yes':
no_tickets += 1
age = input("Great! How old is the person that this ticket is "
"for? ")
age = int(age)
if age < 3:
print("The ticket is free, enjoy!")
continue
elif age <= 12:
print("That'll be £10 please.")
total_cost += 10
continue
elif age > 12:
print("That'll be £15 please.")
total_cost += 15
continue
elif ticket.lower() == 'no':
print(bye_message)
break
else:
print("Please answer 'Yes' or 'No'")
continue
Now this seems to work exactly the same as the previous program, but I'm confused about the if-elif chain. I thought that python executes only one block in an if-elif chain. So if the customer orders 1 ticket, then no_tickets > 0 and so we enter the second elif statement. Why then don't we go back to the start of the while loop and loop infinitely? Why instead do we continue to the other if statements below (testing if ticket.lower() == 'yes' or 'no')?
Thanks for reading all of this! Sorry if this seems like a pointless question as my code is working as intended, I just want to properly understand everything that's going on.
This has to do with indentation. Languages like java enclose if/else statements in parenthesis {}, but python depends on indentation.
Notice that the testing if ticket.lower() == 'yes' or 'no' has the same indentation as if no_tickets == 0: and if no_tickets > 0: therefore it is considered to be outside of the first if/else block.
This might be helpful: https://www.w3schools.in/python-tutorial/concept-of-indentation-in-python/
if your if statement condition is fulfilled, say age<3 is true then statement for that condition are processed/executed and then your program will not see anything in if..elif..else code block, it will go for the next code block(part of code after if..elif..else statement).
why we continue to other if statement, because in your code there are two code section for if statement and they processed one by one unless no break/exit statement didn't occur which cause them to go out of the while loop or exit the program

How to fix my if, elif, else statement in python?

I am working on an omegle simulator for fun, where it asks your age and if you're old enough asks you if you have kik. It works fine if your age is 16 or more but if you say any less than that, it comes up with an error. This is the code:
age = input("age?\n")
if age == "1":
print ("Too young bby")
elif age == "2":
print ("Too young bby")
elif age == "3":
print ("Too young bby")
elif age == "4":
print ("Too young bby")
elif age == "5":
print ("Too young bby")
elif age == "6":
print ("Too young bby")
elif age == "7":
print ("Too young bby")
elif age == "8":
print ("Too young bby")
elif age == "9":
print ("Too young bby")
elif age == "10":
print ("Too young bby")
elif age == "11":
print ("Too young bby")
elif age == "12":
print ("Too young bby")
elif age == "13":
print ("Too young bby")
elif age == "14":
print ("Too young bby")
elif age == "15":
print ("Too young bby")
else:
kik = input("Do you have kik?\n")
yes = "yes"
if kik == yes:
print ("add me bby")
else:
print ("bye")
The error that comes up is:
Traceback (most recent call last):
File "C:/Users/Public/Documents/python/omegle.py", line 36, in <module>
if kik == yes:
NameError: name 'kik' is not defined
Does anyone know how to fix it?
The problem is that you only set kik in this block:
else:
kik = input("Do you have kik?\n")
If this block isn't reached, kik doesn't exist. An option is to set it before your if/elif blocks.
Additionally, you can make this much shorter:
kik = "no"
age = input("age?\n")
if int(age) < 16:
print ("Too young bby")
else:
kik = input("Do you have kik?\n")
yes = "yes"
if kik == yes:
print ("add me bby")
else:
print ("bye")
There are a couple of things you should fix here. FIrst, store the age as a number using int():
age = int(input("age?\n"))
And then do a less than:
if(age < 16):
print ("Too young bby")
else:
kik = input("Do you have kik?\n")
if kik == "yes":
print ("add me bby")
else:
print ("bye")
Set kik to the default it should be outside your chain.
age = input("age?\n")
kik = "no" #assuming no is default
...
As it is in your code, it will only be defined if you hit else
The short answer is that kik is out of scope, and putting kik = "no" at the beginning of your program should get rid of that error.
But, here's a better way to do the whole thing:
age = int(input("age?\n"))
kik = "no"
if age < 16:
print ("Too young bby")
else:
kik = input("Do you have kik?\n")
if kik == yes:
print ("add me bby")
else:
print ("bye")
Andy's post was very helpful to me. There is one thing I would add. If you enter an integer less than 16 to the first question, you get both print ("Too young bby") and print ("bye"). The first output only is sufficient for my use, not print ("bye").
To achieve this you indent the second 'if' statement to the first 'else' statement.
If you do not indent my code, you get "You are not eligible to vote in Ireland." twice. Here is my example;
Citizen = "No"
Yes = "Yes"
Age = int(input("What is your age?: \n"))
if (Age) < 18:
print("You are not eligible to vote in Ireland.\n")
else:
Citizen = input("Do you hold Irish Citizenship? Yes/No: \n")
if Citizen == Yes:
print("You are eligible to vote in Ireland.\n")
else:
print("You are not eligible to vote in Ireland.\n")

Categories