I really don't know what I am doing wrong here but whenever I run the code the output doesn't calculate the variable and only sets it to 0.0
total = 0.0
num1 = 0.0
average = 0.0
while True:
input_num = input("Enter a number ")
if input_num == 'done':
break
try:
num = float(input_num)
except ValueError:
print("Invalid Input")
continue
total = total + num
num1 = num1 + 1
average = total / num1
print("total: ", total)
print("count: ", num1)
print("average: ", average)
I got the following after running the code
[Image of code run]: (https://imgur.com/a/lEz6ibh)
Your code isn't indented properly, so the code after continue never gets executed. To get it to work, unindent the lines after continue:
total = 0.0
num1 = 0.0
average = 0.0
while True:
input_num = input("Enter a number ")
if input_num == 'done':
break
try:
num = float(input_num)
except ValueError:
print("Invalid Input")
continue
total = total + num
num1 = num1 + 1
average = total / num1
print("total: ", total)
print("count: ", num1)
print("average: ", average)
This should work.
num_list = []
while True:
input_num = input("Enter a number ")
if input_num == 'done':
total = sum(num_list)
average = total / len(num_list)
break
num_list.append(float(input_num))
print(f"Average: {average}")
print(f"Total: {total}")
print(f"num_list: {num_list}")
total = 0.0
num1 = 0.0
average = 0.0
while True:
input_num = input("Enter a number ")
if input_num == 'done':
break
try:
num = float(input_num)
total = total + num
num1 = num1 + 1
average = total / num1
except ValueError:
print("Invalid Input")
continue
print("total: ", total)
print("count: ", num1)
print("average: ", average)
Your code to calculate values should be inside the try block rather than the except block otherwise they are never executed.
Related
I want the loop to break when user inputs empty/blank and cant figure it out.
Just gives me value error.
a = 0
x = 0
while True:
num1 = int(input("Give number: "))
if num1 == "":
break
x += num1
a += 1
print("Numbers Given: ", a)
print("Sum of numbers: ",x)
a = 0
x = 0
while True:
num1 = input("Give number: ")
if num1 == "":
break
x += int(num1)
a += 1
print("Numbers Given: ", a)
print("Sum of numbers: ",x)
You can try this try-except:
a = 0
x = 0
while True:
try:
num1 = int(input("Give number: "))
except ValueError as err:
print("Empty `number`")
break
x += num1
a += 1
print("Numbers Given: ", a)
print("Sum of numbers: ",x)
Output:
Give number: 2
Give number: 3
Give number:
Empty `number`
Numbers Given: 2
Sum of numbers: 5
I'm trying to write a basic code that prompts the user for a list of numbers as separate inputs, that then identifies the largest and smallest number. If the user enters anything other than a number the code should return an "invalid input" message. The code seems to run through the two inputs once, but then the while input seems completely broken and I'm not sure where its going wrong.
largest = None
smallest = None
try:
num1 = input("Enter a number: ")
num1 = int(num1)
largest = num1
smallest = num1
while True:
num = input("Enter a number: ")
if num == "done" :
break
if num > largest:
largest = num
if num < smallest:
smallest = num
else: continue
except:
print('Invalid input')
print("Maximum is ", largest)
print("Minimum is ", smallest)
If you check your exit condition of "done" and if the input is not "done" then convert the string to an integer.
Then all the if conditions would correctly and your while loop should run.
largest = None
smallest = None
try:
num1 = input("Enter a number: ")
num1 = int(num1)
largest = num1
smallest = num1
while True:
num = input("Enter a number: ")
if num == "done" :
break
num = int(num)
if num > largest:
largest = num
if num < smallest:
smallest = num
else: continue
except:
print('Invalid input')
print("Maximum is ", largest)
print("Minimum is ", smallest)
heres a simple way to do it:
lst = []
while True:
try:
lst.append(int(input("enter a number: ")))
except:
break
print(f"max is {max(lst)}")
print(f"min is {min(lst)}")
enter a number: 10
enter a number: 22
enter a number: 11
enter a number: 22
enter a number: 4
enter a number: done
max is 22
min is 4
In addition to other corrections:
largest = None
smallest = None
try:
num1 = int(input("Enter a number: "))
largest = num1
smallest = num1
while True:
num = input("Enter a number: ")
if str(num) == "done" :
break
if int(num) > largest:
largest = num
if int(num) < smallest:
smallest = num
else: continue
except:
print('Invalid input')
print("Maximum is ", largest)
print("Minimum is ", smallest)
I am working a small practice program that will allow you to input the 3 test scores in for as many students as you'd like and at the end I would like it to calculate the average between all the students. I am able to enter all the students name and scores and it will give me back their average but when you enter "*" it only calculates the last students average and I was trying to figure out how to make it calculate all the students average from their test scores
def GetPosInt():
nameone = str
while nameone != "*":
nameone =(input("Please enter a student name or '*' to finish: "))
if nameone != "*":
scoreone = int(input("Please enter a score for " + nameone +": "))
if scoreone < 0:
print("positive integers please!")
break
else:
scoretwo = float(input("Please enter another score for "+nameone+": "))
scorethree = float(input("Please enter another score for "+nameone+": "))
testscores = scoreone + scoretwo + scorethree
avg = testscores / 3
print("The average score for",nameone,"is ",avg)
classtotal = avg
if nameone == "*":
classavg = classtotal / 3
print("The class average is: ",classavg)
# main
def main():
GetPosInt()
main()
Here's a simplified version of your code that uses lists to store data for multiple students and then displays these details at the end, and also calculates the class average (comments inlined).
def GetPosInt():
names = [] # declare the lists you'll use to store data later on
avgs = []
while True:
name = ...
if name != "*":
score1 = ...
score2 = ...
score3 = ...
avg = (score1 + score2 + score3) / 3 # calculate the student average
# append student details in the list
names.append(name)
avgs.append(avg)
else:
break
for name, avg in zip(names, avgs): # print student-wise average
print(name, avg)
class_avg = sum(avg) / len(avg) # class average
COLDSPEED sent you a solution for your question while I was working on it. If you want to see a different solution. It's here... You can put conditions for the scores.
def GetPosInt():
numberOfStudents = 0.0
classtotal = 0.0
classavg = 0.0
while(True):
nam = (raw_input("Please enter a student name or '*' to finish "))
if(nam == '*'):
print("The average of the class is " + str(classavg))
break
numberOfStudents += 1.0
scoreone = float(input("Please enter the first score for " + str(nam) + ": "))
scoretwo = float(input("Please enter the second score for " + str(nam) + ": "))
scorethree = float(input("Please enter the third score for " + str(nam) + ": "))
testscores = scoreone + scoretwo + scorethree
avg = testscores / 3.0
print("The average score for " + str(nam) + " is " + str(avg))
classtotal += avg
classavg = classtotal / numberOfStudents
def main():
GetPosInt()
main()
while True:
# main program
number = (" ")
total = 0
num1 = int(input("enter a number"))
total = total + num1
num2 = int(input("enter a number"))
total = total + num2
num3 = int(input("enter a number"))
total = total + num3
if total > 100:
print("That's a big number!")
else:
print("That's a small number.")
print(total)
while True:
answer = raw_input("Run again? (y/n): ")
if answer in y, n:
break
print("Invalid input.")
if answer == 'y':
continue
else:
print 'Goodbye'
break
Essentially I want the program to restart when the user enters 'y' as a response to 'run again?' Any help would be vastly appreciated. Thanks.
As #burhan suggested, simply wrap your main program inside a function. BTW, your code has some bugs which could use some help:
if answer in y, n: - you probably mean if answer not in ('y', 'n'):
number = (" ") is an irrelevant line
while True makes no sense in your main program
print("Invalid input.") is below a break, thus it'll never be executed
So you'll have something like:
def main():
total = 0
num1 = int(input("enter a number"))
total = total + num1
num2 = int(input("enter a number"))
total = total + num2
num3 = int(input("enter a number"))
total = total + num3
if total > 100:
print("That's a big number!")
else:
print("That's a small number.")
print(total)
while True:
answer = raw_input("Run again? (y/n): ")
if answer not in ('y', 'n'):
print("Invalid input.")
break
if answer == 'y':
main()
else:
print("Goodbye")
break
def main():
total = 0
num1 = int(input("enter a number"))
total = total + num1
num2 = int(input("enter a number"))
total = total + num2
num3 = int(input("enter a number"))
total = total + num3
if total > 100:
print("That's a big number!")
else:
print("That's a small number.")
print(total)
answer = raw_input("Run again? (y/n): ")
if answer not in ('y', 'n'):
print("Invalid input.")
if answer == 'y':
main()
else:
print 'Goodbye'
if __name__ == '__main__':
main()
You should probably add a few checks to handle cases when users enter non-number input etc.
Your code looks really messed up. Try to write some better(clean) code next time.
while True:
total = 0
num1 = int(input("enter a number"))
num2 = int(input("enter a number"))
num3 = int(input("enter a number"))
total = num1 + num2 + num3
if total > 100:
print("That's a big number!")
else:
print("That's a small number.")
print(total)
con = int(input("Run again? 1/0: "))
if con==0:
break
here is my current code:
total = 0.0
count = 0
data = input("Enter a number or enter to quit: ")
while data != "":
count += 1
number = float(data)
total += number
data = input("Enter a number or enter to quit: ")
average = total / count
if data > 100:
print("error in value")
elif data < 0:
print("error in value")
elif data == "":
print("These", count, "scores average as: ", average)
The only problem now is "expected an indent block"
I would do something cool like
my_list = list(iter(lambda: int(input('Enter Number?')), 999)) # Thanks JonClements!!
print sum(my_list)
print sum(my_list)/float(len(my_list))
if you wanted to do conditions, something like this would work
def getNum():
val = int(input("Enter Number"))
assert 0 < val < 100 or val == 999, "Number Out Of Range!"
return val
my_list = list(iter(getNum, 999)) # Thanks JonClements!!
print sum(my_list)
print sum(my_list)/float(len(my_list))
To calculate an average you will need to keep track of the number of elements (iterations of the while loop), and then divide the sum by that number when you are done:
total = 0.0
count = 0
data = input("Enter a number or enter 999 to quit: ")
while data != "999":
count += 1
number = float(data)
total += number
data = input("Enter a number or enter 999 to quit: ")
average = total / count
print("The average is", average)
Note that I renamed sum to total because sum is the name of a built-in function.
total = 0.0
count = 0
while True:
data = input("Enter a number or enter 999 to quit: ")
if data == "999":
break
count += 1
total += float(data)
print(total / count)