Why doesn't my else statement run? [python] [duplicate] - python

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 3 years ago.
cont = "y"
while cont == "y":
day = input("Enter today's day: ")
if day == "monday" or "Monday":
day = day.upper()
if day in my_class:
print ("You have ",my_class[day], " today")
elif day == "tuesday" or "Tuesday":
day = day.upper()
if day in my_class:
print ("You have ",my_class[day], " today")
elif day == "wednesday" or "Wednesday":
day = day.upper()
if day in my_class:
print ("You have ",my_class[day], " today")
elif day == "thursday" or "Thursday":
day = day.upper()
if day in my_class:
print ("You have ",my_class[day], " today")
elif day == "friday" or "Friday":
day = day.upper()
if day in my_class:
print ("You have ",my_class[day], " today")
else:
print ("Enter a valid day")
cont = input("Type y to continue: ")
I want it to print what the else says if an invalid date is put in but it skips over to printing "Type y to continue: "

The problem is with your use of the or operator:
if day == "monday" or "Monday":
Is translated as "is day == "monday" truthy, or is "Monday" truthy?" Since "Monday" is always truthy (since it is a non-empty string), you will always get this if block. Your ifs and elifs should look more like:
if day == "monday" or day == "Monday":
One way to shorten it would be:
if day in ["monday","Monday"]:
However, a cleaner way to do this same check would be:
if day.lower() == "monday":
This will make your check case insensitive. The rest of your elif statements should do the same.

Related

Different output on Leap Year

I am confused here that two codes are showing different outputs.
Can anyone help me to figure out that what's wrong with 1st code...
First Code:
It's is showing the wrong output
print("Welcome to Leap Year Finder!")
year = int(input("Write a year to check..\n"))
div4by = year % 4
div100by = year % 100
div400by = year % 400
if(div4by == 0 and div100by == 0 and div400by == 0):
print(f"Year {year} {div4by} {div100by} {div400by} is Leap Year!")
else:
print(f"Year {year} {div4by} {div100by} {div400by} is Not Leap Year!")
Second Code:
It's working fine.
if div4by == 0:
if div100by == 0:
if div400by == 0:
print("Leap year.")
else:
print("Not leap year.")
else:
print("Leap year.")
else:
print("Not leap year.")
The correct condition is
if div400by == 0 or div100by != 0 and div4by == 0:

The output is different from the output. What am I doing wrong?

