Python Average Scores - python

Basically, I need to take input unless a negative number is entered and then print the sum of scores along with some other statistics and all. Question has now been resolved.
nums=[]
total= 0
count= 0
while x >= 0:
x = int(input("Enter a number (enter -1 to terminate): "))
if x <= 100:
total = total + x
count+=1
nums.append(x)
if x>100:
print("Invalid entry.")
x = int(input("Enter a number (enter -1 to terminate): "))
print(nums)
print("Number of scores: ", len(nums))

It looks like the 2nd input should be at the end of the while loop
while x >= 0:
if x <= 100:
total = total + x
count+=1
nums.append(x)
if x>100:
print("Invalid entry.")
x = int(input("Enter a number (enter -1 to terminate): "))
That gives the first value a chance to get processed, and means that the final -1 won't be appended

Related

Write a Python program that reads a positive integer n and finds the average of all odd numbers between 1 and n

This is the question:
Write a Python program that reads a positive integer n and finds the
average of all odd numbers between 1 and n. Your program should not
accept a negative value for n.
And here is my code, which curiously doesn't work:
k = int(input('Enter a positive integer: '))
while k <= 0:
print('Please enter a positive integer!! \n')
k = int(input('Enter a positive integer: '))
else:
b = 1
sum1 = 0
while b <= k:
if b % 2 == 1:
sum1 = sum1+b
b += 1
avg = sum/k
print(avg)
Example: input: 8 and output: 2.5, while it should be 4. Any tips?
if we use while True, the program will run until it receives a positive number. and when we get a positive number, then we execute the instructions and turn off the loop using a break
1 version with list:
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
numbers = [i for i in range(1, n + 1) if i % 2 == 1]
print(sum(numbers) / len(numbers))
break
2 version with list:
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
numbers = []
for i in range(1, n+1):
if i % 2 == 1:
numbers.append(i)
break
print(sum(numbers)/len(numbers))
3 version with counter
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
summ = 0
c = 0
for i in range(1, n+1):
if i % 2 == 1:
summ += i
c += 1
print(summ/c)
break
You have used sum (builtin function name) instead of sum1 (your variable name) in the 2nd last line. Additionally, you need to count the total number of odd numbers and divide using that number instead of the input.
Okay I reviewed the question and here is the answer:
k = int(input('Enter a positive integer: '))
while k <= 0:
print('Please enter a positive integer!! \n')
k = int(input('Enter a positive integer: '))
else:
b = 1
sum1 = 0
c = 0
while b <= k:
if b % 2 == 1: #determines if odd
sum1 = sum1+b
c += 1 #variable which counts the odd elements
b += 1 #counter
avg = sum1/c
print(avg)
sum = int(input("Enter a positive integer: "))
Oddtotal = 0
for number in range(1, sum+1):
if(number % 2 != 0):
print("{0}".format(number))
Oddtotal = Oddtotal + number

is there anything preventing my code from running after inputting a number ? ( Lothar Collatz hypothesis)

number = int(input("Enter any non-negative and non-zero integer number: "))
counter = 0
while number > 0 and number != 1:
counter = +1
if number % 2 == 0:
number = number/2
if number % 2 == 0:
number = number/5
else:
number = (number*3)+1
else:
if number % 2 == 0:
number = number/2
else:
number = (number*3)+1
print("Your number took", counter, "steps")
You need to change the counter= +1 to counter += 1, and you can change your if-else statement like this:
number = int(input("Enter any non-negative and non-zero integer number: "))
counter = 0
while number > 0 and number != 1:
counter += 1
print(number)
if number % 2 == 0:
number = number/2
else:
number = number*3+1
print("Your number took", counter, "steps")
c = int(input("Enter any non-negative and non-zero integer number:"))
step = 0
while c >1:
if c%2 == 0:
c = c/2
else:
c = 3*c + 1
step += 1
print(int(c))
print("How many steps did it take?", step)

How do I get the minimum and maximum without using min and max functions? [duplicate]

