Using both OR, AND in an IF-statement - Python - python

def alarm_clock(day, vacation):
if day == 0 or day == 6 and vacation != True:
return "10.00"
else:
return "off"
print(alarm_clock(0, True))
Why does this return "10.00"? In my mind it should return "off". Yes, day is equal to 0, but vacation is True, and the IF-statements first line states that it should only be executed if vacation is not True.

In Python and binds tighter than or. So your statement is equivalent to this:
if day == 0 or (day == 6 and vacation != True):
To get the correct result you must parenthesize the precedence yourself:
if (day == 0 or day == 6) and vacation != True:

What you probably want is this:
def alarm_clock(day, vacation):
if (day == 0 or day == 6) and vacation != True:
return "10.00"
else:
return "off"
print(alarm_clock(0, True))

Related

Program not working for tuesday but working for sunday

I am learning python using a book called How to think like a computer scientist. There they gave an exercise:
Write a function that helps answer questions like “‘Today is Wednesday.
I leave on holiday in 19 days time. What day will that be?”’
So the function must take a day name and a delta argument — the number of days
to add — and should return the resulting day name:
test(day_add("Monday", 4) == "Friday")
test(day_add("Tuesday", 0) == "Tuesday")
test(day_add("Tuesday", 14) == "Tuesday")
test(day_add("Sunday", 100) == "Tuesday")
Hint: use the first two functions written above to help you write this one
Can your day_add function already work with negative deltas? For example, -1 would be yesterday, or -7 would be a week ago:
test(day_add("Sunday", -1) == "Saturday")
test(day_add("Sunday", -7) == "Sunday")
test(day_add("Tuesday", -100) == "Sunday")
I have written this program
import sys
def test(did_pass):
'''prints result of test at last'''
linenum=sys._getframe(1).f_lineno #gets call line
if did_pass:
msg='Test at line {0} PASS'.format(linenum)
else:
msg=('Test at line {0} FAIL.'.format(linenum))
print(msg)
def day_name(x):
'''converts day number to day'''
if x==0:
return 'Sunday'
elif x==1:
return 'Monday'
elif x==2:
return 'Tuesday'
elif x==3:
return 'Wednesday'
elif x==4:
return 'Thursday'
elif x==5:
return 'Friday'
elif x==6:
return 'Saturday'
else:
return
def day_num(y):
'''converts day to day number'''
if y=='Sunday':
return 0
elif y=='Monday':
return 1
elif y=='Tuesday':
return 2
elif y=='Wednesday':
return 3
elif y=='Thursday':
return 4
elif y=='Friday':
return 5
elif y=='Saturday':
return 6
else:
return
def day_add(today, stay):
'''input day name and remaining days to print day name'''
result=(stay)%7
answer=(result)+(day_num(today))
return day_name(answer)
def test_suite():
test(day_add("Sunday", -1) == "Saturday")
test(day_add("Sunday", -7) == "Sunday")
test(day_add("Tuesday", -100) == "Sunday")
test_suite()
so the first function is to test my program for bugs. The problem is first two tests are clear but last test fails even if it has the same negative value as the first two. I want to know what is the mistake which makes the first two tests pass but later fail. Im beginner so kindly use some easy statements.
Your calculations are wrong. Following How to debug small programs Change your code to
def day_add(today, stay):
'''input day name and remaining days to print day name'''
result = stay % 7
answer = result + day_num(today)
print(result, day_num(today), day_name(answer)) # DEBUG your code
return day_name(answer)
Output:
6 0 Saturday
Test at line 34 PASS
0 0 Sunday
Test at line 35 PASS
5 2 None # analyze this and fix it.
Test at line 36 FAIL.

How do I solve the leap year function in Python for Hackerrank?