I'm new to python programming. This is my assignment for my first final sem. If the user enter their facility as "1" then user as "Yes". The system should show the price accordingly. This is my code but, when my input is "2" and "yes" or any number with "yes", it's always showing the output for facility == 4.I don't know what I'm doing wrong here. It's really hard to find the mistake in this huge codes. Is there anyways to shorten this. If yes, do help me out.
if facility == 1 and user == "Yes" or user == "YES" or user == "yes":
if day == "Monday" or day == "MONDAY" or day == "monday":
price = 100
elif day == "Tuesday" or day == "TUESDAY" or day == "tuesday":
price = 100
elif day == "Wednesday" or day == "WEDNESDAY" or day == "wednesday":
price = 100
elif day == "Thursday" or day == "THURSDAY" or day == "thursday":
price = 100
elif day == "Friday" or day == "FRIDAY" or day == "friday":
price = 100
elif day == " Saturday" or day == "SATURDAY" or day == "saturday":
price = 150
elif day == "Sunday" or day == "SUNDAY" or day == "sunday":
price = 150
if facility == 2 and user == "Yes" or user == "YES" or user == "yes":
if day == "Monday" or day == "MONDAY" or day == "monday":
price = 100
elif day == "Tuesday" or day == "TUESDAY" or day == "tuesday":
price = 100
elif day == "Wednesday" or day == "WEDNESDAY" or day == "wednesday":
price = 100
elif day == "Thursday" or day == "THURSDAY" or day == "thursday":
price = 100
elif day == "Friday" or day == "FRIDAY" or day == "friday":
price = 100
elif day == " Saturday" or day == "SATURDAY" or day == "saturday":
price = 150
elif day == "Sunday" or day == "SUNDAY" or day == "sunday":
price = 150
if facility == 3 and user == "Yes" or user == "YES" or user == "yes":
if day == "Monday" or day == "MONDAY" or day == "monday":
price = 200
elif day == "Tuesday" or day == "TUESDAY" or day == "tuesday":
price = 200
elif day == "Wednesday" or day == "WEDNESDAY" or day == "wednesday":
price = 200
elif day == "Thursday" or day == "THURSDAY" or day == "thursday":
price = 200
elif day == "Friday" or day == "FRIDAY" or day == "friday":
price = 200
elif day == " Saturday" or day == "SATURDAY" or day == "saturday":
price = 250
elif day == "Sunday" or day == "SUNDAY" or day == "sunday":
price = 250
if facility == 4 and user == "Yes" or user == "YES" or user == "yes":
if day == "Monday" or day == "MONDAY" or day == "monday":
price = 30
elif day == "Tuesday" or day == "TUESDAY" or day == "tuesday":
price = 30
elif day == "Wednesday" or day == "WEDNESDAY" or day == "wednesday":
price = 30
elif day == "Thursday" or day == "THURSDAY" or day == "thursday":
price = 30
elif day == "Friday" or day == "FRIDAY" or day == "friday":
price = 30
elif day == " Saturday" or day == "SATURDAY" or day == "saturday":
price = 60
elif day == "Sunday" or day == "SUNDAY" or day == "sunday":
price = 60
if facility == 1 and user == "No" or user == "NO" or user == "no":
if day == "Monday" or day == "MONDAY" or day == "monday":
price = 150
elif day == "Tuesday" or day == "TUESDAY" or day == "tuesday":
price = 150
elif day == "Wednesday" or day == "WEDNESDAY" or day == "wednesday":
price = 150
elif day == "Thursday" or day == "THURSDAY" or day == "thursday":
price = 150
elif day == "Friday" or day == "FRIDAY" or day == "friday":
price = 150
elif day == " Saturday" or day == "SATURDAY" or day == "saturday":
price = 200
elif day == "Sunday" or day == "SUNDAY" or day == "sunday":
price = 200
if facility == 2 and user == "No" or user == "NO" or user == "no":
if day == "Monday" or day == "MONDAY" or day == "monday":
price = 150
elif day == "Tuesday" or day == "TUESDAY" or day == "tuesday":
price = 150
elif day == "Wednesday" or day == "WEDNESDAY" or day == "wednesday":
price = 150
elif day == "Thursday" or day == "THURSDAY" or day == "thursday":
price = 150
elif day == "Friday" or day == "FRIDAY" or day == "friday":
price = 150
elif day == " Saturday" or day == "SATURDAY" or day == "saturday":
price = 200
elif day == "Sunday" or day == "SUNDAY" or day == "sunday":
price = 200
if facility == 3 and user == "No" or user == "NO" or user == "no":
if day == "Monday" or day == "MONDAY" or day == "monday":
price = 250
elif day == "Tuesday" or day == "TUESDAY" or day == "tuesday":
price = 250
elif day == "Wednesday" or day == "WEDNESDAY" or day == "wednesday":
price = 250
elif day == "Thursday" or day == "THURSDAY" or day == "thursday":
price = 250
elif day == "Friday" or day == "FRIDAY" or day == "friday":
price = 250
elif day == " Saturday" or day == "SATURDAY" or day == "saturday":
price = 300
elif day == "Sunday" or day == "SUNDAY" or day == "sunday":
price = 300
if facility == 4 and user == "No" or user == "no" or user == "NO":
if day == "Monday" or day == "MONDAY" or day == "monday":
price = 35
elif day == "Tuesday" or day == "TUESDAY" or day == "tuesday":
price = 35
elif day == "Wednesday" or day == "WEDNESDAY" or day == "wednesday":
price = 35
elif day == "Thursday" or day == "THURSDAY" or day == "thursday":
price = 35
elif day == "Friday" or day == "FRIDAY" or day == "friday":
price = 35
elif day == " Saturday" or day == "SATURDAY" or day == "saturday":
price = 65
elif day == "Sunday" or day == "SUNDAY" or day == "sunday":
price = 65
The problem is that and takes precedence over or. An expression like:
facility == 4 and user == "No" or user == "no" or user == "NO"
is the same as:
(facility == 4 and user == "No") or (user == "no") or (user == "NO"):
To have this expression do what you want it to do, you'd want to use something more like one of the following:
facility == 4 and (user == "No" or user == "no" or user == "NO")
facility == 4 and user in ("No", "no", "NO")
facility == 4 and user.lower() == "no"
Here is how I would write this logic more compactly -- use Enums to standardize all the string values (this protects you from typos and makes it easy to validate that the input is one of the expected values), and then put all the logic into a dict instead of a bunch of if/elif. The dict can be made more compact by the fact that you don't have individual prices for each day, simply different weekday/weekend prices:
from enum import Enum
class User(Enum):
YES = "yes"
NO = "no"
class Day(Enum):
MONDAY = "monday"
TUESDAY = "tuesday"
WEDNESDAY = "wednesday"
THURSDAY = "thursday"
FRIDAY = "friday"
SATURDAY = "saturday"
SUNDAY = "sunday"
def is_weekend(self) -> bool:
return self in (Day.SATURDAY, Day.SUNDAY)
# Prices are keyed on facility number(int), User, and Day.is_weekend().
prices = {
1: {User.YES: {False: 100, True: 150}, User.NO: {False: 150, True: 200}},
2: {User.YES: {False: 100, True: 150}, User.NO: {False: 150, True: 200}},
3: {User.YES: {False: 200, True: 250}, User.NO: {False: 250, True: 300}},
4: {User.YES: {False: 30, True: 60}, User.NO: {False: 35, True: 65}},
}
price = prices[facility][User(user.lower())][Day(day.lower()).is_weekend()]
The problem is that your if statement logic is not correct. When you do the following check:
if facility == 4 and user == "Yes" or user == "YES" or user == "yes":
This is functionally equivalent to:
if (facility == 4 and user == "Yes") or (user == "YES") or (user == "yes"):
Meaning, if the user chose a variation of "Yes", then the if statement will always be entered. Your logic should look like this instead:
if facility == 4 and (user == "Yes" or user == "YES" or user == "yes"):
Which could be simplified to this, by just comparing the lowercase version of the user string:
if facility == 4 and user.lower() == "yes":
You could simplify all your logic to use lowercase, which would simplify your if statements to look like this:
if facility == 4 and user.lower() == "yes":
if day.lower() == "monday":
price = 30
elif day.lower() == "tuesday":
price = 30
elif day.lower() == "wednesday":
price = 30
elif day.lower() == "thursday":
price = 30
elif day.lower() == "friday":
price = 30
elif day.lower() == "saturday":
price = 60
elif day.lower() == "sunday":
price = 60
Try using if/elif instead of if/if.
Also, put brackets around the if logic, like so:
if facility == 4 and (user == "Yes" or user == "YES" or user == "yes":)
To shorten this code you can use .lower() which turns a String into lowercase.
user = user.lower()
day = day.lower()
This will allow you to just check whether day == "monday" instead of looking through different capitalizations of Monday.
You could also do
if day in ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]
This will remove most of your elif statements and just put them all in one.

