Need help on python programming - python-3.x

I'm trying to write a program that calculated the average number and determine the maximum + minimum number from user's input. I followed instructor's guideline but at the end, it messed up and I have no idea which step I did wrong. Please take a look and give me some suggestion, thank you.
MAX_PINTS = 256
def valid_real(value):
try:
if float(value) >= 0:
return True
if float(value) < 0:
return False
except ValueError:
return False
def get_real(prompt):
value = ""
value = input(prompt)
while not valid_real(value):
print(value, "is not a valid number. Please try again.")
value = input(prompt)
return float(value)
def y_or_n(prompt):
value = ""
value = input(prompt)
while True:
if value == "Yes" or value == "yes":
return True
elif value == "No" or value == "no":
return False
else:
print("Please enter yes or no!")
value = input(prompt)
def get_pints_collected(pints_collected):
done = False
counter = 0
while not done:
for turn_counter in range (7):
pints_collected[counter] = get_real("Please enter your collected pints: ")
counter = counter + 1
done = y_or_n("Do you want to end program? (Enter yes or no)")
return counter
def calculate_pints_average(pints_collected):
total = 0
minimum = pints_collected[0]
maximum = pints_collected[0]
for i in range (7):
total = total + pints_collected[i]
if pints_collected[i] > maximum:
maximum = pints_collected[i]
if pints_collected[i] < minimum:
minimum = pints_collected[i]
pints_average = total / 7
def output(pints_average, maximum, minimum):
pints_average = 0
maximum = 0
minimum = 0
print ("The average number of pints donated is: ", pints_average)
print ("The highest pints donated is: ", maximum)
print ("The lowest pints donated is: ", minimum)
def final():
pints_collected = [0.0 for x in range (MAX_PINTS) ]
pints_average = 0.0
number_pints_collected = 0
maximum = 0.0
minimum = 0.0
pints_collected = get_pints_collected(pints_collected)
pints_average = calculate_pints_average(pints_collected)
output(pints_average, maximum, minimum)
final()

Related

Counting weighted average doesn't work properly sometimes

I've made a program that counts weighted average and required weighted value to average being equal to our preference. If I want the average be equal to 85 from (the first value in the list is the weight of next values) [[4,72,78],[3,56],[6,93]] and x value of 6 weight it does not output the right value.
def choice(x):
c = 0
Choice = True
choices = []
while Choice:
if choices == []:
if x != 0:
fill = "weight of required value"
else:
fill = "weight of next values"
else:
if x != 0:
fill = "value of wanted weighted average"
else:
fill = "value"
try:
c = input("Give {}\n" .format(fill))
except:
continue
if isinstance(c, str):
if c == "":
Choice = False
if choices == []:
choices = False
break
else:
try:
choices.append(float(c))
except:
continue
if x != 0 and len(choices) == x:
break
c = 0
return choices
def av(x):
c = 0
alist = x[:]
alist.pop(0)
for a in alist:
c += a*x[0]
return c
def average(k,args):
c = 0
n = 0
for y in range(len(args)):
for a in range(len(args)):
c += (av(args[a]))/2
for b in range(len(args)):
n += (args[b][0]*(len(args[b])-1))/2
if k == 1:
return ([float("{0:.2f}".format(c/n)),c,n])
else:
j = float("{0:.2f}".format(c/n))
print("Weighted average {} from {}" .format(j,args))
def rmark(q,args):
alist = average(1,args)
a = float("{:.2f}" .format((((q[1]*(alist[2]+q[0]))-alist[1])/q[0])))
print("To get weighted average {}, u have to add the value equal to {} of weight {}" .format(q[1],a,q[0]))
# return a
Continue = True
list_choices = []
while Continue:
x = 0
x = choice(0)
if isinstance(x, list):
list_choices.append(x)
elif x == False:
break
print(list_choices)
rmark(choice(2),list_choices)
average(0,list_choices)
Let me break it down for you.
av function is reducing the size of your lists (x1, x2 and x3) to 1 by popping (alist.pop(0)) one element.
Hence, value of len(x1)-1 is 0, which means value of all multipliers in the denominator of (av(x1) + av(x2) + av(x3))/((x1[0]*(len(x1)-1)) + (x2[0]*(len(x2)-1)) + (x3[0]*(len(x3)-1))) is 0. Thus, the error divide by zero.

Find average of given numbers in input

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}")

Local variable 'result ' value is not used even though I am assigning values to it, can any tell why is 'result' unused

my result variable is unused, even though I am assigning values to it, can any tell why is 'result' unused
def caught_speeding(speed, is_birthday):
if speed in range(0, 61):
result = 0
elif speed in range(61, 81):
if is_birthday == True:
result = 0
else:
result = 1
elif speed >= 81:
if is_birthday == True:
result = 0
else:
result = 2
else:
result = None
caught_speeding(60, False)
caught_speeding(65, False)
caught_speeding(65, True)
Modify to return the result:
def caught_speeding(speed, is_birthday):
if speed in range(0, 61):
result = 0
elif speed in range(61, 81):
if is_birthday == True:
result = 0
else:
result = 1
elif speed >= 81:
if is_birthday == True:
result = 0
else:
result = 2
else:
result = None
return result

Python - track inputs

I am having difficulty keeping a track of the total number of inputs. I want my program to keep track of the total number of inputs and print it when my while loop breaks. Any help is appreciated!
r = float(input("enter r:"))
def main(r):
a = 3.14 * (float(r ** 2))
s_v = 0
total = 0
while True:
r = float(input("enter r:"))
if r == sentinal_value:
total += r
print("Total = " , total)
break
else:
print("Area = ", a)
continue
main(r)
I assume that you want your program to re-calculate the area with each iteration. As written, it will only be calculated the first time you run the mymian function. You don't need to pass any arguments to the function.
def mymian():
sentinal_value = 0
total = 0
while True:
r = float(input("enter r:"))
if r == sentinal_value:
print("Total number of r provided to this program" , total)
break
else:
print("Area = ", 3.14 * (float(r ** 2)))
total += 1
continue

Cannot keep certain numbers from averaging

I need help. I'm trying to run the program below. When I enter a number above 100 or below 0 I need it to disregard that input any advice?
total = 0.0
count = 0
data = int(input("Enter a number or 999 to quit: "))
while data != "":
count += 1
number = float(data)
total += number
data = int(input("Enter a number or 999 to quit: "))
try:
data = int(data)
except ValueError:
pass
average = round(total) / count
if data == 999:
break
elif data >= 100:
print("error in value")
elif data <= 0:
number = 0
print("error in value")
print("These", count, "scores average as: ", round(average, 1))
You could move the average = ... line behind the checking for invalid numbers and add continue to the checks for invalid numbers. So the last lines would end up like this:
if data == 999:
break
elif data >= 100:
print("error in value")
continue
elif data <= 0:
print("error in value")
continue
average = round(total) / count

Resources