Python: simple divisibility test - python

I am trying to write a simple code that prompts users to enter two numbers to determine whether they are evenly divisible:
print 'Enter the following'
num1 = input("Integer:")
num2 = input("Integer:")
evaluation = ((num1 / num 2) / 2)
print num1, "/2", num2, "/2" = ",evaluation
I am new to Python and am seeking advice on how to tweak this code. Any help would be greatly appreciated. Thank you for your time!

You need the modulo operator
print "Enter the following"
num1 = input("Integer:")
num2 = input("Integer:")
evaluation = num1 % num2
if evaluation == 0:
print num1, "/", num2, " evenly divides"
else:
print num1, "/", num2, " does not evenly divide"

Related

Recursion output isn't printing

I'm new to python and trying to understand recursion. I'm trying to write a code where someone inputs 2 numbers (Num1, Num2). A calculation will take place until Num1 is greater than Num 2. The result of the calculation's final value should then be outputted.
This is my code:
def Recursive(Num1, Num2):
if Num1 > Num2:
return(10)
else:
if Num1 == Num2:
return(Num1)
else:
return(Num1+Recursive(Num1 * 2, Num2))
Num1=input("Enter number 1: ")
Num2=input("Enter number 2: ")
print("Final value: ", Recursive(Num1, Num2))
This is the output that comes out:
Enter number 1: 1
Enter number 2: 15
That's it. There's no output of my print statement. I'm confused as to what I'm doing wrong here and what I should do.
def Recursive(Num1, Num2):
if Num1 > Num2:
return 10
if Num1 == Num2:
return Num1
print(Num1, Num2)
return Num1 + Recursive(Num1 * 2, Num2)
Num1=int(input("Enter number 1: "))
Num2=int(input("Enter number 2: "))
print("Final value: ", Recursive(Num1, Num2))
This should be working code, the reason why your code was not working was because without the int in Num1 = int( input("") ) the program was reading the number as a string. As a result instead of getting 2 from Num1 * 2 when Num1 is 1 you got 11 as it was multiplying a string instead of an integer.
# Here is an example
a = input("Input a number: ")
b = int(input("input a number: "))
print(f"a is a:{type(a)}\n b is a:{type(b)}")
print(f"{a * 2}\n{b * 2}")
Copy the code above input the two numbers and it should give you a better understanding of what I just said.

Why is my program not printing correctly?

The explanation is below:
def displaySortedNumbers(num1, num2, num3):
smallest = num1
if num2 < smallest:
smallest = num2
if num3 < smallest:
smallest = num3
return smallest
def main():
num1, num2, num3 = eval(input("Enter three numbers seperated by commas:"))
print("The numbers are,",displaySortedNumbers(num1, num2, num3))
main()
After the three numbers are entered, the smallest number prints out but the rest of the numbers do not follow. I need the numbers to print out from smallest to largest. I'm not sure what I did wrong.
Your function is only returning the one smallest number of the provided three, you may consider using a list and sorting it instead if that works for you.
def displaySortedNumbers(num1, num2, num3):
s = ""
for c in sorted([num1, num2, num3]):
s += " " + str(c)
return s
The sorted() function takes an iterable argument and returns it sorted by a key, however in this case, if you are just sorting it in increasing order, you do not need to input a key.
In your return statement there is only ´smallest´, not the other variables.
You can store the values in a list, sort it and then return that list, just like this
def displaySortedNumbers(num1, num2, num3):
list = [num1, num2, num3]
list.sort()
return list
In your return statement, you only return one of the three numbers, the one you deem the smallest. But your function is expected to return all three numbers sorted. I'm guessing you can't use the built-in sorted() function and so you need to program the sort manually. You can do a simple bubble sort on 3 numbers by changing your function to be the following:
def displaySortedNumbers(num1, num2, num3):
if num2 < num1:
num1, num2 = num2, num1
if num3 < num2:
num2, num3 = num3, num2
if num2 < num1:
num1, num2 = num2, num1
return num1, num2, num3
This will print all three numbers, properly sorted.
If you CAN use built-in functions, you could simply say:
def displaySortedNumbers(num1, num2, num3):
return sorted((num1, num2, num3))
Try to rewrite like this:
if smallest > num2:
smallest = num2
elif smallest > num3:
smallest = num3

