If comparison statements in Python - python

This block of code returns "cat", "dog", "hamster", and "unicorn", but it shouldn't return "unicorn" at all! Is there any reason for this?
if random.randint(0,10) < 5:
print("dog")
elif random.randint(0,10) > 5:
print("cat")
elif random.randint(0,10) == 5:
print("hamster")
else:
print("unicorn")

You're getting new random number on each comparison. What you probably meant is:
my_random_int = random.randint(0,10)
if my_random_int < 5:
print("dog")
elif my_random_int > 5:
print("cat")
elif my_random_int == 5:
print("hamster")
else:
print("unicorn")

random.randint is called again each time it is reached, potentially producing a different result each time (since that is the function's purpose).
If you want to repeatedly test with the same value, then store the value first.

You should create the random number only once!
val = random.randint(0,10)
if val < 5:
print("dog")
elif val > 5:
print("cat")
elif val == 5:
print("hamster")
else:
print("unicorn")

Assuming correct indentation, there's no reason for three random ints to be respectively >=5, <=5, and "not 5".
You probably meant to do this:
value = random.randint(0, 10)
if value < 5:
print("dog")
elif value > 5:
print("cat")
elif value == 5:
print("hamster")
else:
print("unicorn")
Now there are no chances of unicorns.

Your random number is different everytime you call random.randint so it might be 7 when you test the first if and go past it, then 3, then 4, and bam, you're in unicorn.
You should call random.randint only once at the beginning of your if, save its value and check it instead.
myrand = random.randint(0,10)
if myrand < 5:
print("dog")
elif myrand > 5:
print("cat")
elif myrand == 5:
print("hamster")
else:
print("unicorn")

The issue here is that you're generating a new random number each time. You should create it once and then assign it to a variable, then check that.

You're generating three different random numbers. What you're thinking is this:
random_number = random.randint(0,10)
if random_number < 5:
print("dog")
elif random_number > 5:
print("cat")
elif random_number == 5:
print("hamster")
else:
print("unicorn")
This code will only return one word, and will never return "unicorn".

You need to create only one random integer.
Your code should be:
myRandom = random.randint(0,10)
if myRandom < 5:
print("dog")
elif myRandom > 5:
print("cat")
elif myRandom == 5:
print("hamster")
else:
print("unicorn")

Related

need help simplifying a program that finds how many times a number appears in an array

i have worked out how to do this using .count(), however i would like to find an alternative way in order to shorten the code.
if check[0]==check[1]==check[2]:
print('jackpot!')
money = money+100
if check[0]!=check[1]!=check[2]:
num1 = check.count(1)
if num1 == 2:
print('you've won £50')
money = money+50
else:
print('youve lost')
break
num2 = check.count(2)
if num2 == 2:
print('you've won £50')
money = money+50
else:
print('you've lost')
break
num3 = check.count(3)
if num3 == 2:
print('you've won £50')
money = money+50
else:
print('you've lost')
break
If you just have 3 numbers and need to check if there is 2 of the same numbers in the check[] list, then either of these will do. First one is using a for loop to iterate the list and uses the .count() function. Second one is just using if elif else statements, note the nesting. For the first one the list size doesn't matter since it will iterate no matter the size but the second only works for 3 numbers.
check = [1, 1, 3, 1 ,5, 6]
for i in check:
if check.count(i) >= 3:
print("jackpot!")
exit()
elif check.count(i) == 2:
print("you have won 50")
exit()
else:
print("you have lost")
or
check = [1, 2, 3]
if check[0] == check[1] == check[2]:
print("jackpot!")
elif check[0] == check[1] or check[1] == check[2] or check[0] == check[2]:
print("you have won 50")
else:
print("you have lost")

Python print day name of week from number

I'm creating a program which I have to put a number and when I run the program, the solution should be the day for that number. But I don't know how to do. The program I did was this:
num = 4
if(num = 1)
print('Monday')
elif(num = 2)
print('Tuesday')
elif(num = 3)
print('Wednesday')
elif(num = 4)
print('Thursday')
elif(num = 5)
print('Friday')
elif(num = 6)
print('Sunday')
elif(num = 7)
print('Saturday')
elif(num < 1)
print('Put a number between 1 and 7')
else(num > 7)
print('Put a number between 1 and 7')
In python, for statements like if, for, etc. You have to add : at the end of it.
And for comparing (for equal) you have to use == and not =
num = 4
if(num == 1):
print('Monday')
elif num == 2:
print('Tuesday')
.....
You can compare without parenthesis and it will work too.
num = 0
while num <= 7:
num += 1
if num == 1:
print('Monday')
elif num == 2:
print('Tuesday')
elif num == 3:
print('Wednesday')
elif num == 4:
print('Thursday')
elif num == 5:
print('Friday')
elif num == 6:
print('Saturday')
elif num == 7:
print('Sunday')

Menu navigation with if and else in Python

This is my little menu navigation with if and else statements:
def navigation():
navigation_eingabe = int(input())
if navigation_eingabe == 1:
met1()
if navigation_eingabe == 2:
pass
if navigation_eingabe == 3:
pass
if navigation_eingabe == 4:
pass
if navigation_eingabe == 5:
pass
if navigation_eingabe == 6:
pass
else:
print("Pls give only Integer numbers")
def met1():
print("method1")
met2()
def met2():
print("method2")
navigation()
Its not working correctly, after I give the Input as 1, the code goes to met1, then to meth2 and then to the else statement. I dont know why?
And then I program this alternativ code with a example:
def navigation ():
x = int(input())
if x == 1:
print("1")
xx1()
if x == 2:
print("2")
xx2()
else:
print("else statement")
def xx1():
print("this is met1")
def xx2():
print("this is met2")
navigation()
But in this code, the statement is working correctly, why not in the first code? Is this a problem with functional programming logic, or with the statement structury? but I cant see the difference of this two codes.
Thank you!
In python, when testing multiple conditions in the same block, you use if for the first condition, elif for other conditional statements after that, and then else. The code block under else runs only if the other conditions were False. The problem with your code is that you use all if statements where you should use elif. The reason your first code goes to the else statement is because your last if statement runs no matter what the result of the first if statement was.
if navigation_eingabe == 1:
met1()
elif navigation_eingabe == 2:
pass
put the rest of your elif statements, and end with the else statement, so it will print if none of the other conditions are true:
else:
print('Pls only give integer numbers.')
However, this code does not do what you think it does. You are using the else statement for exception handling. This does not work. What you need is a try-except statement:
try:
navigation_eingabe = int(input())
if navigation_eingabe == 1:
met1()
elif navigation_eingabe == 2:
pass
elif navigation_eingabe == 3:
pass
elif navigation_eingabe == 4:
pass
elif navigation_eingabe == 5:
pass
elif navigation_eingabe == 6:
pass
else:
print('not a number 1-6')
except ValueError: #the type of error if you try to convert a non-integer string to an int.
print('Pls only give integer numbers.')
This will check each condition and catch the error if an invalid string is passed to the input.
This happened because you thought the execution of navigation() function would stop after the first if statement. It is wrong as after that more if statements are there instead of elif.
So use elif instead of more if statements
if navigation_eingabe == 1:
met1()
elif navigation_eingabe == 2:
pass
elif navigation_eingabe == 3:
pass
elif navigation_eingabe == 4:
pass
elif navigation_eingabe == 5:
pass
elif navigation_eingabe == 6:
pass
else:
print("Pls give only Integer numbers")
Because you're using consecutive if statements as opposed to elif statements, the Python interpreter treats each block as a separate decisional, so navigation() is first evaluating whether navigation_eingabe == 1. For an entry of 1 at the input prompt, this is true. Then, because the next line is treated as a separate decisional statement, it checks if navigation_eingabe == 2, and so on, until it reaches the following block:
if navigation_eingabe == 6:
pass
else:
print("Pls give only Integer numbers")
At which the interpreter enters the decisional with the comparison navigation_eingabe == 6, and evaluates this regardless of whether any of the previous five comparisons were True or False. This comparison evaluates to False because navigation_eingabe == 1, and we fall into the else block as a catch-all.
Additionally, the else clause will never be reached for non-integer input anyway because int(input()) will raise a ValueError exception for anything that cannot be cast as an int. To catch non-integer input, you should separate the contents of navigation() into a try and an except block.
I suspect what you are actually trying to do is the following:
def navigation():
try:
navigation_eingabe = int(input())
if navigation_eingabe == 1:
met1()
elif navigation_eingabe == 2:
pass
elif navigation_eingabe == 3:
pass
elif navigation_eingabe == 4:
pass
elif navigation_eingabe == 5:
pass
elif navigation_eingabe == 6:
pass
except ValueError:
print("Please only enter integers.")
def met1():
print("method1")
met2()
def met2():
print("method2")
navigation()
For which, when you enter 1 at the prompt, the output is the following:
1
method1
method2

Function with branch

Define function print_popcorn_time() with parameter bag_ounces. If bag_ounces is less than 3, print "Too small". If greater than 10, print "Too large". Otherwise, compute and print 6 * bag_ounces followed by "seconds". End with a newline. Example output for bag_ounces = 7:
42 seconds.
For this program I'm getting suck on an error:
"File "main.py", line 6
elif bag_ounces = bag_ounces * 6"
^
def print_popcorn_time(bag_ounces):
if bag_ounces < 3:
print("Too small")
elif bag_ounces > 10:
print("Tool large")
elif bag_ounces = bag_ounces * 6
else:
print(bag_ounces)
print_popcorn_time(7)
Your last condition should just be else
def print_popcorn_time(bag_ounces):
if bag_ounces < 3:
print("Too small")
elif bag_ounces > 10:
print("Tool large")
else:
print('{} seconds'.format(bag_ounces * 6))
Here is the proper code. Tested in ZyBooks. The "else" print statement needed to be reformatted. Cheers.
def print_popcorn_time(bag_ounces):
if bag_ounces < 3:
print('Too small')
elif bag_ounces > 10:
print('Too large')
else:
print((bag_ounces * 6), 'seconds')
print_popcorn_time(7)
def print_popcorn_time(bag_ounces):
if bag_ounces < 3:
print('Too small')
elif bag_ounces > 10:
print('Too large')
else:
print(f'{bag_ounces * 6} seconds')
user_ounces = int(input())
print_popcorn_time(user_ounces)
def print_popcorn_time(bag_ounces):
if bag_ounces < 3:
print("Too small")
return
if bag_ounces > 10:
print("Too large")
return
else:
print(str(6 * bag_ounces)+ " seconds")
user_ounces = int(input())
print_popcorn_time(user_ounces)

Program is outputing answer for coin toss even if the user chose card

def program():
print ("please make sure your answer is spelt correctly")
print ('Start program')
choice = input("please select either a card or coin?")
if choice == "COIN" or "coin" or "Coin":
print ("you will now be given heads or tails")
import random
higher_value = 2
lower_value = 1
final_value = random.randint (lower_value, higher_value)
if final_value == 1:
print ("Heads")
elif final_value == 2:
print ("Tails")
#CARD
else:
if choice == "Card" or "card" or "CARD":
print("you will now be given a number for; number,suit")
import random
higher_value = 13
lower_value = 1
final_value = random.randint (lower_value, higher_value)
if final_value == 1:
print ("ace")
if final_value == 2:
print ("2")
if final_value == 3:
print ("3")
if final_value == 4:
print ("4")
if final_value == 5:
print ("5")
if final_value == 6:
print ("6")
if final_value == 7:
print ("7")
if final_value == 8:
print ("8")
if final_value == 9:
print ("9")
if final_value == 10:
print ("10")
if final_value == 11:
print ("Jack")
if final_value == 12:
print ("Queen")
if final_value == 13:
print ("King")
import random
higher_value = 4
lower_value = 1
final_value = random.randint (lower_value, higher_value)
if final_value == 1:
print ("Hearts")
if final_value == 2:
print ("Clubs")
if final_value == 3:
print ("Spades")
if final_value == 4:
print ("Diamonds")
#REPEAT LOOP
flag = True
while flag:
program()
flag = input('Would you like to run the program again? [y/n]') == 'y'
print ("The program will now terminate.")
print ("Have a good day")
I am currently trying to separate the two parts of the program this is due to the fact that if I input card it will out put the results of coin toss and card pick this is quite frustrating. I can't see a reason why this may be happening so could someone please fix this for me, thanks :)
You have to correctly indent this part:
import random
higher_value = 2
lower_value = 1
final_value = random.randint (lower_value, higher_value)
if final_value == 1:
print ("Heads")
elif final_value == 2:
print ("Tails")
It must have the same indentation as print ("you will now be given heads or tails"), or else the interpreter will assume it exists outside the if statement
In the same manner you have to indent everything below print("you will now be given a number for; number,suit") correctly
Remember that python is different than other languages in the way that you do not use curly braces or begin..end statements to show a block of code. Rather the interpreter understands blocks of code through indentation, so you have to be careful with it.
EDIT: To further explain it, you must understand the difference of the following pieces of code:
i=1
j=2
if i==1:
print i
if j==10:
print j
else: #<--- this corresponds to if i==1:
print j
This will print 1
However, by just changing the indentation:
i=1
j=2
if i==1:
print i
if j==10:
print j
else: #<--- now this corresponds to if j==10:
print j
This will print 1 2
EDIT 2:
if choice == "COIN" or "coin" or "Coin":
This must be changed to
if choice == "COIN" or choice == "coin" or choice == "Coin":
Or else it will always evaluate to true
In the same manner change : if choice == "Card" or "card" or "CARD":
EDIT 3:
This works for me
import random
def main():
print ("please make sure your answer is spelt correctly")
print ('Start program')
choice = input("please select either a card or coin?")
if choice == "COIN" or choice == "coin" or choice == "Coin":
print ("you will now be given heads or tails")
higher_value = 2
lower_value = 1
final_value = random.randint (lower_value, higher_value)
if final_value == 1:
print ("Heads")
elif final_value == 2:
print ("Tails")
#CARD
else:
if choice == "Card" or choice == "card" or choice == "CARD":
print("you will now be given a number for; number,suit")
higher_value = 13
lower_value = 1
final_value = random.randint (lower_value, higher_value)
if final_value == 1:
print ("ace")
if final_value == 2:
print ("2")
if final_value == 3:
print ("3")
if final_value == 4:
print ("4")
if final_value == 5:
print ("5")
if final_value == 6:
print ("6")
if final_value == 7:
print ("7")
if final_value == 8:
print ("8")
if final_value == 9:
print ("9")
if final_value == 10:
print ("10")
if final_value == 11:
print ("Jack")
if final_value == 12:
print ("Queen")
if final_value == 13:
print ("King")
higher_value = 4
lower_value = 1
final_value = random.randint (lower_value, higher_value)
if final_value == 1:
print ("Hearts")
if final_value == 2:
print ("Clubs")
if final_value == 3:
print ("Spades")
if final_value == 4:
print ("Diamonds")
if __name__ == "__main__":
main()

Categories