its my second day of class in introductory programming and im having trouble. We are on if statements. The homework is
Write a program that prompts the user for an integer (you can assume that the
value entered will be an integer). If that integer is equal to zero, print “zero”. If not, determine if
it is positive or negative and print which one it is. Also, determine if the number is evenly divisible
by 5 or not.
Now i can prompt the user for a number and determine if its positve or negative or if its divisible by 5 but i dont know how to make the program bypass the unmet first condition and go into the second set of condition, example of my code below,
number = input("enter an integer: ")
if number > 0 and number%5 == 0:
print number, "is positive and divisible by 5"
else :
print "positive but not divisible by 5"
if number < 0 and number%5== 0:
print "neggy and divisible by 5"
else :
print "neggy but not divisible by 5"
my problem is that when i type a negative number it print "positive but not divisible by 5" because the 1st condition wasnt met. I tried elif but i get a syntax error averytime, help?
Please dont go to fancy as my teacher only wants the basic "and", "or", "if", "else", and "elif", words used. Thanks
Use elif:
number = input("enter an integer: ")
if number > 0 and number%5 == 0:
print number, "is positive and divisible by 5"
elif number > 0:
print "positive but not divisible by 5"
elif number < 0 and number%5== 0:
print "neggy and divisible by 5"
elif number < 0:
print "neggy but not divisible by 5"
else:
print "zero"
Let’s tackle each of the tests separately first. So first of all, you want to check if it is positive or negative (or zero even). That is one “category” of properties, because a number cannot be both positive and negative:
if number > 0:
# number is positive
elif number < 0:
# number is negative
else:
# number is zero
Of course, you can order those checks however you want; you could also check for zero first etc.
So, the second check if it is divisible by 5 or not. That’s a second category, so we have to handle that separately from the sign:
if number % 5 == 0:
# number is divisible by 5
else:
# number is not divisible by 5
So now we have two separate checks for two separate property categories. If we want a single output for both properties (e.g. “positive and divisible by 5” as you already used in your code). There are different ways to interlock those two checks now. One would be to simply put one into the other one, like this:
if number > 0:
if number % 5 == 0:
print('Number is positive and divisible by 5')
else:
print('Number is positive but not divisible by 5')
elif number < 0:
if number % 5 == 0:
print('Number is negative and divisible by 5')
else:
print('Number is negative but not divisible by 5')
else:
print('Number is zero')
As you can see, this is just the second check pasted into each of the (appropriate) cases of the first check. Note that this will unnecessarily increase the indentation level, so we might want to look how we can avoid that.
You already started with this in your code, we basically want to combine two checks using and. Note that we need to make sure that in the above solution, the inner else cases (from the divisibility) still expects the outer (sign check) to be true. So we need to make sure that we keep that:
if number > 0 and number % 5 == 0:
print('Number is positive and divisible by 5')
elif number > 0:
print('Number is positive but not divisible by 5')
elif number < 0 and number % 5 == 0:
print('Number is negative and divisible by 5')
elif number < 0:
print('Number is negative but not divisible by 5')
else:
print('Number is zero')
As you can see, we’re down to a single indentation level, and we have all our checks within a single if-elif-else structure. This unfortunately forces us to have some duplication in the checks as explained above. That’s because when checking for two things in a single if, we don’t know which is false when we get to the else/elif. So if we still want to make sure that e.g. the number is positive when it wasn’t positive and divisible by 5, we have to check for that again.
This is essentially what you forgot: Your else could actually only say “not positive or not divisible by 5”.
Now, to take this just a bit further, we can actually still get rid of the duplication. Because our two “property categories” are completely independent, we can check them independently (just like we did at the beginning). To get a combined output, all we need to do is to construct that output sequentially:
# because zero is a special case, we handle it separately
# while sacrificing an indentation level.
if number == 0:
print('Number if zero')
else:
# check for the sign first
if number > 0:
output = 'Number is positive'
else:
output = 'Number is negative'
# check for the divisibility next
if number % 5 == 0:
output += ' and divisibile by 5'
else:
output += ' but not divisible by 5'
# whatever the checks resulted in, we have our output
print(output)
Of course this might be a bit too far for your task yet, but it might be good to know for the future :)
It's best to use if ... elif ... else but anyway, I'm throwing another option in:
if number == 0:
print 'zero'
else:
print number, 'is', 'positive' if number > 0 else 'negative', 'and',
print 'not' if number % 5 else '', 'divisible by 5'
Explanation... This takes advantage of the way the print statement in Python 2 can take several values separated by commas, and displays the values separated by spaces; and it uses conditional expressions, which allow you to rewrite (e.g.)
if condition:
print 'yes'
else:
print 'no'
as
print 'yes' if condition else 'no'
but are not very highly recommended because they often make code less readable.
if number == 0:
print "zero"
else:
pos = (number > 0 )
div_by_5 = (number % 5 == 0)
if pos and div_by_5:
print number, "is positive and div by 5"
elif pos and not div_by_5:
print number, "is positive but not div by 5"
elif not pos and div_by_5:
print number, "is negative and div by 5"
elif not pos and not div_by_5:
print number, "is negative but not div by 5"
Python 2.7.4
number = int(raw_input())
if not number: print "zero"
elif abs(number) % 5 == 0:
print [ `number` + " is negative and divisible by 5",
`number` + " is positive and divisible by 5"][number > 0]
else: print [ `number` + " is negative but not divisible by 5",
`number` + " is positive but not divisible by 5"][number > 0]
Backtick
Related
I have a code in python to know if a number is even or odd. But when I pass a negative number I receive another value. For example:
def even_or_odd(number):
if (number % 2) == 0:
return "Even"
elif number < 0:
return "Even"
else:
return "Odd"
if I select number -1 I expect Odd but I receive Even.
That's because it is hitting the less than 0 if statement first.
What you are checking for here is a number is even and negative, not if it is even or odd. The traditional way you check for even or odd still applies to negative numbers:
if number % 2 == 0:
return "Even"
else:
return "Odd"
This still works with negative numbers.
This question already has answers here:
Why does integer division yield a float instead of another integer?
(4 answers)
Closed 3 years ago.
I have created a small Python program in repl.it to illustrate the Collatz Conjecture, which says that if you start with any positive integer number n and you apply the following operations recursively: n/2 if n is even, 3n+1 if n is odd, you will always reach 1.
This is the code:
invalid_input = 0
while(invalid_input == 0):
n = input("Give me a positive integer: ")
try: #check for positive integer. If it cannot do int(n) it means a string was entered, and it goes to except.
if(int(n)>0):
invalid_input = 1 #this is to tell the while loop above that the right input was entered
print("Thank you.")
print("Now loading:")
else: #an integer was entered, but it was negative
print("Please enter a positive integer")
except: #a string was entered
print("Please enter a positive integer")
n=int(n)
nentered = n #this will keep track of the initial n
npeak = n #this will keep track of the highest n reached
iteration = 1 #this will keep track of the number of iterations
iterationmax = 1 #this will keep tack of the iteration at which npeak was reached
while(n != 1):
print("%5i: %5i" % (iteration,n))
if(n % 2 == 0): #divide by 2 if even
n=n/2
else: #if it is odd, multiply by 3 and add 1
n=3*n+1
iteration = iteration + 1
if(n>npeak): #record the higher n and its iteration
npeak = n
iterationmax = iteration
It works. But there is a problem: if the entered number is big enough, for example 6666666666666666666666666, then it does something really strange. This is what I get:
Give me a positive integer: 6666666666666666666666666
Thank you.
Now loading:
1: 6666666666666666666666666
2: 3333333333333333277409280
3: 1666666666666666638704640
4: 833333333333333319352320
5: 416666666666666659676160
6: 208333333333333329838080
7: 104166666666666664919040
8: 52083333333333332459520
9: 26041666666666666229760
10: 13020833333333333114880
etc
As you can see, I am expecting the second number to be exactly 3333333333333333333333333, but instead I am getting different numbers at the end.
As another example, entering 1000000000000000000000000 returns 499999999999999991611392 in the second iteration.
What could be the reason for this?
The reason of why what #ruohola said is true, is because when you use floating-point division with a single /, what happens is that a floating-point number is created. However, it cannot be represented as the number is so large, so it is rounded to the closest most accurate representation. So you will have to use // instead of /.
However, using //, is integer division. This results in an integer which can be represented much easier than a high float.
A very similar question can be found here, it contains some more explanation.
Change your / operation to be //, so that they don't result in (inaccurate) floating point values.
So this:
if(n % 2 == 0): #divide by 2 if even
n=n/2
Should be:
if(n % 2 == 0): #divide by 2 if even
n=n//2
Or as properly formatted by Python conventions:
if n % 2 == 0:
n //= 2
I'm trying to solve this problem below. I can get it to print whether it's odd or even but I can't get it to print out the correct message if number is a multiple of 4.
Here is the problem: Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. If the number is a multiple of 4, print out a different message.
Here is my code:
number = input("Pick a number and I'll tell you if it's odd or even. ")
def odd_or_even():
if int(number) % 2 == 0:
return("Your number is even.")
elif int(number) % 4 == 0:
return("Your number is a multiple of 4.")
else:
return("Your number is odd.")
print(odd_or_even())
If a number is a multiple of 4, it is also an even number and that's why it always triggers your first condition and doesn't even check the second one. Change the order of the conditions, i.e.:
...
if int(number) % 4 == 0:
return("Your number is a multiple of 4.")
elif int(number) % 2 == 0:
return("Your number is even.")
...
I am trying to create a program that prints out a list of numbers starting at 0 and leading up to a number the user inputs (represented by the variable "number"). I am required to use "while" loops to solve this problem (I already have a functional "for" loop version of the assignment). The program should mark anything in that list divisible by 3 with the word "Fizz," divisible by 5 with the word "Buzz," and anything divisible by both with "FizzBuzz" while also including unlabeled numbers outside of those specifications.
Every time I run this program, it ignores the conditions and just prints the word "FizzBuzz" however many times is represented by the number inputted. (I typically use 15 because it has at least one example of each condition, so that means I get 15 "FizzBuzz"s in a row).
To find out why it was doing that, I used print(i) instead of the rest of the program under the first conditional and it gave me 15 counts of the number 0, so there is reason to believe the program is completely ignoring the range I gave it and just outputting copies of i based on the user number input.
Any help would be appreciated!
number = int(input("Enter a Number"))
i = 0
while(i < number + 1):
if number % 3 == 0 and number % 5 == 0:
print("Fizzbuzz")
elif number % 5 == 0:
print("Buzz")
elif number % 3 == 0:
print("Fizz")
else:
print(number)
i += 1
print ("Done!")
You meant to check the divisibility of i, which increments every loop, not of number which doesn't change.
You also meant to print(i) in the else clause.
This question already has answers here:
Difference between multiple if's and elif's?
(9 answers)
Closed 8 years ago.
For e.g..
According to some experts,
The conditions here are mutually exclusive:
if(n>0):
print "Number is Positive"
if(n<0):
print "Number is Negative"
if(n==0):
print "Number is ZERO"
It would be better to rewrite with elif and else:
if n > 0:
print "Number is Positive"
elif n < 0:
print "Number is Negative"
else:
print "Number is ZERO"
So I just want to ask the question that , Is there any difference between ' if ' and ' elif ' . I know the basic difference between ' if ' and ' elif '. But I just want to know , Why some novice programmers prefer ' elif ' over ' if '?
The first form if-if-if tests all conditions, whereas the second if-elif-else tests only as many as needed: if it finds one condition that is True, it stops and doesn't evaluate the rest. In other words: if-elif-else is used when the conditions are mutually exclusive.
Let's write an example. if you want to determine the greatest value between three numbers, we could test to see if one is greater or equal than the others until we find the maximum value - but once that value is found, there is no need to test the others:
greatest = None
if a >= b and a >= c:
greatest = a
elif b >= a and b >= c:
greatest = b
else:
greatest = c
print greatest
Alternatively, we could assume one initial value to be the greatest, and test each of the other values in turn to see if the assumption holds true, updating the assumed value as needed:
greatest = None
if a > greatest:
greatest = a
if b > greatest:
greatest = b
if c > greatest:
greatest = c
print greatest
As you can see, both if-if-if and if-elif-else are useful, depending on what you need to do. In particular, the second of my examples is more useful, because it'd be easy to put the conditional inside a loop - so it doesn't matter how many numbers we have, whereas in the first example we'd need to write many conditions by hand for each additional number.
You can chain if with elif and finish with an else if none of the conditions in the chain were met. When checking through the statements, it will find the first matching one and execute the instructions within that block, then break from the if/elif/else block
n = 6
if n % 2 == 0:
print('divisible by 2')
elif n % 3 == 0:
print('divisible by 3')
else:
print('not divisible by two or three')
this would print
divisible by 2
However, say you replace that elif above with an if and remove the else clause...
divisible by 2
divisible by 3
the elif chains the statements and chooses the first appropriate one.