How to stop an endless loop? [duplicate]

This question already has answers here:
how to stop a for loop
(9 answers)
Closed 6 years ago.
I am making a script game and use this code for multiple choice.
while True:
d1a = input ("Do you want to: A) Befriend Fred. B) Be mean to Fred. [A/B]? : ")
if d1a == "A":
print ("You befriend fred. You now have a friend..")
elif d1a == "B":
print ("You angered Fred. He kills you. RIP.")
elif d1a == "Q" :
break
After this happens,If you type A or B it will print the desired text and then ask you again "Do you want to befriend fred?" etc.
You can simply add break statements to each conditional:
while True:
d1a = input ("Do you want to: A) Befriend Fred. B) Be mean to Fred. [A/B]? : ")
if d1a == "A":
print ("You befriend fred. You now have a friend..")
break
elif d1a == "B":
print ("You angered Fred. He kills you. RIP.")
break
elif d1a == "Q" :
break
Also if you want to leave the loop after one iteration the loop isn't necessary. However, I assume you're looping until you get the correct input, in which case it might be nice to tell your player that the input was incorrect:
while True:
d1a = input ("Do you want to: A) Befriend Fred. B) Be mean to Fred. [A/B]? : ")
if d1a == "A":
print ("You befriend fred. You now have a friend..")
break
elif d1a == "B":
print ("You angered Fred. He kills you. RIP.")
break
else:
print("Incorrect input")

Give a quiz 2 right answers

