Cannot keep certain numbers from averaging - python-3.x

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

Related

Number Guessing game Computer Playing

I have created this game. User is giving a number from 1 to 100. Computer is trying to guess it. User is giving hint to computer to go lower or go higher. I am open for any feedback.
Thank you in advance.
import os
import random
os.system('clear')
user = int(input("Please enter a number between 1-100: "))
print("Your Number is: " + str(user))
comp_list = list(range(1,101))
comp_selection = random.choice(comp_list)
count = 0
def game(num, a = 1, b = 100):
global count
print("I have chosen " + str(num) + "\nShould I go Higher or Lower or Correct? ")
user = input("Your Selection: ")
if user == "L":
count = count + 1
low_game(a, num)
elif user == "H":
count = count + 1
high_game(num, b)
else:
print("I have guessed correctly in " + str(count) + " tries")
def low_game(old_low, new_High):
x = new_High
new_comp_list = list(range(old_low, x))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection, old_low, x)
def high_game(new_low, old_high):
x = new_low + 1
new_comp_list = list(range(x, old_high))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection,x, old_high)
game(comp_selection)
I agree, you have over complicated the game with recursive functons.
Here is a much simplified game with penalties for player who does not answer correctly
or falsifies the answer:)
import sys, random
wins = 0
loss = 0
while 1:
user = input('Please enter a number between 1-100: (return or x = quit) > ' )
if user in [ '', 'x' ]:
break
elif user.isnumeric():
user = int( user )
if user < 1 or user > 100:
sys.stdout.write( 'Number must be between 1 and 100!!\n' )
else:
low, high, count = 1, 100, 0
while 1:
p = random.randint( low, high )
count += 1
while 1:
answer = input( f'Is your number {p}? Y/N > ').upper()
if answer in [ 'Y','N' ]:
break
else:
sys.stderr.write( 'Answer must be Y or N\n' )
if answer == 'N':
if p != user:
if input( f'Is my number (H)igher or (L)ower? > ').upper() == 'H':
if user < p:
high = p - 1
else:
sys.stderr.write( f'Wrong!! Your number was lower. You loss\n' )
loss =+ 1
break
else:
if user > p:
low = p + 1
else:
sys.stderr.write( f'Wrong!! Your number higher. You loss\n' )
loss =+ 1
break
else:
sys.stderr.write( f'Cheat!! Your number is {user}!! You loss\n')
loss =+ 1
break
else:
if user == p:
sys.stdout.write( f'I guessed Correctly in {count} guesses\n' )
wins += 1
else:
sys.stderr.write( f'Cheat!! This is not your number. You loss\n' )
loss =+ 1
break
print( f'Computer won = {wins} : You lost = {loss}' )
Happy coding.
You have really overly complicated the problem. The basic process flow is to have the computer guess a number within a fixed range of possible numbers. If the guess is incorrect, the user tells the computer how to adjust the list by either taking the guessed number as the low end or the high end of the guessing range. So to accomplish this, I would do the following:
from random import randint
# Function to request input and verify input type is valid
def getInput(prompt, respType= None):
while True:
resp = input(prompt)
if respType == str or respType == None:
break
else:
try:
resp = respType(resp)
break
except ValueError:
print('Invalid input, please try again')
return resp
def GuessingGame():
MAX_GUESSES = 10 # Arbritray Fixed Number of Guesses
# The Game Preamble
print('Welcome to the Game\nIn this game you will be asked to provide a number between 1 and 100 inclusive')
print('The Computer will attempt to guess your number in ten or fewer guesses, for each guess you will respond by telling the computer: ')
print('either:\n High - indicating the computer should guess higher\n Low - indicating the computer should guess lower, or')
print(' Yes - indicating the computer guessed correctly.')
# The Game
resp = getInput('Would You Like To Play?, Respond Yes/No ')
while True:
secret_number = None
if resp.lower()[0] == 'n':
return
guess_count = 0
guess_range = [0, 100]
secret_number = getInput('Enter an Integer between 1 and 100 inclusive', respType= int)
print(f'Your secret number is {secret_number}')
while guess_count <= MAX_GUESSES:
guess = randint(guess_range[0], guess_range[1]+1)
guess_count += 1
resp =getInput(f'The computer Guesses {guess} is this correct? (High?Low/Yes) ')
if resp.lower()[0] == 'y':
break
else:
if resp.lower()[0] == 'l':
guess_range[1] = guess - 1
else:
guess_range[0] = guess + 1
if guess == secret_number:
print (f'The Computer has Won by Guessing your secret number {secret_number}')
else:
print(f'The Computer failed to guess your secret number {secret_number}')
resp = getInput('Would You Like To Play Again?, Respond Yes/No ')

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

Excluding 0's from calculations

Hi I have been asked to write a program that will keep asking the user for numbers. The average should be given to 2 decimal places and if a 0 is entered it shouldnt be included in the calculation of the average.
so far I have this:
data = input()
numbers = []
while True:
data = input()
if data == "":
break
numbers.append(float(data))
count = len(numbers)
if count > 0:
newsum = sum(numbers)
average = newsum / float(count)
print("The average is {}".format(average))
Dumb question but how do you ensure the 0's arent considered in the calculation?
Correction: you are not appending the first input to the list
Modification: added an if statement to check whether the input is '0'
data = input()
numbers = []
numbers.append(float(data))
while True:
data = input()
if data == "":
break
if data == '0':
continue
numbers.append(float(data))
count = len(numbers)
if count > 0:
newsum = sum(numbers)
average = newsum / float(count)
print("The average is {}".format(average))

not printing count or average regardless of indentation

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)

How to break my loop?

I want to have the loop add integers to the list and break when the user hits return.
How do I manage to do this?
lstScore = []
count = 0
while count >= 0:
count = int(input("Enter a score :"))
if count != int:
break
elif:
lstScore.append(int(count))
This should help you,added exception handling for int conversion errors
lstScore = []
count = 0
while count >= 0:
try:
temp = input("Enter a score :")
if(temp != ''):
count = int(temp)
else:
break
lstScore.append(int(count))
except ValueError as x:
print("value error")
break

Resources