Can anybody tell me what is wrong with my code for checking whether a number is an Armstrong number?
n=input('Enter the number=')
m=n
s=0
while n>0:
d=n%10
s=s+d**3
n=n*10
if m==s:
print'The number is an Armstrong number'
else:
print'The number is not an Armstrong number'
I got the program to work eventually. Turns out I had kept typing the statement n=n/10 as n=n*10. Mistakes do happen sometimes:)
n = input('Enter the number=')
m = n
s = 0
while n>0:
d = n%10
s += d**3
n /= 10
if m==s:
print'The number is an Armstrong number'
else:
print'The number is not an Armstrong number'
sum = 0
no = int(raw_input("Enter the the number to check it is armstrong on or not :"))
pow_no = len(str(no))
check = no
print "#################Method -I Result##############"
while 0<no:
sum = sum +((no%10)**pow_no)
no = no / 10
if check == sum:
print "%s is Armstrong"%check
else:
print "%s is not Armstrong"%check
print "################Method -II Result#############"
for i in str(no):
sum = sum + (int(i)**pow_no)
if check == sum:
print "%s is Armstrong"%check
else:
print "%s is not Armstrong"%check
Related
(Edit: Using python 2.7) I’m trying to get the user to input 10 numbers and the program needs to count and determine how many are negative, positive, or zeros.
However, everytime I run the program, it doesn’t give me the right number of negative or positive (or zero) numbers
i =[]
for i in range(10)
i = input('Enter Next Number: ')
n = 0
p = 0
z = 0
if (i > 0):
p = p+1
elif (i < 0):
n = n+1
elif (i == 0):
z = z+1
print "The number of negative numbers is",n
print "The number of positive numbers is",p
print "The number of zeros is",z
As Johnny Mopp suggested in his comment, you need to declare your counters outside of the loop. If you declare them inside, they are reset at every iteration and you are only counting the last number input by the user
n = 0
p = 0
z = 0
for i in range(10):
i = input('Enter Next Number:')
if (i > 0):
p = p+1
elif (i < 0):
n = n+1
else:
z = z+1
print "The number of negative numbers is",n
print "The number of positive numbers is",p
print "The number of zeros is",z
You will also want to convert the inputs to integers. If you really wish to add them to the list you will then need to iterate through the list after gathering all of the inputs. If retaining the values in a list is not needed #Bentaye answer will work just fine.
i =[]
n = 0
p = 0
z = 0
for num in range(10):
x = int(input('Enter Next Number: '))
i.append(x)
for y in range(len(i)):
if (i[y] > 0):
p = p+1
elif (i[y] < 0):
n = n+1
elif (i[y] == 0):
z = z+1
print ("The number of negative numbers is",n)
print ("The number of positive numbers is",p)
print ("The number of zeros is",z)
I've just started to learn Python (my first dabble in coding) and this is my first time posting... I hope I'm not abusing the forum by asking this question (I'm essentially asking an expert to help me learn). Please let me know if this is frowned upon in the community.
For this assignment from a Michigan open course, I've been instructed to ask a user for input until the user enters "done", at which point the code should calculate the largest, smallest, sum, and average. In all my test-runs, it's worked fine. But I feel like there's probably a much simpler way to write this code. Can anyone offer suggestions for improvement?
largest = None
smallest = None
count = 0
sum = 0
while True:
try:
num = raw_input("Enter a number: ")
if num == "done" : break
num = float(num)
count = count + 1
sum = sum + num
avg = sum/count
if largest is None:
largest = num
if smallest is None:
smallest = num
if num < smallest:
smallest = num
elif num > largest:
largest = num
continue
except: print 'Invalid input'
print "Maximum is", int(largest)
print "Minimum is", int(smallest)
print "Count:", int(count)
print "Sum:", int(sum)
print "Average:", avg
Well there are a few things here:
you can drop the continue statement since it is the end of the loop anyway;
you can compress the if statements into if largest is None or num > largest: this will shortcircuit and make the loop smaller;
you can use x += y instead of x = x + y; and
you do not have to calculate the average inside the loop; calculating it once when the loop finishes, is enough.
So:
largest = None
smallest = None
count = 0
sum = 0
while True:
try:
num = raw_input("Enter a number: ")
if num == "done" : break
num = float(num)
count += 1
sum += num
if largest is None or num > largest:
largest = num
if smallest is None or num < smallest:
smallest = num
except: print 'Invalid input'
print "Maximum is", int(largest)
print "Minimum is", int(smallest)
print "Count:", int(count)
print "Sum:", int(sum)
print "Average:", sum/count
But in terms of big oh, you cannot improve much: calculating the sum, etc. simply require O(n) and it also costs O(n) to read the input anyway.
Furthermore some software engineering advice: don't use the blanket exception, always specify the exception you expect so:
largest = None
smallest = None
count = 0
sum = 0
while True:
try:
num = raw_input("Enter a number: ")
if num == "done" : break
num = float(num)
count += 1
sum += num
if largest is None or num > largest:
largest = num
if smallest is None or num < smallest:
smallest = num
except ValueError: print 'Invalid input'
print "Maximum is", int(largest)
print "Minimum is", int(smallest)
print "Count:", int(count)
print "Sum:", int(sum)
print "Average:", sum/count
An alternative approach to accomplish this is to store all of the inputs in a list, and then use the built-ins min(),max(),len() and sum() to find values:
num=raw_input("Enter a number: ")
nums=[]
while num!="done": #check if user has finished entering inputs
try:
nums.append(int(num)) #append the input as an integer to a list
num=raw_input("Enter a number: ") #get another input
except ValueError:
print "Invalid input"
print "Maximum is",max(nums)
print "Minimum is",min(nums)
print "Count:",len(nums)
print "Sum: ",sum(nums)
print "Average: ",sum(nums)/len(nums)
Output:
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: 5
Enter a number: 6
Enter a number: done
Maximum is 6
Minimum is 1
Count: 6
Sum: 21
Average: 3.5
I am trying to multiply the elements in the list so that they give me their total but with only using addition and subtraction. For example, a list of [1,3,6,8] will have the output 144. The code I have so far is:
numbers = [1,3,6,8]
def no_sign(numbers):
total = 0
answer = 0
for i in range(len(numbers)):
first_number = numbers[i]
print str(first_number) + ' pop'
for j in range(first_number):
#print first_number
answer = first_number + answer
print str(first_number) + ' firstnum'
print str(answer)+ " answeer "
total = total + answer
print str(total) + " total"
return total
print no_sign(numbers)
This only gives me 110, which isn't enough. Any suggestions?
Your code takes the square of each element and adds them up. Hence you are getting 1 + 9 + 36 + 64 = 110
Since you want to do same thing couple times, writing your multiplication(num1, num2) function yourself with only addition and using that when multiplying would be much better choice.
Multiplication of two numbers, as you know, is adding firstNumber to itself secondNumber of times. S you can write multiplication function like below and use it on a list.
def multiplication(num1, num2):
answer = 0
for i in range(num2):
answer += num1
return answer
numbers = [1,3,6,8]
def no_sign(numbers):
total = 1
for number in numbers:
total = multiplication(total, number)
return total
print no_sign(numbers)
I have a problem with my code that my teacher ask my to check the prime numbers but he does not allow me to use If-Else function . Here is my code:
def is_prime(n):
i = 2
while (i % n != 0):
while (n % i == 0) and ( n != i):
print("False")
break
i += 1
while (i == n):
print("True")
break
number = int(input("Please enter a certain number: "))
print(is_prime(number))
But the problem is when i print out the result, it's a little bit weird with the numbers which are not a prime number:
Please enter a certain number: 10
False
False
True
None
How would i solve this problem? I just need one answer: True or False. Thank you for your helps!!!
To be short: let your function to return a value, not to print it.
def is_prime(n):
i = 2
while (i % n != 0):
while (n % i == 0) and ( n != i):
return False
i += 1
return True
number = int(input("Please enter a certain number: "))
print(is_prime(number))
Explanation:
As soon as you find out that n is not prime (line while (n % i == 0) and ( n != i):) you return False. The function is left at this moment so you do not need break. If n is not found to be divisible by any i you return True.
The True or False is now the result of the function and you can print it or assign to a variable and use somewhere else. E.g.
x = is_prime(12) // x is False now
I wrote this python code to find any prime number, the 1st, 2nd, 1000th, etc. I ran the code and it returned this, no matter what integer I entered:
2 is the 1 prime
3 is the 2 prime
5 is the 3 prime
7 is the 4 prime
Here is the code (written in python 2.7.8):
#code to find the nth prime
def isprime(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n:
return False
# range starts with 3 and only needs to go up the squareroot of n for all odd numbers
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:
return False
return True
num_ofprimes = 0
candidate_prime = 2
final_primes = raw_input("What prime would you like to find?")
while num_ofprimes <= final_primes:
if isprime(candidate_prime) == True:
if candidate_prime == 2:
num_ofprimes = num_ofprimes + 1
print (str(candidate_prime) + " is the " + str(num_ofprimes) + " prime")
candidate_prime = candidate_prime + 1
#2 is prime
elif candidate_prime % 2 == 0:
candidate_prime = candidate_prime + 1
#if a number is even it is not prime
else:
num_ofprimes = num_ofprimes + 1
print (str(candidate_prime) + " is the " + str(num_ofprimes) + " prime")
candidate_prime = candidate_prime + 1
# checks all odd numbers to see if prime then prints out if true
print ("All done!")
Your program does not stop after it found those first few primes, but it runs into an infinite loop, generating no more output. The reason for this is that if your isprime check fails, you never increment the candidate_prime variable!
Also, as noted in comments, you should compare num_ofprimes to int(final_primes); otherwise you are comparing an int to a str, which is much like comparing apples to oranges.
Finally, you should put the check whether the number is even inside your isprime function. Not only will this make your isprime function actually return correct results for even numbers, but it will also make your code a whole deal more compact, as you no longer need all those if/elif/else blocks below your if isprime check.
In addition to tobias's important comments, you seem to be doing a lot of extra work in your script for no reason. The while loop can be simplified to:
while num_ofprimes < final_primes:
if isprime(candidate_prime):
num_ofprimes = num_ofprimes + 1
print (str(candidate_prime) + " is the " + str(num_ofprimes) + " prime")
candidate_prime = candidate_prime + 1
for num in range(3, 1000):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)