There is no error in this code but its not printing the result. Here, what could be the problem.
# Using WHILE LOOP
num = int(input('Enter any positive integer: '))
sum1 = 0
i = 1
if num <= 0:
print('Invalid Number.')
else:
while(i < num):
if num % i == 0:
sum1 = sum1 + i
i = i + 1
if sum1 == num:
print(num, "is a perfect number")
else:
print(num, "is not a perfect number")
The problem lies here:
if num % i == 0. The == operator checks if the remainder of num/i is 0. If yes, then it updates i. But, if num % i is not 0, then it never adds anything to i. So, with each iteration, you are doing the same thing: num % i == 0.
You need to bring i = i + 1 outside if statement because i should increase regardless of whether the number is divisible or not.
Also, it is better to use i+=1. See difference between add and iadd
while(i < num):
if num % i == 0:
sum1 = sum1 + i
i = i + 1
You set if num % i == 0: i += 1, so if num % i != 0, i will not be updated. you just add else after if num % i == 0.
num = int(input('Enter any positive integer: '))
sum1 = 0
i = 1
if num <= 0:
print('Invalid Number.')
else:
while(i < num):
if num % i == 0:
sum1 = sum1 + i
i += + 1
else:
i+=1
if sum1 == num:
print(num, "is a perfect number")
else:
print(num, "is not a perfect number")
You set up an infinite while loop.
If i < num is true and num % i == 0 is false, the while loop will run infinitely. You can verify this by using a print statement inside the while loop. Like this:
while(i < num):
if num % i == 0:
sum1 = sum1 + i
i = i + 1
print('Passed the if statement')
If Passed the if statement gets printed multiple times then num % i == 0 is false and the if statement got ignored, and the while loop keeps running and ignoring the if statement again and again.
Once you figured out the problem, you could find out many solutions. I could suggest moving the incrementation of i out of the if statement so that whenever num % i == 0 results to false, i would be incremented and checked again. So the while loop could look like this:
while(i < num):
if num % i == 0:
sum1 = sum1 + i
i = i + 1
Related
I need to check if a number is Lychrel number and if not to print the number of times the loop did until it got to the palindrome, for some reason it always print 0
num = input('please enter your number ')
num = int(num)
count = 0
for i in range(1, 500):
if str(num) == str(num)[::-1]:
print(count)
exit()
else:
num = num + int(str(num)[::-1])
count += 1
print('True')
update: thanks to Vova the code is now working.
fixed code:
num = int(input('please enter your number '))
count = 0
for i in range(1, 500):
if str(num) == str(num)[::-1]:
print(count)
exit()
else:
num = num + int(str(num)[::-1])
count += 1
print('True')
It will print 0 each time when you type 1 numeric number(0..9)
When you type more than 1 numeric not mirror number for example 2,3,4 etc(10,234 etc), it will print 1
Moreover it will never print True, coz you exit() it in if statement
Try to input 23, it will print 1:
num = int(input('please enter your number '))
count = 0
for i in range(1, 500):
if str(num) == str(num)[::-1]:
print(count)
exit()
else:
num = num + int(str(num)[::-1])
count += 1
print('True')
I am a Python beginner.
I got a prime number within the specified range. However, I couldn't convert it to a list.
I also tried converting it to a string and back to a list.
import random
lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))
for num in range(lower,upper + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
Start with an empty list, and every time you find a prime number, append it to the list. Then you can print the list at the end:
nums = []
for num in range(lower,upper + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
nums.append(num)
print(nums)
Note that you only need to iterate up the square root of num, any factor beyond that can only have another factor which is less than it:
from math import sqrt
nums = []
for num in range(lower,upper + 1):
if num > 1:
for i in range(2, int(sqrt(num))):
if (num % i) == 0:
break
else:
nums.append(num)
print(nums)
I have a little thing here which checks if a number is prime or not:
num = int(input("Choose a number: "))
for i in range(2, num):
if num % i == 0:
print("Not prime")
break
else: print("prime")
What I would like to add is the output on which number the foor loop ended, so which number is the smallest divisor of num
Example: for num = 8 it would be 2. For num = 21 it would be 3
How can I implement that?
you can try this:
for i in range(2, num):
if num % i == 0:
print(num, " is Not prime")
print("Smallest devisor of num is = ", i)
break
else:
print("prime")
Im trying to make a while loop in python, but the loop keeps looping infinitely.
Here's what I have so far:
def pvalue(num):
ans = ''
while num > 0:
if 1 <= num <= 9:
ans += 'B'
num -= 1
if num >= 10:
ans += 'A'
num -= 10
return ans
I want num to be returned as ans as follows:
if num is 5, I want ans to be BBBBB
if num is 10, ans is A
if num is 22, I want ans to be AABB.
You may want to learn about the break statement.
As for your code:
def pvalue(num):
ans = ''
while num > 0:
if num >= 10:
ans += 'A'
num -= 10
else:
ans += 'B'
num -= 1
return ans
Is much better, the case when num == 9 is now handled properly
Use the break statement to get out of the loop.
def pvalue(num):
ans = ''
while num > 0:
if 1 <= num <= 9:
ans += 'B'
num -= 1
if num >= 10:
ans += 'A'
num -= 10
if num<=0:
break
return ans
I'm a beginning programmer in python and have a question about my code I'm writing:
number = int(input("Enter a random number: "))
for num in range(1, number + 1) :
for i in range(2, num) :
if (num % i) == 0 :
break
else :
print(num)
break
When I run this program I also get 9, 15 21 as output. But these are not prime numbers.
What is wrong with my code?
Thanks!
With if (num % i) == 0: you go to the else block for every num, which is not a multiply of 2, as you start i with 2, thus printing num. I got all odd numbers printed with your code.
You can use something like this:
number = int(input("Enter a random number: "))
for num in range(1, number + 1):
prime = True
for i in range(2, num):
if (num % i) == 0:
prime = False
break
if prime:
print(num)
It sets prime to False when it encounters a divisor without rest.
the trouble is in your else: statement which has to run outside of the first loop. I recommend the following:
def isprime(num):
for i in range(2, num):
if (num % i) == 0:
return False
return True
for num in range(1, number + 1) :
if isprime(num):
print num
Your problem
The else statement that you put inside the for loop means that if that number(num) is divisible by this current no represented by i, return true considering it as a prime which IS NOT CORRECT.
Suggestion
Your outer loop starts with 1 which should change to 2, as 1 is not a prime number
Solution
def fun(number):
#Not counting 1 in the sequence as its not prime
for num in range(2, number + 1) :
isPrime = True
for i in range(2, num) :
if (num % i) == 0 :
isPrime = False
break
if isPrime:
print num
fun(10)
Output
1
2
3
5
7
I am assuming the random number is the range you want the numbers to be within.
I found that the variable i is always equal to 2 in your code.This destroys the purpose of having a second for loop
Prime numbers are numbers that cannot be divisible by 2, 3 or 7, excluding 2, 3 or 7!
With this knowledge I adapted your code to show the true prime numbers.
solution
number = int(input("Enter a random number: "))
for num in range(2,number +1) :
printnum = True
if num == 2:
printnum = True
elif num == 3:
printnum = True
elif num == 7:
printnum = True
elif num % 2 == 0:
printnum = False
elif num % 3 == 0:
printnum = False
elif num % 7 == 0:
printnum = False
if printnum == True:
print(num)
This is my method to generate first ten prime numbers with no imports, just simple code with components we are learning on college. I save those numbers into list.
def main():
listaPrim = []
broj = 0
while len(listaPrim) != 10:
broj+= 1
brojac = 0
for i in range(1,100):
if broj % i == 0:
brojac += 1
if brojac == 2:
listaPrim.append(broj)
print(listaPrim)
if __name__=='__main__':
main()