For the month of February I am trying to make it so it has 3 correct answers for the number of days in the month 28,29 29 28 but it doesn't seem to be working when I try to change
user = int(input(""))
if month == "January":
answer = 31
elif month == "Feburary":
answer = 28
to
user = int(input(""))
if month == "January":
answer = 31
elif month == "Feburary (use comma to seperate two numbers)":
answer = 28,29 or 28 or 29
I realise that there is a problem with using integer in the input but I am not sure how to fix that with the comma and it won't let me put a space in between the 28 and 29 .
This is the rest of the code:
import random
import shelve
from tkinter import *
result = []
highscore = []
root = Tk()
highscore = 0
correct = 0
d = shelve.open('highscore.txt')
d['highscore'] = highscore
d.close()
name = input("What is your name: ")
print ("Hello there",name,"!")
for count in range(12):
month = random.choice(["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"])
while month in result:
month = random.choice(["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"])
result.append(month)
print ("How many Days in?", month)
user = int(input(""))
if month == "January":
answer = 31
elif month == "February":
answer = 28,29 or 29 or 28
elif month == "March":
answer = 31
elif month == "April":
answer = 30
elif month == "May":
answer = 31
elif month == "June":
answer = 30
elif month == "July":
answer = 31
elif month == "August":
answer = 31
elif month == "September":
answer = 30
elif month == "October":
answer = 31
elif month == "November":
answer = 30
elif month == "December":
answer = 31
if user == answer:
print("Correct!")
correct = correct + 1
else:
print ("Wrong, the correct answer was", answer)
if correct > highscore:
highscore = correct
print (name,", You Beat The Highscore and got",highscore,"Out Of 12")
photo = PhotoImage(file='/Users/HoneyCentaur/Desktop/Approval.gif')
photo_label = Label(image=photo)
photo_label.grid()
photo_label.image = photo
text = Label(text=" ")
text.grid()
root.deiconify()
root.mainloop()
else:
print (name, ", You Got", correct, "Out Of 12")
d = shelve.open('highscore.txt')
d['highscore'] = highscore
d.close()
You will likely want to use a list to check if the user answer was in the list of possible answers for the number of days in a month. you can then use the in keyword in python check if user is in the possible answers list.
The code would look a bit like the following:
if month == "Janurary":
answer=[31]
elif month == "Feburary":
answer=[28,29]
if user in answer:
print("Correct!")
correct = correct + 1
EDIT #1
Keep in mind there are many other options for going at this. To have a single element in a list kind of defeats the purpose and hinders understandability.
A better option might be to just cast the users answer from 28 to 29 or vice-a-versa if you're just using it to count points:
if month == "Janurary":
answer=31
elif month == "Feburary":
if(user == 28):
user = 29
answer=29
if user in answer:
print("Correct!")
correct = correct + 1
I believe "or" is only used for boolean or comparison operations.
i.e.
if month == "Janurary" or month == "Feburary":
do_something
if the quiz is looking for the possible "last days" of a month, I'm assuming the function would want a list of options.
if month == "Janurary":
answer=[31]
elif month == "Feburary":
answer=[28,29]

Calendar program help (string variables)

