m = int(input("First number (0 to stop): "))
n = int(input("Second number: "))
def gcd(a, b):
while b != 0:
c = a % b
a = b
b = c
if b == 0:
break
return a
print ("The greatest common divisor of", n,"and", m, "is", abs(gcd(m,n)))
How do I break out of this while loop, when m is equal to 0.
You probably want an outer loop, judging from your input hint of (0 to stop):
def gcd(a, b):
while b != 0:
c = a % b
a, b = b, c # tuple assignment FTW!
if b == 0:
break
return a
while True:
m = int(input("First number (0 to stop): "))
if m == 0:
break
n = int(input("Second number: "))
print("The greatest common divisor of {0} and {1} is {2}".format(n, m, abs(gcd(m, n))))
Related
my goal is to sort three numbers into a, b, and c, with a being the largest, b being the middle, and c being the smallest. To do this, I'm required to write a function. However, I've tried multiple ways and haven't found a way to allow it to work.
num1 = int(input("input an integer: "))
num2 = int(input("input another integer: "))
num3 = int(input("input another integer: "))
def simple_sort(a,b,c):
if a > b and a > c:
return a
if b < a and b > c:
return b
if c < a and c < b:
return c
a,b,c=simple_sort(num1,num2,num3)
print(a,b,c)
#for it to be correct, when i do print(a,b,c), it should print num1, num2 and num3
#in ascending order
You're only returning one value (a, b, or c) where you need to return a tuple or list.
def simple_sort(a,b,c):
if a < b:
a,b = b,a
# above guarantees that a > b
if c > a:
return (c,a,b)
elif c > b:
return (a,c,b)
else:
return (a,b,c)
values = list(map(int,input("Input three integers separated by spaces: ").split()))
print(simple_sort(*values))
This is the question:
Write a Python program that reads a positive integer n and finds the
average of all odd numbers between 1 and n. Your program should not
accept a negative value for n.
And here is my code, which curiously doesn't work:
k = int(input('Enter a positive integer: '))
while k <= 0:
print('Please enter a positive integer!! \n')
k = int(input('Enter a positive integer: '))
else:
b = 1
sum1 = 0
while b <= k:
if b % 2 == 1:
sum1 = sum1+b
b += 1
avg = sum/k
print(avg)
Example: input: 8 and output: 2.5, while it should be 4. Any tips?
if we use while True, the program will run until it receives a positive number. and when we get a positive number, then we execute the instructions and turn off the loop using a break
1 version with list:
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
numbers = [i for i in range(1, n + 1) if i % 2 == 1]
print(sum(numbers) / len(numbers))
break
2 version with list:
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
numbers = []
for i in range(1, n+1):
if i % 2 == 1:
numbers.append(i)
break
print(sum(numbers)/len(numbers))
3 version with counter
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
summ = 0
c = 0
for i in range(1, n+1):
if i % 2 == 1:
summ += i
c += 1
print(summ/c)
break
You have used sum (builtin function name) instead of sum1 (your variable name) in the 2nd last line. Additionally, you need to count the total number of odd numbers and divide using that number instead of the input.
Okay I reviewed the question and here is the answer:
k = int(input('Enter a positive integer: '))
while k <= 0:
print('Please enter a positive integer!! \n')
k = int(input('Enter a positive integer: '))
else:
b = 1
sum1 = 0
c = 0
while b <= k:
if b % 2 == 1: #determines if odd
sum1 = sum1+b
c += 1 #variable which counts the odd elements
b += 1 #counter
avg = sum1/c
print(avg)
sum = int(input("Enter a positive integer: "))
Oddtotal = 0
for number in range(1, sum+1):
if(number % 2 != 0):
print("{0}".format(number))
Oddtotal = Oddtotal + number
I have this code and I'm trying to print only one message with all the results, but instead is printing each message with the result which is getting awful.
a = int(input('First Integer: '))
b = int(input('Second Integer: '))
if a < b:
for i in range(a, b + 1):
print('The Numbers in Ascending Order Are: ', i)
else:
for i in range(a, b - 1, -1):
print('The Numbers in Descending Order Are: ', i)
Don't print each item in a loop then.
Write instead.
Code
a = int(input('First Integer: '))
b = int(input('Second Integer: '))
if a < b:
print(f'The Numbers in Ascending Order Are: {list(range(a, b+1))}')
else:
print(f'The Numbers in Descending Order Are: {list(range(a, b-1, -1))}')
Output
Another approach with for loop
a = int(input('First Integer: '))
b = int(input('Second Integer: '))
if a < b:
temp = []
for i in range(a, b + 1):
temp.append(i)
print('The Numbers in Ascending Order Are: ', temp)
else:
temp = []
for i in range(a, b - 1, -1):
temp.append(i)
print('The Numbers in Descending Order Are: ', temp)
Output
First of all, print the order message before each for loop. Secondly, you can use range in the following way:
a = int(input('First Integer: '))
b = int(input('Second Integer: '))
if a < b:
print('The Numbers in Ascending Order Are: ')
for i in range(a,b + 1): # adding 1 to include b
print(i)
else:
print('The Numbers in Descending Order Are:')
for i in range(a , b - 1, -1): # reducing 1 to include b
print(i)
Input:
First Integer: 1
Second Integer: 5
Output:
1
2
3
4
5
Input:
First Integer: 5
Second Integer: 1
Output:
5
4
3
2
1
To avoid repeating the message, take it out of the for loop, like this:
a = int(input("First Integer:"))
b = int(input("Second Integer:"))
if (a < b):
print("The numbers in ascending order are:")
for number in range(a, b + 1):
print(number)
else:
print("The numbers in descending order are:")
for number in range(a, b - 1, -1):
print(number)
Sample outputs:
First Integer:5
Second Integer:2
The numbers in descending order are:
5
4
3
2
First Integer:2
Second Integer:4
The numbers in ascending order are:
2
3
4
You can sort them:
a = int(input("First Integer"))
b = int(input("Second Integer"))
c = [a,b]
if a < b:
sorted(c)
else:
sorted(c,reverse=True)
You need to correct your second loop and each message should be issued with the result of the loop instead of per item.
a = int(input('First Integer: '))
b = int(input('Second Integer: '))
asc = ", ".join([str(i) for i in range(a, b + 1)])
desc = ", ".join([str(i) for i in range(b, a - 1, -1)])
if a < b:
print(f'The Numbers in Ascending Order Are: {asc}')
print(f'The Numbers in Descending Order Are: {desc}')
Write a program to read 3 integers from the user, and calculate the sum of the integers. However, if one of the values is the same as another of the values, it should not count towards the sum.
Enter a: 3
Enter b: 3
Enter c: 3
The sum is 3
The correct answer should be 0, however I realise by my first if statement a has been reassigned to 0 and since by that point a!=c for 0!=3, I am stuck on this testcase
a = int(input("Enter a: "))
b = int(input("Enter b: "))
c = int(input("Enter c: "))
if a == b:
a = 0
b = 0
elif a == c:
a = 0
c = 0
elif b == c:
b = 0
c = 0
print("The sum is", a + b + c)
you could use collections.Counter and only count the values that appear once:
count = Counter((a, b, c))
s = sum(value for value, quantity in count.items() if quantity == 1)
print(f"The sum is {s}")
the problem with your implementation is that if a == b the other two elifs will never be executed. you need change the elifs to ifs.
then you would test a == c again (after having set a to 0). for that approach to work you would have to use temporary variables instead:
tmp_a, tmp_b, tmp_c = a, b, c
if a == b:
tmp_a, tmp_b = 0, 0
if a == c:
tmp_a, tmp_c = 0, 0
if b == c:
tmp_b, tmp_c = 0, 0
print(f"The sum is {tmp_a + tmp_b + tmp_c}")
The problem is that you reassign 0 to values that could be duplicate of other values. You first need to do the comparison between all values at the same time, and then do single comparison.
a = int(input("Enter a: "))
b = int(input("Enter b: "))
c = int(input("Enter c: "))
s = 0
if a == b and a == c:
s = 0
elif a == b:
s = c
elif a == c:
s = b
elif b == c:
s = a
else:
s = a + b + c
print("The sum is ", s)
I am trying to input 3 integers and determine if they are Fibonacci Triples. A Fibonacci Triple is three consecutive Fibonacci numbers. Can someone help me figure out where I'm going wrong. Thanks!
def fibs():
a, b = 0, 1
yield a
yield b
while True:
a,b = b, a + b
yield b
fibInput = (input("please enter 3 numbers separated by commas: "))
n, o, p = [int(i) for i in fibInput.split(',')]
#print(n,o,p) TEST
for fib in fibs():
if n == fib and o == fib and p == fib:
print("Your numbers are a fibonacci triple.")
break
if fib > n and fib > o and fib > p:
print("your numbers are not a fibonacci triple.")
break
if n == fib and o == fib and p == fib:
You're not checking whether the three numbers are consecutive Fibonacci numbers. You're checking whether they're all the same Fibonacci number.
In your loop fib has the same value.
You could write other generator for Fibonacci triples
def fib_triple():
it = iter(fibs())
a = it.next()
b = it.next()
c = it.next()
while True:
yield(a, b, c)
a, b, c = b, c, it.next()