This question already has answers here:
Min and Max of a List (without using min/max function)
(11 answers)
Closed 3 months ago.
I am trying to find the maximum and minimum without using the min and max functions. But the maximum is only displaying the first number. Any help?
My code:
count = 0
total = 0.0
num = float(input("Enter the number: "))
maximum = num
minimum = num
while num = 0:
count = count + 1
total = total + num
num = float(input("Enter the number: "))
if num < minimum:
minimum = num
else:
num > maximum
maximum = num
if count == 0:
print("Invalid Entry.")
else:
print("Average Number:", round(total/count, 1))
print("Minimum Number:", minimum)
print("Maximum Number:", maximum)
You did not intended the if condition that is why it is not working
I have modified the code for getting 6 numbers one after one try this
count = 0
total = 0.0
num = float(input("Enter the number: "))
maximum = num
minimum = num
while count < 5:
count = count + 1
total = total + num
num = float(input("Enter the number: "))
if num < minimum:
minimum = num
else:
num > maximum
maximum = num
if count == 0:
print("Invalid Entry.")
else:
print("Average Number:", round(total/count, 1))
print("Minimum Number:", minimum)
print("Maximum Number:", maximum)
count = 0
total = 0.0
num = None
maximum = -float("inf")
minimum = float("inf")
# No need to do the 1st round outside the loop
while num != 0:
num = float(input("Enter the number: "))
count += 1
total += num # += is more concise
# This block needs to be in the while loop
if num < minimum:
minimum = num
if num > maximum: # elif is fine if you initialize minimum and maximumwith the 1st value of num
maximum = num
if count == 0:
print("Invalid Entry.")
else:
print("Average Number:", round(total/count, 1))
print("Minimum Number:", minimum)
print("Maximum Number:", maximum)
I'm not quite sure what you are trying to accomplish here. If your first input is anything other than 0, you will set the variables maximum and minimum to that non-zero number. You will skip the while loop and if statement. If you don't get an error, it will probably just spit out the maximum and minimum being the same number. Can you provide more detail as to what you are trying to do?
you need to check the minimum and maximum for every number. so this part must be in while loop:
if num < minimum:
minimum = num
if num > maximum
maximum = num
also while condition doesn't seem right. you are assigning 0 to num every time. you probably meant num!=0. in this case when user inputs 0 the program terminates.

How to validate data based on conditions

a = int(input("Enter mark of BIOLOGY: "))
b = int(input("Enter mark of CHEMISTRY: "))
c = int(input("Enter mark of PHYSICS: "))
sum = a + b + c
x = sum
y = 3
avg = x / y
print("Total marks = ", sum)
print("Average marks = ", avg)
I want to limit the user's input so it only accepts integers from 0 to 90.
To limit the user's input to 0 to 90, you will need to repeatedly ask the user to re-input the data until it meets the 0 to 90 criteria. You can do that by implementing a while loop and then break if the criteria is met. Here's the code:
# Data validation for the variable "a"
while True:
a = int(input("Enter mark of BIOLOGY: "))
if 0 <= a <= 90:
break
else:
print("The mark is not between 0 and 90. Please enter a new mark.")
Hope this helped.
If you are wanting to limit the sum variable, at the end of your code you could simply put an if statement checking that the variable is within the boundary..
if sum > 90:
sum = 90
elif sum < 0:
sum = 0
The following code will ensure that the user inputs the number in the specified range:
while True:
a = int(input("enter mark of BIOLOGY = "))
if 0 <= a <= 90:
break
else:
print("Invalid mark. Please try again.")
while True:
b = int(input("enter mark of CHEMISTRY = "))
if 0 <= b <= 90:
break
else:
print("Invalid mark. Please try again.")
while True:
c = int(input("enter mark of PHYSICS = "))
if 0 <= c <= 90:
break
else:
print("Invalid mark. Please try again.")
sum = a + b + c
x = sum
y = 3
avg = x / y
print("total marks = ", sum)
print("average marks = ", avg)
This will ensure the variables a, b, and c are between 0-90.

smallest, largest, and average value of n numbers input by the user

