If number is a multiple of n - Python - python

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.")
...

Related

I don't know why the results of my code aren't the same?

Here's the instructions:
This question deals with numbers that can be used as keys: two numbers
are considered to be key if the largest of the two numbers is prime. A
prime number is one that is divisible by 1 and itself. Your task is to
write a python program that reads two integers (as described above)
from the user and checks if they are valid keys. If the user inputs a
float, the appropriate conversion must be done. If the user inputs a
non digit number, the appropriate error catch must be used Allow the
user to repeat the process as many times as she/he would like
Here is my attempt at an answer but the answers of this code keep changing and I don't know why...
i=1
while i!=0:
int1=int(input("dear user please enter the 1st number "))
int2=int(input("dear user please enter the 2nd number"))
largest=max(int1 , int2)
if largest >1:
for i in range (2, int(largest/2)+1):
if ( largest % i )== 0:
print("it cannot be a key ", largest)
break
else:
print("the key is ", largest) break print (" enter another keys")
If you mean that it prints "valid key" and "invalid key" in the same run, it's because it runs through every value for i, so for example 27 % 3 = 0 but 27 % 2 != 0 therefore it will for i = 3 print that it is a valid key.
To fix this you could do this:
valid_key = False
if largest > 1: for i in range(2, (int(largest/2)) + 1):
if (largest % i) == 0:
valid_key = False
break
else:
valid_key = True
if(valid_key):
print(largest, "is a valid key"
else:
print(largest, "is not a prime number")
You can use for-else. It will check if the largest number can divide by i and if it doesn't divide by any of those numbers it will go for the else and say that its a prime number so it wont print negative and positive at the same time. Here's how to use it:
while 1 != 0:
int1 = int(input("dear user please enter the 1st number "))
int2 = int(input("dear user please enter the 2nd number"))
largest = max(int1, int2)
if largest > 1:
for i in range(2, int(largest/2)+1):
if (largest % i) == 0:
print("it cannot be a key ", largest)
break
else:
print("the key is ", largest)
print("enter another keys")
It is because, for every condition it is printing some or the other thing. You've to take a new variable which has some inital value. Check the if condition in loop, if the condition is satisfied, change the value of the variable. After completion, check if the variable value is changed or not. If changed, the condition was satisfied else, it was never satisfied. Your code:
i=1
f=0
while i!=0:
int1=int(input("dear user please enter the 1st number "))
int2=int(input("dear user please enter the 2nd number"))
largest=max(int1 , int2)
if largest >1:
for i in range (2, int(largest/2)+1):
if ( largest % i )== 0:
f=1
break
if f==1:
print("It cannot be key")
if f==0:
print("It can be key")
break

How to count how many times a number was printed using python?

So I made a nooby Collatz Sequence showing program. I am interested in knowing how many times number was printed by the computer so that I can see how many steps it took for a number to eventually become 1. If you don't know much about the Collatz sequence, run my code...
import sys
def collatz(number):
if number <= 0:
print("Next time, enter an integer greater than 1.")
sys.exit()
while number % 2 == 0:
number = number // 2
print(number)
if number == 1:
sys.exit()
while number % 2 != 0:
number = 3*number+1
print(number)
collatz(number)
print("""Enter a number.
Even number is halfed, odd number is multiplied by 3 and 1 is added to the product.
This is called as Collatz sequence.
Watch as your number slowly becomes 1.
Enter a positive integer:""")
try:
collatz(int(input()))
except ValueError:
print("Next time, Enter a positive integer, you dummy...")
One really quick and dirty way to do this, would be to just use an "iterations" argument. Something like this would get your desired result:
import sys
def collatz(number, iterations=0):
if number <= 0:
print("Next time, enter an integer greater than 1.")
sys.exit()
while number % 2 == 0:
number = number // 2
print(number)
iterations += 1
if number == 1:
print(f'This number took {iterations} steps to get to 1')
sys.exit()
while number % 2 != 0:
number = 3*number+1
print(number)
iterations += 1
collatz(number, iterations)
print("Enter a number.")
print("Even number is halfed, odd number is multiplied by 3 and 1 is added to the product.")
print("This is called as Collatz sequence.")
print("Watch as your number slowly becomes 1.\nEnter a positive integer:")
try:
collatz(int(input()))
except ValueError:
print("Next time, Enter a positive integer, you dummy...")
You can also use a global variable steps. But NewBoard's solution is also good.
import sys
steps = 0
def collatz(number):
global steps
if number <= 0:
print("Next time, enter an integer greater than 1.")
sys.exit()
while number % 2 == 0:
steps += 1
number = number // 2
print(number)
if number == 1:
print(f"Steps: {steps}")
sys.exit()
while number % 2 != 0:
steps += 1
number = 3*number+1
print(number)
collatz(number)
print("Enter a number.")
print("Even number is halfed, odd number is multiplied by 3 and 1 is added to the product.")
print("This is called as Collatz sequence.")
print("Watch as your number slowly becomes 1.\nEnter a positive integer:")
try:
collatz(int(input()))
except ValueError:
print("Next time, Enter a positive integer, you dummy...")

What's wrong with my use of if / then in this script?

I'm learning if and then statements. I'm trying to write code that takes any decimal number input (like 2, 3, or even 5.5) and prints whether the input was even or odd (depending on whether the input is actually an integer.)
I get an error in line 8
#input integer / test if any decimal number is even or odd
inp2 = input("Please enter a number: ")
the_number = str(inp2)
if "." in the_number:
if int(the_number) % 1 == 0
if int(the_number) % 2 == 0:
print("Your number is even.")
else:
print("Your number is odd.")
else:
print("You dum-dum, that's not an integer.")
else:
the_number = int(inp2)
if the_number % 2 == 0:
print("Your number is even.")
else:
print("Your number is odd.")
I'm just starting with python so I appreciate any feedback.
You have to include a colon at the end of second if statement, like you did in your other conditional statements.
if int(the_number) % 1 == 0:
Next time, give a closer look at the error message. It'll give you enough hints to fix it yourself, and that's the best way to learn a language.
EOL.
You forgot a :. Line 8 should read if int(the_number) % 1 == 0:.
Try putting the : at the end of the if statement
if int(the_number) % 1 == 0:
You can test your input as following code snippet
num = input('Enter a number: ')
if num.isnumeric():
print('You have entered {}'.format(num))
num = int(num)
if num%2:
print('{} is odd number'.format(num))
else:
print('{} is even number'.format(num))
else:
print('Input is not integer number')

Collatz Sequence - Trying to fix a printed 'None' value

Complete beginner here, I'm currently reading through "Automate the Boring Stuff With Python" by Al Sweigert. I'm running into an issue where my program is returning a None value and I can't figure out how to change that.
I understand that at some point collatz(number) doesn't have a value, therefor None is returned- but I don't understand how to fix it. The book hasn't touched on yield yet. I've tried using return instead of print within the function, but I haven't been able to fix it.
def collatz(number):
while number != 1:
if number % 2 == 0:
number = number // 2
print(number)
elif number % 2 == 1:
number = 3 * number + 1
print(number)
print('Enter number:')
try:
number = int(input())
print(collatz(number))
except ValueError:
print ('Please enter an integer.')
As #chepner proposed you need to remove the print statement which is enclosing your collatz(number) call. The correct code would look like
def collatz(number):
while number != 1:
if number % 2 == 0:
number = number // 2
print(number)
elif number % 2 == 1:
number = 3 * number + 1
print(number)
print('Enter number:')
try:
number = int(input())
collatz(number)
except ValueError:
print ('Please enter an integer.')

How to bypass 1st set of conditionals

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

Categories

Resources