Not sure about python function - python

I am only starting and getting mad over this function (it gives me the wrong outputs):
def rental_car_cost(days):
x = 40
if days < 2:
return days*x
elif days >= 3:
return days*x-20
elif days>= 7:
return days*x-50
else:
print "Please enter nr of days"
Also, how do I make sure that a number is entered for "days"?

Not sure what you are expecting, however change the order of the elif conditions:
def rental_car_cost(days):
if isinstance(days, int):
x = 40
if days < 2:
return days*x
elif days >= 7:
return days*x-50
elif days>= 3:
return days*x-20
else:
print "Please enter nr of days"

The days>= 7 and else clauses never trigger, because the earlier days >= 3 triggers on the same inputs. if/elif/else clauses are processed in order until one of them is triggered.
What you need are clauses for days < 2, days < 7 and else.
To detect non-numbers, start with
if not isinstance(days, int):
which does a type check for integers.

rental_car_cost(2) should equal 60
But, none of your if statements will match 2. 2 isn't less than 2, nor is it greater than or equal to 3, nor is it greater than or equal to 7. Follow the advise from the other two answers by larsmans and Ankit Jaiswal also, but I'm assuming 2 should match the days*x-20 part. Just change elif days >= 3: to elif days >= 2:.

Related

how to use while loop?