I recently signed up on this site because I am really stuck on the assignment in which I am required to create a program where the user inputs a month and the program displays how many days there are in that month. The user must also input the year so the program can check if it is a leap year in case the user inputs the month of february.
This is the coding I've come up with so far:
def get_year():
year = raw_input("Please enter the year: ")
return year
def get_month():
month = raw_input("Please enter the month: ")
return month
def leap_year(year):
if year % 4 == 0:
return true
else:
return false
def get_days(month):
if month == "january":
print "31 days"
elif month == "february" and leap_year == true:
print "29 days"
else:
print "28 days"
if month == "march":
print "31 days"
elif month == "april":
print "30 days"
elif month == "may":
print "31 days"
elif month == "june":
print "30 days"
elif month == "july":
print "31 days"
elif month == "august":
print "31 days"
elif month == "september":
print "30 days"
elif month == "october":
print "31 days"
elif month == "november":
print "30 days"
elif month == "december":
print "31 days"
else:
print
def main():
user_year = get_year()
user_month = get_month()
leap_year(user_year)
get_days(user_month)
main()
Anyways it's clear that there is an error in my get_days function its just I'm not sure
how to write the code so that the program knows that the user inputs a month such as
january or march. I'm guessing that the input has to be a variable and that since each
month is a string, a variable string is needed. But I could be completely wrong about this.
I'm very new to python (exactly 2 weeks now of off and on programming for school work) so I'm not too sure on many of the specifics of python programming so if anybody could assist me in the proper direction, it would be much appreciated!
You were kinda close. I made some changes which I commented. And as Raymond Hettinger points out, your get_days(month) is completely broken.
def get_year():
year = raw_input("Please enter the year: ")
return int(year) #otherwise it is a string!
def get_month():
month = raw_input("Please enter the month: ")
return month
def leap_year(year):
if year % 4 == 0:
return True
else:
return False
def get_days(month,leap_year): #leap_year must be passes to this function
#This checks for "january" and "february" with leap years
#and falls back to last option on EVERYTHING ELSE like a feb without a leap year or even a "march"
if month == "january":
print "31 days"
elif month == "february" and leap_year == True:
print "29 days"
else:
print "28 days"
#this is a separate block that runs AFTER the previous block
if month == "march":
print "31 days"
elif month == "april":
print "30 days"
elif month == "may":
print "31 days"
elif month == "june":
print "30 days"
elif month == "july":
print "31 days"
elif month == "august":
print "31 days"
elif month == "september":
print "30 days"
elif month == "october":
print "31 days"
elif month == "november":
print "30 days"
elif month == "december":
print "31 days"
else:
print "invalid input" #so that it doesnt fail silently when I enter 2
def main():
user_year = get_year()
user_month = get_month()
leap_status = leap_year(user_year) #store the leap_year status to a variable
get_days(user_month, leap_status) #and then pass it to a function
main()
The if-elif was being broken in February. The minor change is to continue with an uninterrupted pattern of if-elif logic:
def get_days(month):
if month == "january":
print "31 days"
elif month == "february" and leap_year:
print "29 days"
elif month == "february" and not leap_year:
print "28 days"
elif month == "march":
print "31 days"
elif month == "april":
print "30 days"
elif month == "may":
print "31 days"
elif month == "june":
print "30 days"
elif month == "july":
print "31 days"
elif month == "august":
print "31 days"
elif month == "september":
print "30 days"
elif month == "october":
print "31 days"
elif month == "november":
print "30 days"
elif month == "december":
print "31 days"
else:
print 'unknown month'
I would suggest you to using dictionary which a build-in data type in python.
def get_days(year, month):
"""
take year and month ,return the days in that month.
"""
#define a dictionary and the month is key which value is days
daydict = dict()
daydict = ['january'=31, 'february'=28, 'februaryinleapyear'=29,
'march'=31, 'april'=30,
'may'=31, 'june'=30,
'july'=31, 'august'=31,
'september'=30, 'october'=31,
'november'=30, 'december'=31 ]
try:
if month in daydict:
if month == 'february' and leap_year(year):
print daydict[februaryinleapyear]
else:
print daydict[month]
else:
print 'The year or month you input is invalid !'
except:
print 'error!'
n=int(input('enter no of days in a month= '))
#0=sunday
#1=moday
#2=tuesday
#3=wednesday
#4=thursday
#5=friday
#6=saturday
d=int(input('enter the starting day of month= '))
print('sun','mon','tue','wed','thu','fri','sat',sep='\t')
for j in range(d):
print (' ',end='\t')
i=1
while(i<=n):
print (i,end='\t')
if(i+d)%7==0:
print('\t')
i=i+1
This code ask for user inputs( more simple codes)
#python calendar days in month.
month= input ("Enter the month('January', ...,'December'): ") # ask for inputs from user
start=input ("Enter the start day ('Monday', ..., 'Sunday'): ")
if start== "Monday" :
num=1
elif start== "Tuesday" :
num=0
elif start== "Wednesday" :
num=-1
elif start== "Thursday" :
num=-2
elif start== "Friday" :
num=-3
elif start== "Sartday" :
num=-4
elif start=="Sunday":
num=-5
print(month)
print("Mo Tu We Th Fr Sa Su") #the header of the Calender
if month== "January" or month=="March" or month=="May" or month=="July" or month=="August" or month=="October" or month=="December" :
#for month with 31 days
for num_ in range (num,num+41,7):
for i in range(7):
if num<1:
print (' ',end="")
elif num>31:
print("",end="")
else:
print ("{0:>2}".format(num),end="")
if i<6 and num<31:
print(" ",end="")
num +=1
print()
elif month== "April" or month=="June" or month=="Septemmber" or month=="November":
#for month with 30 days
for num_ in range (num,num+41,7):
for i in range(7):
if num<1:
print (' ',end="")
elif num>30:
print("",end="")
else:
print ("{0:>2}".format(num),end="")
if i<6 and num<30:
print(" ",end="")
num +=1
print()
elif month== "February" :
# february is an exception : it has 28 days
for num_ in range (num,num+41,7):
for i in range(7):
if num<1:
print (' ',end="")
elif num>28:
print("",end="")
else:
print ("{0:>2}".format(num),end="")
if i<6 and num<28:
print(" ",end="")
num +=1
print()
else:
print("invalid entry")

Categories

Resources