This question already has answers here:
Difference between multiple if's and elif's?
(9 answers)
Closed 5 days ago.
Something that's confusing me is If statements vs Elif statements. If they can both be run and both do the same thing, then what's the difference? For example:
num = int(input("Please enter a number 1-10 "))
if num == 1:
print("I is the roman numeral for 1 ")
elif num == 2:
print("II is the roman numeral for 2 ")
elif num == 3:
print("III is the roman numeral for 3 ")
else:
print("invalid number please try again")
This code can and will run, but what's stopping me from just using an If statement instead of an elif? I read that elifs are faster, but I don't know how true that is if at all.
I've tried going back and removing the if statements and replacing them with elif statements and vice versa, but I just don't see the difference.
The semantics are totally different, and it is very important to understand the difference. Just a bunch of ifs will run only based on the condition. But if you use if ... elif... then the elif will only run if previous if and elifs did not succeed!
In your case, your conditions are mutually exclusive so the behavior is exactly equivalent. But suppose your conditions were not mutually exclusive. Consider the different behaviors between:
x = 1
if x == 1:
print("I am solitary")
elif x < 12:
print("I am less than a dozen")
which simply prints:
I am solitary
versus:
x = 1
if x == 1:
print("I am solitary")
if x < 12:
print("I am less than a dozen")
which prints:
I am solitary
I am less than a dozen
Also note, because of your else on the last if, the behavior isn't exactly equivalent.
Related
Firstly, I am a beginner in python. So i won't be able to understand complex stuff.
So I tried to make an age testing thing (it was for testing before I try to make a large one). I wrote a code where if the age is equal to 4, then it shows "yes". and if the age in range of 2 to 8, it will show "what". and if it is some thing else, it shows "wot". i want the priority of the first statement more than the second one, like if the first one is true, then skip the second one.
code:
if (age<8 and age>2):
print ("what")
if (a == 4):
print ("yes")
else:
print ("wot")
Try this code :
if age == 4 :
print('yes')
elif age < 8 and age > 2 :
print('what')
else :
print('wot')
python does not require round bracket in conditions.
You are looking for elif statement
if age == 4:
print('yes')
elif age > 2 and age <8:
print('what')
else:
print('wot')
All these three statements are exclusive, i.e. only one print call will be made, the one that gets a True evaluation first from top to bottom.
The precedence goes like this:
if then elif then else. Usually you would have one if and as many elifs you want and one or no else statements. In your case, you would like to have a if statement to check for age == 4 and elif age > 2 and age < 8 while else takes care of any other possible case.
In that case you should do:
if age == 4:
print('yes')
elif age < 8 and age > 2:
print('what')
else:
print('wot')
Then if the first conditional statement is true, the rest of the lines get skipped. If the first line fails, then it moves on to the second statement, etc...
Also, you used age as well as a for your age variable, that will also cause an issue.
As what the others have replied, you would be using an nested if condition in your case. In python, your first condition will start as if, followed by elif (it stands for else if) and else (which concludes what will happen if none of the previous conditions are met)
For example:
if condition 1:
print("hi")
elif condition 2:
print("bye")
else:
print("hello")
Note that in python, once the first condition is met, it will automatically perform the action specified under that particular condition and exit from the if statement (meaning the rest of the statement will be ignored).
I am new to python and I am taking a summer online class to learn python.
Unfortunately, our professor doesn't really do much. We had an assignment that wanted us to make a program (python) which asks the user for a number and it determines whether that number is even or odd. The program needs to keep asking the user for the input until the user hit zero. Well, I actually turned in a code that doesn't work and I got a 100% on my assignment. Needless to say our professor is lazy and really doesn't help much. For my own knowledge I want to know the correct way to do this!!! Here is what I have/had. I am so embarrassed because I know if probably very easy!
counter = 1
num = 1
while num != 0:
counter = counter + 1
num=int(input("Enter number:"))
while num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
There are a couple of problems with your code:
You never use counter, even though you defined it.
You have an unnecessary nested while loop. If the number the user inputs is even, then you're code will continue to run the while loop forever.
You are incorrectly using the else clause that is available with while loops. See this post for more details.
Here is the corrected code:
while True:
# Get a number from the user.
number = int(input('enter a number: '))
# If the number is zero, then break from the while loop
# so the program can end.
if number == 0:
break
# Test if the number given is even. If so, let the
# user know the number was even.
if number % 2 == 0:
print('The number', number, 'is even')
# Otherwise, we know the number is odd. Let the user know this.
else:
print('The number', number, 'is odd')
Note that I opted above to use an infinite loop, test if the user input is zero inside of the loop, and then break, rather than testing for this condition in the loop head. In my opinion this is cleaner, but both are functionally equivalent.
You already have the part that continues until the user quits with a 0 entry. Inside that loop, all you need is a simple if:
while num != 0:
num=int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
I left out the counter increment; I'm not sure why that's in the program, since you never use it.
Use input() and If its only number specific input you can use int(input()) or use an If/else statement to check
Your code wasn't indented and you need to use if condition with else and not while
counter = 1
num = 1
while num != 0:
counter = counter + 1
num = int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
Sample Run
Enter number:1
Odd 1
Enter number:2
Even 2
Enter number:3
Odd 3
Enter number:4
Even 4
Enter number:5
Odd 5
Enter number:6
Even 6
Enter number:0
Even 0
I am a beginner student in a python coding class. I have the majority of the done and the program itself works, however I need to figure out a way to make the program ask if wants a subtraction or an adding problem, and if the user would like another question. I asked my teacher for assistance and he hasn't gotten back to me, so I'm simply trying to figure out and understand what exactly I need to do.
import random
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
maximum = 10 ** x;
maximum += 1
firstnum = random.randrange(1,maximum) # return an int from 1 to 100
secondnum = random.randrange(1, maximum)
compsum = firstnum + secondnum # adds the 2 random numbers together
# print (compsum) # print for troubleshooting
print("What is the sum of", firstnum, " +", secondnum, "?") # presents problem to user
added = int(input("Your answer is: ")) # gets user input
if added == compsum: # compares user input to real answer
print("You are correct!!!")
else:
print ("Sorry, you are incorrect")
You'll want to do something like this:
def foo():
print("Doing good work...")
while True:
foo()
if input("Want to do more good work? [y/n] ").strip().lower() == 'n':
break
I've seen this construct (i.e., using a break) used more often than using a sentinel in Python, but either will work. The sentinel version looks like this:
do_good_work = True
while do_good_work:
foo()
do_good_work = input("Want to do more good work? [y/n] ").strip().lower() != 'n'
You'll want to do more error checking than me in your code, too.
Asking users for input is straightforward, you just need to use the python built-in input() function. You then compare the stored answer to some possible outcomes. In your case this would work fine:
print('Would you like to test your adding or subtracting skills?')
user_choice = input('Answer A for adding or S for subtracting: ')
if user_choice.upper() == 'A':
# ask adding question
elif user_choice.upper() == 'S':
# ask substracting question
else:
print('Sorry I did not understand your choice')
For repeating the code While loops are your choice, they will repeatedly execute a statement in them while the starting condition is true.
while True: # Condition is always satisfied code will run forever
# put your program logic here
if input('Would you like another test? [Y/N]').upper() == 'N':
break # Break statement exits the loop
The result of using input() function is always a string. We use a .upper() method on it which converts it to UPPERCASE. If you write it like this, it doesn't matter whether someone will answer N or n the loop will still terminate.
If you want the possibility to have another question asked use a while loop and ask the user for an input. If you want the user to input whether (s)he want an addition or substraction you already used the tools to ask for such an input. Just ask the user for a string.
I've been working on this simple program in Python just so I can start experimenting with Python and become more knowledgeable of Python and other programming languages in general by designing them in a way in which others can use them in an efficient manner without getting caught on the parts which make this code work. I've been doing this by having a simple program calculate "Angles in a triangle" as it's a simple subject. Recently, I replaced def(): commands with if statements as it cuts down typing to a minimum and making it generally easier for others however, when I try to run this code I get a syntax error message with N becoming highlighted on line 17.
def triangle():
N = int(input("Please enter the number of angles you currently have between 1 and 3: "))
if N == 1:
a = int(input("What's one of the angles?"))
b = int(input("What's the other angle in the triangle?"))
c = a + b
f = 180 - c
print(f)
print("If you'd like to continue, please type in triangle()")
elif N == 2:
a = int(input("What's the value of angle 1?"))
b = 180 - a
c = b /2
print(c)
print("If you'd like to continue, please type in triangle()")
else N == 3:
a = 180
b = 180 / 3
print(b)
print("If you'd like to continue, please type in triangle()")
But I'm getting a syntax error returned on elif N == 3:
Any tips would be great.
else does not have a condition.. remove it to just say
else:
or make it says
elif N == 3:
You have else N == 3:. That is not how the if..elif..else structure works - the else is a catch-all branch that is entered if none of the preceding if or elif conditions are satisfied. If you want to check specifically for N == 3 and no other values, use elif N == 3. If you want a catch-all condition, simply use else:.
elif N == 3:
Either you meant elif (which is Python for else..if), or else
If you meant plain else, it doesn't take a condition.
If you want to annotate that an else implies a certain condition is met, then I use a comment:
else: # N == 3
But that's considered bad style: only do that if you're sure N cannot have any other value than 1,2,3. In your case the user could also input any number 4,5,..,9 (or indeed 10 or larger, or indeed 0 or any negative number), and that will wrongly get handled by the N==3 branch.
Whereas if your last branch if elif N == 3, with no else-clause, invalid numbers will silently fail every branch in your tree.
So for completeness and sanity-checking, you might prefer to do:
...
elif N ==3:
# Handle N == 3 case
else:
print "Invalid number!"
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 years ago.
I am trying to write a number guessing program as follows:
def oracle():
n = ' '
print 'Start number = 50'
guess = 50 #Sets 50 as a starting number
n = raw_input("\n\nTrue, False or Correct?: ")
while True:
if n == 'True':
guess = guess + int(guess/5)
print
print 'What about',guess, '?'
break
elif n == 'False':
guess = guess - int(guess/5)
print
print 'What about',guess, '?'
break
elif n == 'Correct':
print 'Success!, your number is approximately equal to:', guess
oracle()
What I am trying to do now is get this sequence of if/ elif/ else commands to loop until the user enters 'Correct', i.e. when the number stated by the program is approximately equal to the users number, however if I do not know the users number I cannot think how I could implement and if statement, and my attempts to use 'while' also do not work.
As an alternative to #Mark Byers' approach, you can use while True:
guess = 50 # this should be outside the loop, I think
while True: # infinite loop
n = raw_input("\n\nTrue, False or Correct?: ")
if n == "Correct":
break # stops the loop
elif n == "True":
# etc.
Your code won't work because you haven't assigned anything to n before you first use it. Try this:
def oracle():
n = None
while n != 'Correct':
# etc...
A more readable approach is to move the test until later and use a break:
def oracle():
guess = 50
while True:
print 'Current number = {0}'.format(guess)
n = raw_input("lower, higher or stop?: ")
if n == 'stop':
break
# etc...
Also input in Python 2.x reads a line of input and then evaluates it. You want to use raw_input.
Note: In Python 3.x, raw_input has been renamed to input and the old input method no longer exists.