I cannot for the life of me solve this challenge on Hackerrank. The closest I got it was to 4/6 passes.
Rules:
In the Gregorian calendar three criteria must be taken into account to identify leap years:
The year can be evenly divided by 4, is a leap year, unless:
The year can be evenly divided by 100, it is NOT a leap year, unless:
The year is also evenly divisible by 400. Then it is a leap year.
Code:
def is_leap(year):
leap = False
# Write your logic here
if year%400==0 :
leap = True
elif year%4 == 0 and year%100 != 0:
leap = True
return leap
year = int(input())
print(is_leap(year))
You forgot the ==0 or !=0 which will help understand the conditions better. You don't have to use them, but then it can cause confusion maintaining the code.
def is_leap(year):
leap = False
if (year % 4 == 0) and (year % 100 != 0):
# Note that in your code the condition will be true if it is not..
leap = True
elif (year % 100 == 0) and (year % 400 != 0):
leap = False
elif (year % 400 == 0):
# For some reason here you had False twice
leap = True
else:
leap = False
return leap
a shorter version would be:
def is_leap(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
You can try this
def is_leap():
leap = False
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
leap = True
return leap
This code might be easy for some of the people to wrap their head around
def is_leap(year):
leap = False
# Write your logic here
if year%4==0:
leap=True
if year%100==0:
leap=False
if year%400==0:
leap=True
return leap
year = int(input())
print(is_leap(year))
If we split the question point by point.
Actual question:
The year can be evenly divided by 4, is a leap year, unless:
The year can be evenly divided by 100, it is NOT a leap year, unless:
The year is also evenly divisible by 400. Then it is a leap year.
Explaining it : If a year is divided by 4, then its a leap year.
If this is divided by 100 but not 400 after being divisible by 4,
then its not a leap year.
If this is divisible by 4, 100 ,400 , then its a leap year.
Basically, nested if
if(year % 4 == 0):
if(year % 100 == 0):
if(year % 400 == 0):
leap =True
else:
leap=False
else:
leap=True
else:
leap=False
return leap
def is_leap(year):
leap=False
check =lambda year : year :year%4==0 and (year%400==0 or year%100!=0)
leap=check(year)
return leap
year =int(input())
print(is_leap(year))
def is_leap(year):
leap = False
if year%4 == 0:
if(year%100 != 0 or year%400 == 0):
leap = True
return leap
def is_leap(year):
leap = False
# Write your logic here
if year % 4 == 0 and year % 100 != 0:
leap = True
elif year % 100 == 0 and year % 400 != 0:
leap = False
elif year % 400 == 0:
leap = True
elif year % 4 != 0:
leap = False
return leap
year = int(raw_input())
print is_leap(year)
def is_leap(year):
leap = False
if(year%4==0):
#century year check
if(year%100==0):
#century leap year check
if(year%400==0):
leap=True
else:
leap=True
return leap
if year%4==0 and year%100==0 and year%400==0:
return True
elif year%4==0 and year%100!=0 and year%400!=0:
return True
else:
return False
n = [int(input("Enter a year in four digit: "))]
a = list(map(lambda x: "is a Leap year" if x%4 == 0 or ( x % 100 != 0 or x % 400 == 0) else "is not a Leap year" , n))
print(f"{n[0]} {a[0]}")
def is_leap(year):
leap = False
if year % 4 == 0 and year % 100 != 0:
leap = True
elif year % 400 == 0 and year % 100 == 0:
leap = True
return leap
I just try with this:
def is_leap(year):
leap = False
# Write your logic here
if (year%4 ==0 and year%100 !=0) or year%400 ==0:
leap = True
else:
leap = False
return leap
year = int(input())
print(is_leap(year))
if year can be evenly divided by 4 and 400 is True but if it can be evenly divided by 100 is False
#simplest solution for beginner
n = int(input('Enter year to check if it is leap year.'))
if n % 4 == 0 and n%100 != 0:
leap = 'True'
elif n % 100 == 0 and n%400==0:
leap = 'True'
else:
leap = 'False'
print('the entered year is,'+leap)
This would be my solution for the problem. We want the number to be divisible with 4 no matter what. So year % 4 will need to be true for the output to be bool True as well. Then we have to consider if the number which is divisible with 4 can be divided to 400. If the number is divisible to 100 but not 400 it should give us bool False. That is why we should check divisibility to 400 and non-divisibility to 100 together and use or statement.
def is_leap(year):
leap = False
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
return not leap
else:
return leap
year = int(input())
print(is_leap(year))
def is_leap(year):
leap = False
# Write your logic here
if (year%4 ==0):
if (year%100 == 0) and (year%400 ==0):
leap = True
elif(year%100 == 0) and (year%400 !=0):
leap = False
else:
leap = True
else:
leap = False
return leap
year = int(input())
HackerRank Problem - An extra day is added to the calendar almost every four years as February 29, and the day is called a leap day. It corrects the calendar for the fact that our planet takes approximately 365.25 days to orbit the sun. A leap year contains a leap day.
In the Gregorian calendar, three conditions are used to identify leap years:
The year can be evenly divided by 4, is a leap year, unless:
The year can be evenly divided by 100, it is NOT a leap year, unless:
The year is also evenly divisible by 400. Then it is a leap years.
Solution is the below Python Code.
def is_leap(year):
leap = False
# Write your logic here
if (year % 4 == 0) and (year % 100 != 0):
# Note that in your code the condition will be true if it is not..
leap = True
elif (year % 100 == 0) and (year % 400 != 0):
leap = False
elif (year % 400 == 0):
# For some reason here you had False twice
leap = True
else:
leap = False
return leap
year = int(input())
print(is_leap(year))
Try this #Charles Thompson, this passed all test cases for me.
def is_leap(year):
leap = False
if year%4 == 0:
if year%100 == 0:
if year%400 == 0:
leap = True
else:
leap = False
else:
leap = True
return leap
def is_leap(year):
leap = False
if year % 4 == 0 and year % 100 == 0 and year % 400 == 0:
return True
elif year %4 == 0 and year % 100! = 0 and year % 400!= 0:
return True
else:
return False
year = int(raw_input())
print is_leap(year)
def is_leap(year):
leap = False
# Write your logic here
if year%4==0:
leap= True
if year%100 ==0 and year%400==0:
leap = True
if (year%100 == 0) and (year%400 != 0):
leap = False
return leap
year = int(input())
print(is_leap(year))
def is_leap(year):
leap = False
d4 = year%4
d100 = year%100
d400 = year%400
if d4 == 0 :
if d100 != 0 or d400 == 0 :
leap = True
else :
leap = False
return leap
year = int(input())
print(is_leap(year))

Why doesn't Python read my boolean Vacation?

I was trying this excercise on Codebat:
Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and a boolean indicating if we are on vacation, return a string of the form "7:00" indicating when the alarm clock should ring. On weekdays, the alarm should be "7:00" and on the weekend it should be "10:00". Unless we are on vacation -- then on weekdays it should be "10:00" and weekends it should be "off".
def alarm_clock(day, vacation):
vacation_weekday = vacation and day in range(1,6)
vacation_weekend = day == 0 and day == 6 and vacation
if day in range(1,6):
return "7:00"
elif day == 0 or day == 6:
return "10:00"
elif vacation_weekday:
return "10:00"
elif vacation_weekend:
return "off"
If i run print(alarm_clock(1,True)) it returns "7:00" instead of "10:00". Can somebody help me ?
Your first if statement checks if day in range(1, 6). If day is 1 that will always be true. Since the first condition matched, none of the elif conditions are even executed. (Additionally, since you return immediately, no other code in the function is executed after that point either.)
You probably want to rearrange the if statements so that you check the special cases first, and then the general cases. Alternatively, precompute a weekend and/or weekday boolean value and then express all the conditions explicitly:
def alarm_clock(day, vacation):
weekday = 1 <= day <= 5
weekend = not weekday
if weekend and vacation:
return "off"
if weekend and not vacation:
return "10:00"
if weekday and vacation:
return "10:00"
if weekday and not vacation:
return "7:00"
Or even, using a ternary expression:
def alarm_clock(day, vacation):
weekday = 1 <= day <= 5
if vacation:
return "10:00" if weekday else "off"
return "7:00" if weekday else "10:00"
Here is how you should have rewritten your code to evaluate it properly:
def alarm_clock(day, vacation):
weekday_alarm_clock = "7:00 AM"
weekend_alarm_clock = "10:00 AM"
if vacation:
weekday_alarm_clock = "10:00 AM"
weekend_alarm_clock = "off"
if day > 0 and day < 6:
return weekday_alarm_clock
else:
return weekend_alarm_clock
As you can see here, if we are on vacation then we set out weekday alarm clock to 10:00. and turn off the weekend clock. it is not Sunday or Saturday and vacation is not true then we return our normal clock. Else its the weekend and its not vacation and we return our normal weekend alarm clock
Now the output I receive when using print(alarm_clock(1,True))is 10:00 AM as expected
My approach would be a little complex:
def alarm_clock(day, vacation):
weekend = [6,7]
if day not in weekend and vacation is True:
return '10:00 AM'
elif day in weekend and vacation is True:
return 'off'
elif day in weekend and vacation is False:
return '10:00 AM'
elif day not in weekend and vacation is False:
return '7:00 AM'
else:
return 'off'
print(alarm_clock(day, vacation))

Python Program Doesn't Execute Any Functions

I'm currently learning python for fun. I'm used to coding in C++ and so far it's fairly easy to pickup. I wrote my first program on my own, but for some reason, it doesn't do anything and the functions I wrote won't execute. If I write print statements outside the functions, the statements execute, but it never goes inside the function. Here is my code. Any tips would be much appreciated.
racks = 1000000
sum = 0
def ConsecutivePrime():
primeNum = 0
stack = []
while(StackAdder == False):
primeNum = isPrime(primeNum)
stack.append(primeNum)
StackAdder(stack)
if(StackAdder == True):
print ("Largets Prime: ", sum)
def StackAdder(stack):
for n in stack:
sum += n
if(count < racks):
return False
else:
stack.pop()
return True
def isPrime(primeNum):
isPrime = False
while(isPrime == False):
primeNum += 1
if(primeNum % 2 == 1): #First Checks If Odd
if(primeNum % 3 == 0):
isPrime == False
elif(primeNum % 5 == 0):
isPrime == False
elif(primeNum % 7 == 0):
isPrime == False
elif(primeNum % 9 == 0):
isPrime == False
else:
isPrime == True
if(isPrime == True):
return primeNum
def main():
ConsecutivePrime()
if __name__ == "__main__":
main()
StackAdder is a function; it is neither True nor False, so ConsecutivePrime is called, it just doesn't do anything.
Add these lines at the beginning of your ConsecutivePrime() function, and observe the output:
print(StackAdder == True)
print(StackAdder == False)
You can see False printed twice, right? Surprised? Read the comments on the answer by Scott Hunter. May be that will help a little.
So, your conditionals for both while and if are False.
If what you wanted was to check what value StackAdder() returned, you need to do it like this:
def ConsecutivePrime():
primeNum = 0
stack = []
while(StackAdder(myStack) == False): # define myStack to your needs
primeNum = isPrime(primeNum)
stack.append(primeNum)
StackAdder(stack)
if(StackAdder(myStack) == True):
print ("Largets Prime: ", sum)
There are major problems in the way you structured your code, and I will try to point out the most obvious mistakes in your functions:
1) Regarding the function isPrime(primeNum), this is the correct way of writing it:
def isPrime(primeNum):
isPrime = False
while not isPrime:
primeNum += 1
if(primeNum % 2 == 1): #First Checks If Odd
if(primeNum % 3 == 0):
isPrime == False
elif(primeNum % 5 == 0):
isPrime == False
elif(primeNum % 7 == 0):
isPrime == False
elif(primeNum % 9 == 0):
isPrime == False
else:
isPrime == True
return primeNum
I rewrote while(isPrime == False) as while not isPrime. Also, you don't need the if(isPrime == True) statement, because the while loop will be exited when isPrime == True.
2) In the function StackAdder(stack), you are introducing count, which was not defined before. Maybe you wanted sum instead? Or maybe you were trying to use the count() method (which returns the count of how many times an obj occurs in a list?)
3) In the function ConsecutivePrime(), Stackadder is a function, so your code should be: while(StackAdder(stack) == False)