I need to create a function that will print the smallest, largest,and average of n amount of numbers inputed by user.
My function, so far, can print the average and largest value of n amount of numbers entered by user but I'm stuck on finding the smallest value.
This is what I have so far:
def main():
n = int(input("how many?"))
if (n>0):
counter=0
total=0
l_v=0
while counter<n:
x = int(input("enter next number"))
total=total+x
counter=counter+1
if x>l_v:
l_v=x
print ("the largest value is {0}".format(l_v))
print("the average is ", total/n)
else:
print("What? it is not possible to find the average, sorry ")
main()
As #Padraic mentioned, the answer that your posted to your question doesn't work for positive values, since your if-statement only checks if the min value is less that 0.
To fix this, you could just assign the first inputted value to all the variables. This way you wouldn't have to use positive and negative inf variables:
def main():
n = int(input("how many?"))
if (n>0):
counter=0
total=0
f_v = l_v = s_v = total =int (input("enter first value")) #first value
while counter<(n-1):
x = int(input("enter next number"))
total=total+x
counter=counter+1
if x<s_v: #find minimum
s_v=x
elif x>l_v: #find maximum
l_v=x
print ("the smallest value is {0}".format(s_v))
print ("the largest value is {0}".format(l_v))
print("the average is ", total/n)
else:
print("What? it is not possible to find the average, sorry ")
main()
Now your code will run without any issues:
how many?5
enter first value-1
enter next number7
enter next number0
enter next number3
enter next number2
the smallest value is -1
the largest value is 7
('the average is ', 2.2)
You could add the items to a list while the user inputs data.
When the user is done, just use min(), max(), and sum() (and maybe len()) on the list.
Keep track of the lowest number also, set the start value to float(inf) for the min and float(-inf) for the max:
if n > 0:
l_v = float("-inf")
mn_v = float("inf")
sm, counter = 0, 0
while counter < n:
x = int(input("enter next number"))
if x < mn:
mn = x
if x > l_v:
l_v = x
sm += x
counter += 1
print("the largest value is {0}".format(l_v))
print("the average is ", sm / n)
print("the min value is {}".format(mn_v))
You can also use a for loop with range:
n = int(input("how many?"))
if n > 0:
l_v = float("-inf")
mn_v = float("inf")
sm = 0
for i in range(n):
x = int(input("enter next number"))
if x < mn:
mn = x
if x > l_v:
l_v = x
sm += x
print("the largest value is {0}".format(l_v))
print("the average is ", sm / n)
print("the min value is {}".format(mn_v))
Or using a list comp:
n = int(input("how many?"))
if n > 0:
nums = [int(input("enter next number")) for _ in range(n)]
print ("the largest value is {0}".format(min(nums)))
print("the average is ", sum(nums)/ n)
print("the min value is {}".format(min(nums)))
else:
print("What? it is not possible to find the average, sorry ")
sm += x is augmented assignment which the same as doing sm = sm + x.
When verifying user input and casting you should really use a try/except to catch any exceptions:
def get_num():
while True:
try:
n = int(input("enter next number"))
# user entered valid input, return n
return n
except ValueError:
# could not be cast to int, ask again
print("Not an interger")
while True:
try:
n = int(input("how many?"))
break
except ValueError:
print("Not an interger")
if n > 0:
l_v = float("-inf")
mn_v = float("inf")
sm, counter = 0, 0
while counter < n:
x = int(input("enter next number"))
if x < mn:
mn = x
if x > l_v:
l_v = x
sm += x
counter += 1
print("the largest value is {0}".format(l_v))
print("the average is ", sm / n)
print("the min value is {}".format(mn_v))
This is what I ended up doing... Just kind of worked it out myself through trial and error.
I really appreciate the answers! Gives me a different way of looking at the problem!
Answer:
def main():
n = int(input("how many?"))
if (n>0):
counter=0
total=1
l_v=0
s_v= 0
f_v = int (input("enter first value"))
while counter<n:
x = int(input("enter next number"))
total=total+x
counter=counter+1
if x<f_v:
s_v=x
elif x>l_v:
l_v=x
print ("the smallest value is {0}".format(s_v))
print ("the largest value is {0}".format(l_v))
print("the average is ", total/n)
else:
print("What? it is not possible to find the average, sorry ")
main()

Categories

Resources