I've to create a program that computes the average of a collection of values entered by the user. The user will enter 0 as a sentinel value to indicate that no further values will be provided. The program should display an appropriate error message if the first value entered by the user is 0.
Note: Number of inputs by the user can vary. Also, 0 marks the end of the
input it should not be included in the average
x = int(input("Enter Values\n"))
num = 1
count = 0
sum = 0.0
if x == 0:
print("Program exits")
exit()
while (x>0):
sum += num
count += 1
avg = (sum/(count-1))
print("Average: {}".format(avg))
You were not taking input inside while loop. You were taking input on the first line for once. So your program was not taking input repeatedly.
You may be looking for this -
sum = 0.0
count = 0
while(1):
x=int(input("Enter Values: "))
if x == 0:
print("End of input.")
break;
sum+=x;
count+=1;
if count == 0:
print("No input given")
else:
avg = sum/count;
print("Average is - ",avg)
Your code does not work because int function expect only one number.
If you insert the numbers one by one, the following code works:
num = int(input("Enter a value: "))
count = 0
sum = 0.0
if num <= 0:
print("Program exits")
exit()
while (num>=0):
sum += num
count += 1
num = int(input("Enter a value: "))
avg = (sum/count)
print(f"Average: {avg}")
Related
n=int(input("Enter a Number: "))
x=0
y=0
z=0
while(n>0):
x=n%10
y=x**3
z=z+y
n=n//10
print (z)
#The z here is the same value which I enter, yet it doesn't work.
#If I enter 407 as n, z becomes (4^3)+(0^3)+(7^3) which is 407
if (z==n):
#But even when 407==407, it just wont print the bottom statement
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
#it prints that it isn't an Armstrong number
After the while loop, n already became 4//10 which is 0, so it'll never equal z which is 407.
You will want to keep a copy of the original input for comparison.
As a general advice, use a debugger or at least print() your objects to see where the assignments went wrong.
Without using any built-in method
Armstrong number is 371 because 3**3 + 7**3 + 1**3 = 371. according this rule 123 is not Armstrong number because 1**3 + 2**3 + 3**3 is not equal to 123
def count_digit(n):
count = 0
while n > 0:
count += 1
n //= 10
return count
def is_armstrong(n):
given = n
result = 0
digit = count_digit(n)
while n > 0:
reminder = n % 10
result += reminder ** digit
n //= 10
return given == result
is_armstrong(371)
>> True
is_armstrong(123)
>> False
You can take in your initial number as a string so we can more easily convert it to a list. We can then map to create that list of ints. After we can use list comprehension to raise all int in that list to the power that is the len of our list. If the sum of this list equals our input, then we have an Armstrong number.
n = input('Enter a number: ')
nums = list(map(int, n))
raised = [i**len(nums) for i in nums]
if sum(raised) == int(n):
print('The number is Armstrong')
else:
print('The number is not Armstrong')
Expanded list comprehension:
raised = []
for i in nums:
i = i**len(nums)
raised.append(i)
print(raised)
Alternate for map:
nums = []
for i in n:
i = int(i)
nums.append(int(i))
I corrected your code:
n = int(input("Enter a Number: "))
x = 0
y = 0
z = 0
num = n
while n > 0:
x = n % 10
y = x**len(str(num))
z = z+y
n = n//10
print(z)
if (z == num):
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
But you can still do it in many ways better. Look at the code of vash_the_stampede and ggorlen.
Or:
def isArmstrong(n):
print(f"{n} is {'' if int(n) == sum(int(i)**len(n) for i in n) else 'not '}an Armstrong number")
isArmstrong(input("Please enter a number: "))
Definition: a number n is an Armstrong number if the sum of each digit in n taken to the power of the total digits in n is equal to n.
It's important to keep track of the original number n, because it'll be needed to compare against the result of z (your variable representing the sum). Since you're mutating n in your while loop, there's no grounds for comparison against your original input, so if (z==n): isn't working like you expect. Save n in another variable, say, original, before reducing it to 0.
Additionally, your code has arbitrarily chosen 3 as the number of digits in the number. For your function to work correctly for any number, you'll need a way to count its digits. One way is to convert the number to a string and take the length.
I strongly recommend using descriptive variable names which reduces the chance of confusing yourself and others. It's only apparent that z represents your sum and x your remainder by virtue of reading through the code. If the code was any longer or more complex, it could be a nightmare to make sense of.
Lastly, Python is not a particularly flexible language from a style standpoint. I recommend adhering to the style guide as best as possible to keep your code readable.
Here's a working example:
def armstrong(n):
total = 0
original = n
digits = len(str(n))
while n > 0:
total += (n % 10) ** digits
n //= 10
return total == original
if __name__ == "__main__":
while 1:
print(armstrong(int(input("Enter a Number: "))))
Output:
Enter a Number: 407
True
Enter a Number: 1234
False
Enter a Number: 23
False
Enter a Number: 8
True
Enter a Number: 371
True
Try it!
total=0
def Armstrong(n):
m=list(n)
global total
for i in m:
total+=pow(int(i),len(n))
if total==int(n):
print ("it is Armstrong number")
else:
print("it is not Armstrong number")
Armstrong(input("enter your number"))
print(total)
I want the sum of all prime numbers till 2 million. My program logic is correct but it takes too much time with 2 million. How can I make it faster?
num_l=[]
y = int(input("enter till what number do you want the sum"))
for count in range(0,y):
num_l.append(count)
total = 0
for counter in range(0,y):
num = num_l[counter]
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
total = total + num
print(total)
just use a function to check that it is prime or not and if it is then add it to a counter (for total). The code below takes about 20 seconds to find what you want.
One more thing is that your algorithm for testing if a number is prime or not is having a long range of numbers to go through you don't need to test to the last number you just need to go through for a range of square root of the number.
import time
def is_prime(n):
if n == 1:
return False
elif n == 2:
return True
else:
for i in range(2, int(n**0.5)+1): # this range is just enough
if n % i == 0:
return False
return True
counter = 0
start = time.time()
for i in range(1, 2*10**6): # you can change this range for taking it as input
if is_prime(i):
counter += i
print(counter)
print(time.time() - start)
I want to take two input. The program must accept only valid scores (a score must fit in the range [0 to 10]). Each score must be validated separately. If the input is not valid, I want to print "Wrong input".
After taking two valid input, I want to print sum of the values.
count = 0
count2 = 0
while True:
a = float(input())
if 0 <= a <= 10:
count2 += a
count2 += 1
b = float(input())
if 0 <= b <= 10:
count2 += b
count += 1
else:
print('Wrong input')
if count == 2:
break
print('Sum = {}'.format(count2))
Sample input:
-3.5
3.5
11.0
10.0
Output:
Wrong input
Wrong input
sum = 13.5
By taking two while loops you can easily verify each input individually till you get the expected value.
while True:
a = float(input())
if 0<=a<=10:
break
else:
print('Wrong Input')
while True:
b = float(input())
if 0<=b<=10:
break
else:
print('Wrong Input')
print("sum =", a+b)
Can anyone tell me why when I input 1, 2, 3, and 4 into this code, my output is 6, 2, 3.00? I thought that every time my while loop evaluated to true it would increment the count by one, but the output is not making sense. It's taking the total of 3 of the numbers, but only 2 for the count? I'm probably just overlooking something so an extra pair of eyes would be awesome.
def calcAverage(total, count):
average = float(total)/float(count)
return format(average, ',.2f')
def inputPositiveInteger():
str_in = input("Please enter a positive integer, anything else to quit: ")
if not str_in.isdigit():
return -1
else:
try:
pos_int = int(str_in)
return pos_int
except:
return -1
def main():
total = 0
count = 0
while inputPositiveInteger() != -1:
total += inputPositiveInteger()
count += 1
else:
if count != 0:
print(total)
print(count)
print(calcAverage(total, count))
main()
The error with your code is that on this piece of code...
while inputPositiveInteger() != -1:
total += inputPositiveInteger()
You first call inputPositiveInteger and throw out the result in your condition. You need to store the result, otherwise one input out of two is ignored and the other is added even if it is -1.
num = inputPositiveInteger()
while num != -1:
total += num
count += 1
num = inputPositiveInteger()
Improvements
Although, note that your code can be significantly improved. See the comments in the following improved version of your code.
def calcAverage(total, count):
# In Python3, / is a float division you do not need a float cast
average = total / count
return format(average, ',.2f')
def inputPositiveInteger():
str_int = input("Please enter a positive integer, anything else to quit: ")
# If str_int.isdigit() returns True you can safely assume the int cast will work
return int(str_int) if str_int.isdigit() else -1
# In Python, we usually rely on this format to run the main script
if __name__ == '__main__':
# Using the second form of iter is a neat way to loop over user inputs
nums = iter(inputPositiveInteger, -1)
sum_ = sum(nums)
print(sum_)
print(len(nums))
print(calcAverage(sum_, len(nums)))
One detail worth reading about in the above code is the second form of iter.
I have to make a program that allows the user to enter grades until they enter a negative, and then output the number of passing grades and failing grades with the average. we aren't allowed to use the list function.
maxgrade = 100
mingrade = 0
passing = 0
failing = 0
while True:
try:
grade = int(input("Enter a grade: "))
if 100 >= grade > 60:
passing += 1
elif grade <= 60:
failing += 1
if grade < 0:
print("Invalid")
if grade < mingrade:
mingrade = grade
if grade > maxgrade:
maxgrade = grade
total == grade
count = passing + failing
avg = total/count
print("Average: ", avg)
print("# Passing: ", passing)
print("# Failing: ", failing)
except:
print("Invalid")
break
First, as I mentioned in the comment, your usage of try and except is incorrect. Try and except are used in tandem to prevent errors from occurring. In your case however, I doubt that try and except is even needed. See below code for the workaround.
You also need to take into account your logic and code execution order. The following annotated code will work as specified.
# Assume the lowest and highest possible for max and min grades, respectively
max_grade = 0
min_grade = 100
grade_sum = 0
passing_count = 0
failing_count = 0
# Loop sentinel
running = 1
# Main loop
while running:
# Input validation sentinel
invalid_input = 1
# Input validation loop
while invalid_input:
grade = input("Enter a grade: ")
if grade.isnumeric():
grade = int(grade)
invalid_input = 0
else:
print("Please enter a number!")
# Increment number of passing or failing grades
if 100 >= grade > 60:
passing_count += 1
elif 60 >= grade >= 0:
failing_count += 1
else:
running = 0
# Update grade_sum
grade_sum += grade
# Update min_grade and max_grade
if grade < min_grade:
min_grade = grade
if grade > max_grade:
max_grade = grade
# Calculate grade average
grade_avg = grade_sum / (passing_count + failing_count)
# Print results
print("Average: ", grade_avg)
print("# Passing: ", passing_count)
print("# Failing: ", failing_count)