Formatting, not printing incorrect format?

Hey I'm having an issue getting the last bit of my code to run.
I am unable to get the values at the end and believe it may have to do with my formatting, although I'm not entirely sure. Instead of stabbing in the dark I thought I'd ask around here as the fastest way to improve is with help from the more experienced.
I'm new, and not seasoned. Haven't been programming for a full 2 months yet.
import math
def month():
month = input(' # of month born ')
if month == '1':
print ("January")
return "January"
elif month == '2':
print ("February")
return "February"
elif month == '3':
print ("March")
return "March"
elif month == '4':
print ("April")
return "April"
elif month == '5':
print ("May")
return "May"
elif month == '6':
print("June")
return ("June")
elif month == '7':
print ("July")
return "July"
elif month == '8':
print("August")
return "August"
elif month == '9':
print("september")
return "September"
elif month == '10':
print("October")
return "October"
elif month == '11':
print ("November")
return "November"
elif month == '12':
return "December"
print ("December")
else:
return month()
month()
print('day born')
day=input(' input day # ')
print ('{}'.format (day))
if month==1 and day<20:
print ('Capricorn')
elif month ==1 and day>22:
print ('aquarius')
It does everything fine except return aquarious or capricorn.
How may I format it correctly so it prints these values?
You run the function month(), right after the definition of it, but you do not store the return value. You should do this:
m = month()
if m == "October":
# ...
But instead, you're comparing the function month to 1, which will result to False.
def month(): pass # month is a function
month == 1 # is month equal to 1? no! this is False
Also, the function month actually returns string by your design, so you should not compare it to 1, but to "January", for example. Also, there's a very handy builtin package for this, you can use datetime here, see https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior.
In [3]: import datetime
In [4]: datetime.datetime(2000, 1, 1).strftime('%B')
Out[4]: 'January'
In [5]: datetime.datetime(2000, 12, 1).strftime('%B')
Out[5]: 'December'
So in a function:
def convert_number_to_month_name(i):
return datetime.datetime(2000, i, 1).strftime('%B')

Categories