number = 50
while number >= 0:
if number % 5 == 0:
print(number)
number = number - 1
elif number % 5 == 1:
continue
number = number = number - 1
the answer it's giving me is 50 then the loop stops executing
Here is the program I am trying to make:
While Loops Practice #2
Create a While Loop that subtracts one by one the numbers from 50 to 0 (both numbers included) with the following additional conditions:
If the number is divisible by 5, show that number on the screen (remember that here you can use the modulus operation dividing by 5 and checking the remainder!)
If the number is not divisible by 5, continue executing the loop without showing the value on the screen (don't forget to continue subtracting so that the program doesn't run infinitely).
Here is your code, improved:
number = 50
while number >= 0:
if number % 5 == 0:
print(number)
number = number - 1
I'm confused about that too, but here are my thoughts: you only subtracted when number % 5 == 1, but it can also be 2, 3, 4 or 5.
num = 50
while num != 0:
if num % 5 == 0:
print(num)
num -= 1
would work for this as it will only print the number if it is divisible by 5, and always subtract.
Make sure you always subtract 1 from number before continuing the loop. As the prompt reminds you, this is especially important when you use the continue statement, since that brings you straight back to the top of the loop -- if you haven't subtracted before then, the loop will repeat infinitely!
One way to make sure that something always happens even if execution is interrupted (not just a continue but maybe a return, a break, a raise, etc) is try/finally:
number = 50
while number >= 0:
try:
if number % 5 == 0:
print(number)
elif number % 5 == 1:
continue
finally:
number -= 1
prints:
50
45
40
35
30
25
20
15
10
5
0
In this case, though, there's no need to immediately continue the loop, since there's nothing in the loop that you explicitly need to skip in the number % 5 == 1 case (note that this isn't the same as "not divisible by 5" -- what you're testing for here is "has a reminder of 1 after dividing by 5", i.e. 1, 6, 11, and so on, which isn't part of the problem statement).
You can therefore just do:
number = 50
while number >= 0:
if number % 5 == 0:
print(number)
number -= 1
The main structure is corret, but in the last line you wrote two times the code "number =" and "else" is useless in this case, because you need to substract 1 in every loop.
here's the code solved:
number = 50
while number != 0:
if (number%5) == 0:
print(number)
number = number - 1

I’m trying to code a blackjack game, can anyone help me with my score-checking solution? Python

this is my code. As you can see by my comment at the top of my code, I want any value under 21 to return the value 0, exactly 21 to return a 1, and anything over 21 to return a 2. This is my best attempt, and almost everything works.
Except when I win in my blackjack game and get 21 points, where the output of winCheck() is still 0. Anything over 21 returns the value 2 correctly, just like when I’m still under 21 points I get returned a 0. I just can’t get it to return the value 1 when I hit 21 points.
Is there something I’ve misunderstood about if/elif statements?
# 0 = under 21, 1 = exactly 21, 2 = bust
def winCheck(points):
if points <= 21:
return 0
elif points == 21:
return 1
elif points >= 21:
return 2
The conditions are checked in order: if points <= 21 is true (and it is if points is 21), your if statement never bothers checking points == 21. Simply altering the order of the checks will suffice:
def winCheck(points):
if points == 21:
return 0
elif points <= 21:
return 1
elif points >= 21:
return 2
Note, though, that if points == 21 is false, then points <= 21 and points < 21 are equivalent. Using < (and >) is both more readable and allows you to peform the checks in any order, because only one of the three can be true for a given value of points.
def winCheck(points):
if points == 21:
return 0
elif points < 21:
return 1
elif points > 21:
return 2
or
def winCheck(points):
if points < 21:
return 0
elif points == 21:
return 1
elif points > 21:
return 2

Python - Multiple Elif Statements Being Skipped Over in If Statement

I'm trying to get my program to return different statements based off the hour the user inputs. If I input a number for hour between he first two statements ((hours < 6) and (hours <= 10) or (hours >= 6)), it will return the correct string but if I input anything greater than 10 for the hour, it won't return the intended string for that hour but it will keep repeating the second string.
Any help is appreciated!
Here's my program:
https://i.stack.imgur.com/uQzBi.png
def food(hours, boolean):
if boolean == "True" or boolean == "true":
if (hours < 6):
return "no food"
elif (hours <= 10) or (hours >= 6):
return "breakfast, marmalade"
elif (hours <= 15) or (hours >= 11):
return "lunch, true,dessert"
elif (hours < 22) or (hours >= 15):
return "dinner, dessert"
else:
return "no food"
else:
if (hours < 6):
return "no food"
elif (hours <= 10) or (hours >= 6):
return "breakfast,coffee"
elif (hours <= 15) or (hours >= 11):
return "lunch, false"
elif (hours < 22) or (hours >= 15):
return "dinner"
else:
return "no food"
x = food(15, "true")
print(x)
You should be using “and” instead of “or”. Anything > 10 will also be >= 6 so the second condition always matches.
Python have boolean value True and False. Their is no need to use strings 'True' or 'False'. You can also use the power of if-elif-else logic. Python executes from top to bottom, when condition is met, it breaks. Your function can be rewritten to this:
def food(hour, boolean):
'''Food
Takes in hour as int and boolean as bool
E.g. x = food(15,True)
# TODO:
Ensure that input data types are correct.
'''
if boolean:
if hour >= 22 or hour >= 0:
return 'no food'
elif hour >= 15:
return 'dinner, dessert'
elif hour >= 11:
return 'lunch, true,dessert'
elif hour >= 6:
return 'breakfast, marmalade'
else:
raise ValueError('something wrong')
else:
if hour >= 22 or hour >= 0:
return 'no food'
elif hour >= 15:
return 'dinner'
elif hour >= 11:
return 'lunch, false'
elif hour >= 6:
return 'breakfast, coffee'
else:
raise ValueError('something wrong')
x = food(15, True)
print(x)
Looks like the first elif statement is your problem. You should use and instead of or. By using or, anything >= 6 will return breakfast marmalade, not just anything between 6 and 10.
Welcome to StackOverflow! As mentioned by the other answers, using 'and' instead of 'or' would solve your issue. However, it is redundant to include more than one condition for each meal if they are all sequential as by writing:
if (hours < 6):
return "no food"
you are already saying to only output the return value if the hour input is less than 6, hence only values more than 6 would make it to the next elif statement.
Do let me know if I misunderstood something about your program's use case that required you to write the code as such!

conditional flows - I am stuck in- if elif else- work, I have tried some solutions that generate 1,1,1 and no -1, or 0 as required

just learning python. Been working on conditional flows, and got stuck here. Kindly help me out. Thanks.
def greater_less_equal_5(answer):
if ________:
return 1
elif ________:
return -1
else:
return 0
print greater_less_equal_5(4)
print greater_less_equal_5(5)
print greater_less_equal_5(6)
Just use conditionals:
def greater_less_equal_5(answer): #Take in input
if answer <= 5: #Check to see if it is less than or equal to 5
return 1 #Truthy value
else:
return 0 #Untruthy value
print greater_less_equal_5(4) #1
print greater_less_equal_5(5) #1
print greater_less_equal_5(6) #0
I am not sure, what you want out there, but I hope you want the function to tell you whether the number you enter is less than or greater than or equal to 5. Here is the code:
def greater_less_equal_5(answer):
if answer > 5:
return 'Greater than 5'
elif answer < 5:
return 'Less than 5'
else:
return 'Equal to 5'
print greater_less_equal_5(4) # Less than 5
print greater_less_equal_5(5) # Equal to 5
print greater_less_equal_5(6) # Greater than 5

Python greater than or less than

I have an 'if-elif-else' block and if a value is within that range it is assigned a certain value. However it when I run it just assigns it the value in the else block. This is my code:
if mile < 300:
mileInfo['miles'] = 1
elif mile>=300 and mile <2000:
mileInfo['miles'] = 2
elif mile>=2000 and mile <5000:
mileInfo['miles'] = 3
else:
mileInfo['miles'] = 4
Mile returns a float, but I thought that this didn't matter as much as in Java for example.
Thanks
Maybe mile is a string containing a number? It will not be automatically converted.
>>> "1" < 100
False
>>> "1" == 1
False
You don't need to have the elif re-check that the previous if was false. If the value wasn't < 300, it is guaranteed to be >=300.
The issue was that 'mile' was a string and as pointed out by other members string is not automatically converted. So I changed code to:
mileInt = int(float(mile))
if mileInt < 300:
mileInfo['miles'] = 1
elif mileInt < 2000:
mileInfo['miles'] = 2
elif mileInt < 5000:
mileInfo['miles'] = 3
else:
mileInfo['miles'] = 4
Using print type(mile) helps check what the type is.

Categories

Resources