wrong answer with the nested if in python - python

I expect 3 value in return but my code doesn't return anything .
Thanks
a = 3
if a > 0:
if a == 1:
print(1)
elif a == 2:
print(2)
elif a == 2:
print(2)
elif a == 3:
print(3)
else:
print(a)

This is because your first condition is met, if a > 0. Because of this the code travels down that path and does not meet the two nested conditions of a == 1 or a == 2.

elif only executes if the if condition is False, so you may need:
a = 3
if a > 0:
if a == 1:
print(1)
elif a == 2:
print(2)
if a == 3:
print(3)
else:
print(a)
Output:
3

The first if statement is met as the value of a is greater than 0. The result you're looking for could be achieved with the following if/elif block:
a = 3
if a == 3:
print(3)
elif a == 2:
print(2)
elif a == 1:
print(1)
else:
print(a)
The above will check the variable for the three conditions, printing the desired result. The else: will catch any other input and print the variable.

because a ==3 , your first if is satisfied (other elif(s) will not trigger, because they only trigger if the previous ifs fail), then your code will test if a ==1 or 2 (which is not the case) hence your code prints nothing. Your should modify your code like this
a = 3
if a > 0:
if a == 1:
print(1)
elif a == 2:
print(2)
if a == 2:
print(2)
if a == 3:
print(3)
else:
print(a)

Related

python loops does not break even after successful while statement

