while loop number sort counter odd vs. evens - indentation

Hi I am trying to create a program that finds evens and odd numbers. I produce a random number and then separate into odds/evens, count if odd or even and then stop the program when I have 5 more odds than evens. I have an indentation error. Can someone point me in the right direction?
evens=0
odds=0
while odds- evens >= 5:
def getrandom():
number= random.randint (1,99)
return number
digit= random.randint(1,99)
if digit %2 ==0:
evens=evens +1
print ("there are", evens, "numbers")
else:
odds = odds +1
print ("there are", odds, "numbers")

The while condition odds - evens >= 5 is false since 0 - 0 isn't greater than 5 and that's why it isn't working
import random
def getrandom():
number= random.randint (1,99)
return number
evens=0
odds=0
while odds - evens < 5:
digit = getrandom()
if digit %2 ==0:
evens=evens +1
print ("there are", evens, " even numbers")
else:
odds = odds +1
print ("there are", odds, " odds numbers")
About the indentation, the error was on the function getrandom
def getrandom():
number= random.randint (1,99)
return number

Related

Program determines how many numbers are positive, negative, or zeros

(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'm trying to sum up all the logs of the first 10 primes. Program not working

The result I'm getting after running the code in powershell is three numbers and then a freeze.
The numbers are
1.09861228867,
1.60943791243,
1.94591014906
#summing up all the logs of the first 10 primes, excluding 2.
from math import * # library imports
import math # " "
count = 1 #1-9 gives us 9 primes in total
numb = 3 #3 is the second prime number.
logy_of_prime_sum_total = 0 #sum of log of primes starts at zero
logy = 0 #first value of log is zero
while count != 10: #loops 9 times, for a total of 9 primes.
for k in range(2,numb): #from 2 up to but not including numb.
if numb%k == 0: #purpose is to skip the else if not prime.
break #break takes us out of the for/else disj.
else:
logy_of_prime_sum_total = logy+logy_of_prime_sum_total
logy = math.log(numb) #when the else activates, we are
print(logy) #dealing with a prime, getting a value
numb += 2 #the log of it, incr. numb. by two,
count += 1 #because primes have to be odd,
#increase the count
print logy_of_prime_sum_total #print the sum of all the logs after the
#while end.
The only issue you have is you are not increasing numb if numb happens to be composite. Just move numb += 2 to the end of the loop and unindent. When numb is composite, e.g. 9 (4th number) you are breaking out of the for loop and never incrementing numb (else on a for loop only executes if you don't break):
while count != 10:
for k in range(2,numb): #from 2 up to but not including prime.
if numb%k == 0:
break
else:
logy_of_prime_sum_total = logy+logy_of_prime_sum_total
logy = math.log(numb)
print(logy)
count += 1
numb += 2
print(logy_of_prime_sum_total)
Output:
1.0986122886681098
1.6094379124341003
1.9459101490553132
2.3978952727983707
2.5649493574615367
2.833213344056216
2.9444389791664403
3.1354942159291497
3.367295829986474
18.529951519569238
BTW: You need to start the count = 0 to get 10 numbers, you will currently only get 9.

How can I improve this Python code to be more efficient?

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

Testing integer error in while loop

I have ran into some problems while trying to combine while loop and ValueError.
Initially I wanted my program to add numbers together. When the sum of numbers has exceeded X, I would like my program to continue to else statement. At first I didn't focus on the fact that input could also be (for example) string.
number = 1
while number < 10:
add = int(raw_input("Enter a number to add: "))
number += add
print number
else:
print "Number is greater than 10"
I tried combining the first code with try/except and ValueError to accept integers as the only inputs. Second code will not continue to else statement when sum of numbers exceeds X. Could someone please explain why this is not working?
number = 1
while number < 10:
while True:
try:
add = int(raw_input("Enter a number: "))
number += add
print number
except ValueError:
print "Please enter a number"
else:
print "Number is greater than 10"
Thank You.
there's an extra while True: loop resulting in an infinte loop.
Remove it and your code will work fine.
Another example where while(condition) (with condition not True) leads to mistakes: you have to ensure that the loop will be entered once, sometimes by initalizing your condition artificially. I would write that instead
number = 1
while True:
try:
add = int(raw_input("Enter a number: "))
number += add
print number
if number>10:
break
except ValueError:
print "Please enter a number"
print "Number is greater than 10"

Condition for Armstrong number

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