Python GCD algorithms without using 'define'

I need to make two different types of codes to find GCD.
I'm not allowed to use def() because I didn't learn it yet.
This is my first code. I am not supposed to use the euclid method here.
I need to input two numbers together,
and set the smaller one to 'bound'.
num1, num2 = (input("input two integers to find GCD: ")).split()
num1=int(num1); num2=int(num2)
if num1 > num2:
bound == num2
elif num1 < num2:
bound == num1
i=2
while (i <= bound) :
if (num1 % i == 0) and (num2 % i == 0):
i == GCD
i=i+1
print("The GCD for %d, %d is %d."%(num1,num2,GCD))
This is my second code. Here, I need to be using the euclid method.
I have tried my best, but I can't catch my errors.
num1, num2 = (input("input two integers to find GCD: ")).split()
num1=int(num1)
num2=int(num2)
temp=num1%num2
while (num1 != 0):
num1=num2;
num2=tmp;
tmp=num1%num2
print("The GCD for %d, %d is %d."%(num1, tmp, num2))
GCD for your first code:
Edit: You were using == instead of =
num1, num2 = (input("input two integers to find GCD: ")).split()
num1=int(num1)
num2=int(num2)
if num1 > num2:
bound = num2
elif num1 < num2:
bound = num1
i=2
for i in range(1, bound+1):
if (num1 % i == 0) and (num2 % i == 0):
gcd=i
i=i+1
print("The GCD for %d, %d is %d."%(num1,num2,gcd))
GCD for your second code without using def using euclid method:
num1, num2 = (input("input two integers to find GCD: ")).split()
num1 = int(num1)
num2 = int(num2)
while num1 != num2:
if num1 > num2:
num1 = num1 - num2
else:
num2 = num2 - num1
print(num1)

Need help finding sum and average

I can't seem to make this program to run. There's no error, there's just nothing showing up when I run it. Any help is appreciated1
#Return multiple values
def load():
name=input("enter a name")
num1=int(input("Enter num1: "))
num2=int(input("Enter num2: "))
num3=int(input("Enter num3: "))
return name, num1, num2, num3
def calc(num1, num2, num3):
sum=num1, num2, num3
avg=sum/3
return sum, avg
def output(name, num1, num2, num3, avg, sum):
print("Your name is: ", name)
print("The 3 numbers are: ", num1, num2, num3)
print('The sum is: ',sum )
print("The average is: ", avg)
def main():
name, num1, num2, num3=load()
sum, avg=calc(num1, num2, num3)
output(name, num1, num2, num3, sum, avg)
You need to call main() function, this line will probably throw an exception:
sum=num1, num2, num3
avg=sum/3
change it to:
sum=num1 + num2 + num3
avg=sum/3
As a friendly commenter noted earlier, you were not calling your main() routine (see last line). You had also mixed the sequence of sum and avg calls in the signature of output. Furthermore sum is a Python built-in function. Avoid those. I used raw_input because I'm using Python 2.x, don't let that confuse you. My use of Python 2.x is also the reason for the extra parentheses you'll see in my output.
Overall you were very close to a working solution, nice job for a Beginner!
#Return multiple values
def load():
name=raw_input("enter a name: ")
num1=int(raw_input("Enter num1: "))
num2=int(raw_input("Enter num2: "))
num3=int(raw_input("Enter num3: "))
return name, num1, num2, num3
def calc(num1, num2, num3):
sum1=num1+num2+num3 # sum is a python keyword
avg=sum1/3.0 # avoiding integer division in case you are using python 2.x
return sum1, avg
def output(name, num1, num2, num3, sum1, avg):
print("Your name is: ", name)
print("The 3 numbers are: ", num1, num2, num3)
print('The sum is: ',sum1 )
print("The average is: ", avg)
def main():
name, num1, num2, num3=load()
sum1, avg=calc(num1, num2, num3)
output(name, num1, num2, num3, sum1,avg)
main()
Output:
enter a name: Anton
Enter num1: 1
Enter num2: 2
Enter num3: 3
('Your name is: ', 'Anton')
('The 3 numbers are: ', 1, 2, 3)
('The sum is: ', 6)
('The average is: ', 2.0)