My while loop does not break even after successful while recall. I need to check if the number exists and if it doesnt my while loop should break and successfull print out the number apart from 1 / 3 or 6
def is_1(inp):
if inp == 1:
print("1 it is")
return False
def is_3(inp):
if inp == 3:
print("3 it is")
return False
def is_6(inp):
if inp == 6:
print("6 it is")
return False
# ------------------------
me = False
while me != True:
try:
inpp = int(input("Please enter a number : "))
if any([is_1(inpp),is_3(inpp),is_6(inpp)]) == False:
me = False
else:
me = True
print(inpp)
except IndexError:
print('Inappropriate domain and username')
Each of the functions is_1(), is_3(), is_6() returns None when the respective condition is not met.
This means, if you enter any number other than 1, 3, or 6, this will lead to an array containing only Nones in the line
if any([is_1(inpp),is_3(inpp),is_6(inpp)]) == False:
i.e.
if any([None,None,None]) == False:
This, in turn, will evaluates to False.
In other words, the line me = True is never reached.
In order to fix this, you need to make the three methods above return something that evaluates to True if the condition isn't met (i.e. when you are passing in anything else than 1,3, or 6).
You just add a break and rewrite you if statements. That would break your loop. (Also according to what #p3j4p5 wrote)
Here is the code:
def is_1(inp):
if inp == 1:
print("1 it is")
return False
def is_3(inp):
if inp == 3:
print("3 it is")
return False
def is_6(inp):
if inp == 6:
print("6 it is")
return False
# ------------------------
me = False
while me != True:
try:
inpp = int(input("Please enter a number : "))
if inpp not in (1, 3, 6):
me = True
print(inpp)
break
elif any([is_1(inpp),is_3(inpp),is_6(inpp)]) == False:
me = False
except IndexError:
print('Inappropriate domain and username')
Now if the input is not in 1 or 3 or 6 it will break. Is this the solution?
The problem is_1, is_3, and is_6 will evaluate to none if inp != 1, and because of the code also to false if inp ==1
def is_1(inp):
if inp == 1:
print("1 it is")
return False
2-
any([item1, item2, ....]) returns true if any (or at least one) of the items is true. Otherwise It returns false
And because is_1 and is_3 and is_6 always return false or none, any([is_1(inpp),is_3(inpp),is_6(inpp)]) will always be false and me will always be false.
To fix the issue, is_1 and is_3 and is_6 needs to return a true value:
def is_1(inp):
if inp == 1:
print("1 it is")
return True
def is_3(inp):1
if inp == 3:
print("3 it is")
return True
def is_6(inp):
if inp == 6:
print("6 it is")
return True
# ------------------------
me = False
while me != True:
try:
inpp = int(input("Please enter a number : "))
if any([is_1(inpp),is_3(inpp),is_6(inpp)]) == False:
me = False
else:
me = True
print(inpp)
except IndexError:
print('Inappropriate domain and username')

How can I refactor my code using functions?

It is a simple maze game I did for school. I have tried different solutions but still cant figure out how. I don't necessarily need a full solution; any tips would help.
x = 1
y = 1
valid_selection = True
while True:
if x == 1 and y == 1:
if valid_selection == True:
print("You can travel: (N)orth.")
valid_selection = True
choice = input("Direction: ")
if choice.lower() == "n":
y += 1
else:
print("Not a valid direction!")
valid_selection = False
elif x == 1 and y == 2:
if valid_selection == True:
print("You can travel: (N)orth or (E)ast or (S)outh.")
valid_selection = True
choice = input("Direction: ")
if choice.lower() == "n":
y += 1
elif choice.lower() == "e":
x += 1
elif choice.lower() == "s":
y -= 1
else:
print("Not a valid direction!")
valid_selection = False
elif x == 3 and y == 1:
print("Victory!")
break
You could have your function recieving x and y as parameters, removing the While True and replacing it with its creation, like def MyFunc(x,y), putting the valid_selection variable inside it and removing x and y attributions. And then you call it in the end of the code passing 1 and 1 as your desired parameters, like MyFunc(1,1)
There are many ways to create a function.
First, you need to abstract what your program do. The name of the function have to express this.
Second, you need to know what are the inputs. In your case the input must be x and y, or the proper names to these input.
The answer which your function will return is a important thing to know. The user will see a print or the user of the function will use a number, string or other object to feed other function.
I hope this not confusing.

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

Can you use input to accept both an integer and a string?

I have a small script I have been working on for practice with Python. I am having trouble getting my input to accept a number for an if statement and also accept string as lower case.
I want to tell my script for any input if the user types '99' then close the program. So far it works where I have int(input()), but it won't work where I have input(). What am I doing wrong or is it not something I can do?
Right now my if statement looks like:
if choice1 == 99:
break
Should I just make 99 into a string by quoting it?
Maybe something like this:
if choice1 == "99":
break
Here is the script:
global flip
flip = True
global prun
prun = False
def note_finder(word):
prun = True
while prun == True:
print ('\n','\n','Type one of the following keywords: ','\n','\n', keywords,)
choice2 = input('--> ').lower()
if choice2 == 'exit':
print ('Exiting Function')
prun = False
start_over(input)
elif choice2 == 99: # this is where the scrip doesnt work
break # for some reason it skips this elif
elif choice2 in notes:
print (notes[choice2],'\n')
else:
print ('\n',"Not a Keyword",'\n')
def start_over(word):
flip = True
while flip == True:
print ('# Type one of the following options:\n# 1 \n# Type "99" to exit the program')
choice1 = int(input('--> '))
if choice1 == 99:
break
elif choice1 < 1 or choice1 > 1:
print ("Not an option")
else:
flip = False
note_finder(input)
while flip == True:
print ('# Type one of the following options:\n# 1 \n# Type "99" to exit the program')
choice1 = int(input('--> '))
if choice1 == 99:
break
elif choice1 < 1 or choice1 > 1:
print ("Not an option")
else:
flip = False
note_finder(input)
So input() always returns a string. You can see the docs here:
https://docs.python.org/3/library/functions.html#input
What you could do is something like this:
choice2 = input('--> ')
if choice2.isnumeric() and (int(choice2) == 99):
break
this avoids you to type check and catch errors that aren't important.
see below for how isnumeric works with different numeric types:
In [12]: a='1'
In [13]: a.isnumeric()
Out[13]: True
In [14]: a='1.0'
In [15]: a.isnumeric()
Out[15]: False
In [16]: a='a'
In [17]: a.isnumeric()
Out[17]: False

If comparison statements in 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")

Categories