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')
Related
I'm trying to solve the scenario with these conditions:
Ask the user to enter a number
Count up from 1 to the number that the user has entered, displaying each number on its own line if it is an odd number. If it is an even number, do not display the number.
If the user enters a number that is 0 or less, display error
My codes are as follows and I can't seem to satisfy the <= 0 print("error) condition:
num=int(input("Enter number: "))
for x in range(num):
if x % 2 == 0:
continue
print(x)
elif x<=0:
print("error")
Your solution will be :
num=int(input("Enter number: "))
if num <= 0:
print("Error")
else:
for i in range(1, num + 1):
if i % 2 == 0:
continue
print(i)
You need to print the error before looping from 1 to num because if the value is less the 0 then the loop won't run. I hope you understand.
You have to check the condition num <= 0 as soon as the user enters the number:
num = int(input("Enter number: "))
if num <= 0:
print("error")
else:
for x in range(num):
if x % 2 == 0:
continue
print(x)
I'm trying to make a lucky number counter where if there is a number containing either a 6 or an 8 between the two inputs the number is lucky, but if there's both a 6 and an 8 the number is unlucky. I'm having an issue where it's double-counting numbers, like 66, 88, etc., and not calling unlucky numbers like 68, 86, etc. Please help fast :\
l, h = [int(x) for x in input().split()]
count = 0
for i in range(l,h+1):
i = str(i)
for j in range(len(i)):
if i[j] == '6' or i[j] == '8':
count += 1
print(count)
Try this:
import sys
temp1 = ""
while len(temp1) != 2:
temp1 = input("Enter 2 digits: ")
try:
temp2 = int(temp1)
except ValueError:
print("You did not enter valid input")
sys.exit(1)
lucky = False
if "6" in temp1:
lucky = True
if "8" in temp1:
lucky = True
if ("6" in temp1) and ("8" in temp1):
lucky = False
print("Lucky number: "+str(lucky))
Something like this, probably:
number = ''
while len(number) != 2 or any(ch not in '0123456789' for ch in number):
number = input('Enter a 2-digit positive integer:')
print(f'{number} is {"lucky" if ("6" in number) != ("8" in number) else "not lucky"}')
# or, if you meant to say "exactly one 6 or 8":
print(f'{number} is {"lucky" if len([ch for ch in number if ch in "68"]) == 1 else "not lucky"}')
You could try using the count() method for Strings:
numbers = input().split(' ')
count = 0
for num in numbers:
if num.count('6') > 0:
if num.count('8') > 0:
continue
else:
count += 1
elif num.count('8') > 0:
count += 1
print(count)
this, while not as elegant or efficient, seems to be the correct code for the implied question
l, h = [int(x) for x in input().split()]
count = 0
for i in range(l,h+1):
i = str(i)
if ('6' in i and '8' in i):
continue
if i.count('6') > 0 or i.count('8') > 0:
count += 1
print(count)
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
My goal is to build a programm, that says is a number prime or not.
A positive whole number n > 2 is prime if no number between 2 and sqrt(n)
divides n.
Here is my code:
import math
def main():
print("Prime number or not")
try:
N = -1
while N<2:
print("Error!Enter numbers greater than two")
N = int(input("Enter the right number:"))
values = list(range(2,round(math.sqrt(N))))
for i in values:
if i%N !=0:
continue
x = print("The number is not prime")
elif i%N ==0:
break
x = print("The number is NOT prime")
print(x)
except ValueError:
print("Error!Print correct number")
except NameError:
print("Error!Print the numbers")
main()
But is shows a syntax error in line
elif i%N ==0:
Please, give me some advice how to correct this error and about the code in general. I am new in learning Python, so any help and critic will be good!
Thanks.
If you wanted this to be your whole programme, here is my solution:
# Get num
num = input('Input a whole number: ')
# Is num valid
try:
num = int(num)
if num < 1 or num > 1000000000000:
print('Your field cannot be greater than one quantillion or less than one.')
else:
# Is num 2 or 5, if yes, prime.
if num != 2 and num != 5:
# Is the last number of num 0, 2, 4, 5, 6, or 8, if yes, composite.
lastNum = str(num)[-1]
if lastNum == '0' or lastNum == '2' or lastNum == '4' or lastNum == '5' or lastNum == '6' or lastNum == '8':
print('Your number is composite.')
if lastNum == '5':
print(str(num) + ' is divisible by 5.')
else:
print(str(num) + ' is divisible by 2.')
else:
# List multiples of 3 less than 123, call it multiplesOf3.
multiplesOf3 = []
appendMultiple = 0
for i in range(40):
appendMultiple += 3
multiplesOf3.append(appendMultiple)
# Get sum of all numbers in num, name is sumOfNum
sumOfNum = 0
numStr = str(num)
for i in range(len(numStr)):
sumOfNum += int(numStr[i])
# Is sumOfNum in multiplesOf3?
numMultipleOf3 = sumOfNum in multiplesOf3
if numMultipleOf3 == True:
print('Your number is composite.\n' + str(num) + ' is divisible by 3.')
else:
print('Your number is prime.')
else:
print('Your number is prime')
except:
print('Your field needs to be a whole number. Make sure there is no decimal points (i.e. 12.0 will not be accepted).')
But if you wanted this to be just a function, here is my solution (Make sure you put in a parameter, it requires 1 argument; put in your number.)
def isPrime(num):
try:
num = int(num)
if num < 1 or num > 1000000000000:
print('Your field cannot be greater than one quantillion or less than one.')
else:
# Is num 2 or 5, if yes, prime.
if num != 2 and num != 5:
# Is the last number of num 0, 2, 4, 5, 6, or 8, if yes, composite.
lastNum = str(num)[-1]
if lastNum == '0' or lastNum == '2' or lastNum == '4' or lastNum == '5' or lastNum == '6' or lastNum == '8':
print('Your number is composite.')
if lastNum == '5':
print(str(num) + ' is divisible by 5.')
else:
print(str(num) + ' is divisible by 2.')
else:
# List multiples of 3 less than 123, call it multiplesOf3.
multiplesOf3 = []
appendMultiple = 0
for i in range(40):
appendMultiple += 3
multiplesOf3.append(appendMultiple)
# Get sum of all numbers in num, name is sumOfNum
sumOfNum = 0
numStr = str(num)
for i in range(len(numStr)):
sumOfNum += int(numStr[i])
# Is sumOfNum in multiplesOf3?
numMultipleOf3 = sumOfNum in multiplesOf3
if numMultipleOf3 == True:
print('Your number is composite.\n' + str(num) + ' is divisible by 3.')
else:
print('Your number is prime.')
else:
print('Your number is prime')
except:
print('Your field needs to be a whole number. Make sure there is no decimal points (i.e. 12.0 will not be accepted).')
Another way,
def isprime(n):
if min(n//2,n//3,n//5) == 1:
return True
elif min(n%2,n%3,n%5) == 0:
return False
return True
This is SO much shorter!
assuming that the indentation on the question is correct NOW, the problem is that your elif block doesn't have an if parent. It's also indented wrong, which even if you fix the first error will throw an IndentationError but that's almost beside the point.
for i in values:
if i%N !=0:
continue
x = print("The number is not prime") # huh? you've left the `if` block
elif i%N ==0: # under-indented
break
Maximum, minimum and total numbers using python. For example:
>>>maxmin()
Enter integers, one per line, terminated by -10 :
2
1
3
7
8
-10
Output : total =5, minimum=1, maximum = 8
Here is my code. I need some help with this.
def maxmin():
minimum = None
maximum = None
while (num != -10):
num = input('Please enter a number, or -10 to stop: ' )
if num == -10:
break
if (minimum) is None or (num < minimum):
minimum = num
if (maximum) is None or (num > maximum):
maximum = num
print ("Maximum: ", maximum)
print ("Minimum: ", minimum)
def maxmintotal():
num = 0
numbers = []
while True:
num = int(input('Please enter a number, or -10 to stop: ' ))
if num == -10:
break
numbers.append(num)
print('Numbers:', len(numbers))
print('Maximum:', max(numbers))
print('Minumum:', min(numbers))
I would do this:
def maxmin():
minimum = None
maximum = None
while True:
num = input('Please enter a number, or -10 to stop: ')
if num == -10:
break
if (minimum) is None or (num < minimum):
minimum = num
if (maximum) is None or (num > maximum):
maximum = num
print ("Maximum: ", maximum)
print ("Minimum: ", minimum)
maxmin()
See, you're not really conditioning your while loop aroud num != -10 since you check for that within the loop and break out of it. So, there will never be a time when num=-10 at the beginning of the loop, make sense?
So, you just loop forever (The while True) until someone inputs a -10
You have to define num before you use it in the while, also your nested if should be out of the other if:
def maxmin():
minimum = None
maximum = None
num = None
while True:
num = input('Please enter a number, or -10 to stop: ')
if num == -10:
break
if (minimum) is None or (num < minimum):
minimum = num
if (maximum) is None or (num > maximum):
maximum = num
print ("Maximum: ", maximum)
print ("Minimum: ", minimum)
maxmin()
This function should give you the output that you want:
def maxmin():
minimum, maximum, total = None, None, 0
while(True):
number = input('Please enter a number, or -10 to stop: ')
num = int(number)
if num == -10:
break
if total == 0:
minimum, maximum, total = num, num, 1
continue
total += 1
if num < minimum:
minimum = num
elif num > maximum:
maximum = num
print("Output : total ={}, minimum={}, maximum ={}".format(total, minimum, maximum))