Python: How to prevent questions with negative answers being randomly generated

My task is to create a maths quiz for primary school children. this is what I have done so far:
import random
import math
def test():
num1=random.randint(1, 10)
num2=random.randint(1, 10)
ops = ['+', '-', '*']
operation = random.choice(ops)
num3=int(eval(str(num1) + operation + str(num2)))
print ("What is {} {} {}?".format(num1, operation, num2))
userAnswer= int(input("Your answer:"))
if userAnswer != num3:
print ("Incorrect. The right answer is {}".format(num3))
return False
else:
print ("correct")
return True
username=input("What is your name?")
print ("Welcome "+username+" to the Arithmetic quiz")
correctAnswers=0
for question_number in range(10):
if test():
correctAnswers +=1
print("{}: You got {} answers correct".format(username, correctAnswers))
What I now need to do is make my program only create questions with positive answers. e.g nothing like 3-10=-7
I've tried searching everywhere online but I cant find anything so I've turned to you guys for help. Any help will be appreciated :)
What I would recommend is:
#Random code...
if num1<num2:
num1, num2 = num2, num1
#Rest of program
So that 3 - 7 = -4 becomes 7 - 3 = 4
The reason I recommend doing this is that the answer would still be the same as the previous equation, just positive instead of negative, so you are still testing the same numbers.
Keep the larger number on the left of the expression, also use operator instead of eval:
from operator import add, sub, mul
def test():
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
d = {"+": add, "-": sub, "*": mul}
operation = random.choice(list(d)))
num1 = max(num1, num2)
num2 = min(num1, num2)
num3 = d[operation](num1, num2)
print("What is {} {} {}?".format(num1, operation, num2))
userAnswer = int(input("Your answer:"))
if userAnswer != num3:
print("Incorrect. The right answer is {}".format(num3))
return False
else:
print("correct")
return True
username = input("What is your name?")
print("Welcome {} to the Arithmetic quiz".format(username))
correctAnswers = sum(test() for question_number in range(10))
print("{}: You got {} answers correct".format(username, correctAnswers))
Or as #jonclements suggests sorting will also work:
num2, num1 = sorted([num1, num2])
On another note you should really be using a try/except to verify the user input and cast to an int otherwise the first value that cannot be cast to an int your program will crash.
You can choose the numbers such that num2 will be between 1 and num1 like:
num1=random.randint(1, 10)
num2=random.randint(1, num1)
or that num1 > num2:
n1=random.randint(1, 10)
n2=random.randint(1, 10)
num1 = max(n1,n2)
num2 = min(n1,n2)
i would go with the first option. no extra variables, no extra lines.
after the code that chooses the random numbers you can add this while loop:
while num3<0:
num1=random.randint(1, 10)
num2=random.randint(1, 10)
ops = ['+','-','*']
operation = random.choice(ops)
num3=int(eval(str(num1) + operation + str(num2)))
It will enter this loop every time the answer is negative. This will ensure that the answer is positive when the program quits the loop.
A change in one line should do it:
if num1 > num2:
num3=int(eval(str(num1) + operation + str(num2)))
else:
num3=int(eval(str(num2) + operation + str(num1)))

Categories

Resources