Invalid Syntax Error - Average Calculator "IF" and "WHILE" - python

I have no idea what I'm doing wrong, but this is driving me up a wall. Why am I getting a Syntax error? I have to code an average calculator using a while statement, where "0" defines that the program needs to perform the calculation.
Here's the sample output my professor defined:
SAMPLE RUN
Enter test score 80
Enter test score 70
Enter test score 90
Enter test score 88
Enter test score 0
The average is 82.000%

The if statement in the image (please post the actual code in your question) is invalid. It needs a colon, i.e. if test == '0':. It also needs a body.
The sample output suggests that 0 is to terminate the loop. Check for that first, before you modify division_integer otherwise the average will be affected. Then, when you get a 0 break out of the while loop with break, i.e.
while True:
test = int(input('Enter test score:'))
if test == 0:
break
addition_integer += test
division_integer += 1
Note that you are converting the input into an integer, but your test was for the string "0". You need to test for the integer 0 as I show above.
Another point, you should use a try/except block when converting the input into an integer so that you can catch invalid input:
while True:
try:
test = int(input('Enter test score:'))
except ValueError:
print('Invalid number entered, try again.')
continue
# etc.

I've fixed your code for you. For future questions, please post your code directly in your question and indent it all by 4 spaces to properly format it.
addition_integer = 0
divison_integer = 0
while True:
test = int(input("Enter test score: "))
if test == 0:
break
else:
addition_integer += test
divison_integer += 1
print("The average is {}%".format(addition_integer/divison_integer))
Here's an explanation of what I did to fix this:
You were looping while True, which is correct, however you had no way to break out of the while loop. Your line saying if test == '0' would never resolve to true because you're taking the input as an int from the user, not to mention it was out of place and didn't have proper syntax.. What I am doing in the code above is continuing to loop until the input from the user is equal to 0 (an integer, not a string). If the user inputs 0, then we simply break out of the loop and print the average. Until then, we continue to add the input to addition_integer and increment division_integer by 1.
All in all, you were pretty close to the solution, you just needed a few syntax changes and to be steered in the right direction as to how you can break out of an infinite loop.
Finally, here is a test using the numbers that you've provided in your question:
Enter test score: 80
Enter test score: 70
Enter test score: 90
Enter test score: 88
Enter test score: 0
The average is 82%

Alternative answer
Use a list, sum and divide. Same concept, compare test inside the while loop in order to break out of it. Also check if you get valid input that can be made an integer with a try/except.
Additionally, beware of the division by zero
values = []
while True:
try:
test = int(input('Enter test score:'))
if test == 0:
break
values.append(test)
except:
break
total = len(values)
avg = 0 if total == 0 else 1.0 * sum(values) / total
print("The average is", avg)

Related

Keep asking for numbers and find the average when user enters -1

number = 0
number_list = []
while number != -1:
number = int(input('Enter a number'))
number_list.append(number)
else:
print(sum(number_list)/ len(number_list))
EDIT: Have found a simpler way to get the average of the list but if for example I enter '2' '3' '4' my program calculates the average to be 2 not 3. Unsure of where it's going wrong! Sorry for the confusion
Trying out your code, I did a bit of simplification and also utilized an if statement to break out of the while loop in order to give a timely average. Following is the snippet of code for your evaluation.
number_list = []
def average(mylist):
return sum(mylist)/len(mylist)
while True:
number = int(input('Enter a number: '))
if number == -1:
break
number_list.append(number)
print(average(number_list));
Some points to note.
Instead of associating the else statement with the while loop, I revised the while loop utilizing the Boolean constant "True" and then tested for the value of "-1" in order to break out of the loop.
In the average function, I renamed the list variable to "mylist" so as to not confuse anyone who might analyze the code as list is a word that has significance in Python.
Finally, the return of the average was added to the end of the function. If a return statement is not included in a function, a value of "None" will be returned by a function, which is most likely why you received the error.
Following was a test run from the terminal.
#Dev:~/Python_Programs/Average$ python3 Average.py
Enter a number: 10
Enter a number: 22
Enter a number: 40
Enter a number: -1
24.0
Give that a try and see if it meets the spirit of your project.
converts the resulting list to Type: None
No, it doesn't. You get a ValueError with int() when it cannot parse what is passed.
You can try-except that. And you can just use while True.
Also, your average function doesn't output anything, but if it did, you need to call it with a parameter, not only print the function object...
ex.
from statistics import fmean
def average(data):
return fmean(data)
number_list = []
while True:
x = input('Enter a number')
try:
val = int(x)
if val == -1:
break
number_list.append(val)
except:
break
print(average(number_list))
edit
my program calculates the average to be 2 not 3
Your calculation includes the -1 appended to the list , so you are running 8 / 4 == 2
You don't need to save all the numbers themselves, just save the sum and count.
You should check if the input is a number before trying to convert it to int
total_sum = 0
count = 0
while True:
number = input("Enter a number: ")
if number == '-1':
break
elif not number.isnumeric() and not (number[0] == "-" and number[1:].isnumeric()):
print("Please enter numbers only")
continue
total_sum += int(number)
count += 1
print(total_sum / count)

A program that uses while loop to find average of numbers inputted, and uses a break statement to exit the loop

I would like to write a program that uses a while loop to repeatedly prompt the user for numbers and adds the numbers to a running total. When a blank line is entered, the program should print the average of all the numbers entered. I also would like to use a break statement to exit the while loop.
My Incorrect Work:
y = "\n"
total = 0
k = 0
while True:
x = input("Enter your number here: ")
x = float(x)
total = total + float(x)
k = k + 1
if type(x) != int:
print(total/k)
break
Be aware that the function input() will always outputs a string, so type(input()) != int will always be true.
Try using try-except function, when there is ValueError (example unable to convert blank/letters to float), the exception will be raised and break the loop:
total = 0
k = 0
while True:
x = input("Enter your number here: ")
try:
total += float(x)
k += 1
except ValueError:
if k > 0: #to avoid division by zero
print("Average: ", total/k)
break
Output:
Enter your number here: 3
Enter your number here: 4
Enter your number here: 5
Enter your number here:
Average: 4.0
Bearing in mind the comments already made, here is one such way to perform your task and finishing up when a blank entry is encountered.
total = 0.0
k = 0.0
while True:
x = input("Enter your number here: ")
if (x == " "): # Check for a blank line entry here before attempting to convert to float
print("Average is:", (total/k))
break
x = float(x)
total = total + float(x)
k = k + 1
As noted in the comments, one should check for the blank line entry prior to attempting to convert the entry.
You are immediately casting the value of x that is inputted to a float. So,
if type(x) != int
always is true, meaning the loop breaks after one iteration every time.
Others have already solved your problem in different ways, but I think that explaining our thinking might also be useful.
Currently, your program is not checking correclty the exit condition (empty line is entered instead of a number). When a new line is entered, your program should do one of the two possible scenarios:
when an empty line is entered: print result & exit (break)
else (assume a number is entered): add number to total
No third option is specified, so for now, let's assume that every line will either be an empty line or a number. Will expand it later.
After you decided what to do, the actions should just be easily wrapped in a while True: block - so it should be:
initialize_variables_total_and_count
while True:
read_line
decide_what_to_do:
# in case line was a number
convert_line_to_float
add_float_to_total
increment_count
other_case:
# empty line was entered
calculate_and_print
break
With only two options, you only need to decide once what to do. You can swap around the cases by deciding which condition to check for (and that also results in the other being the "default" behavior for other cases).
It's simpler to check for the line being empty with if line_entered == "":. In this case, any non-empty line is treated like a number, and if it were not one, the float() function will error out and your program crashes.
Checking if a string (the entered line) can be converted to a float is a bit harder. There is just no built-in for that in python, but there is a trick: you can try to convert it to a float, and if that works, it was convertible, and if that errors, it was not. There are other ways too, but this is the simplest - see this question on the topic.
In this case, every number will be added to the total, and every non-number (including the empty line, but also random strings like "asdf") will cause the program to calculate the total and stop.
You can avoid putting both cases into an if-else block by using break or continue. (technicly, you never need to use break or continue, all programs can be written without them. In this case, you could have a boolean variable, named run for example, write while run: and instead of break, do run = False). You can use the fact that both break and continue end the loop early to avoid placing the second case inside an else-block and still have the same behavior (as break and continue already causes skipping the rest of the loop body).
So an example implementation: (testing for == "", not using unstructured control flow)
total = 0
count = 0
run = True
while run:
line = input("Enter your number here: ")
if line == "":
print(total / count)
run = False
else:
total += float(line)
count += 1
I also renamed k to count, x to line and used in-place addition operators.
Another implementation, with break, testing for float with try/except (and re-using that for the entire control flow):
total = 0
count = 0
while True:
line = input("Enter your number here: ")
try:
# order matters here. If the first line errors out, the second won't happen so the count will only be inremented if it was indeed a float
total += float(line)
count += 1
except:
print(f"Average is: {total / count}")
break
Here I removed the run variable, and used a format string to print a bit fancier.
And an example using both continue and break:
total = 0
count = 0
while True:
line = input("Enter your number here: ")
if line != "":
total += float(line)
count += 1
continue
print(f"Average is: {total / count}")
break
You can fancy it a bit with adding more error handling - use three cases:
user entered empty line: print & exit
user entered a number: add to total
user entered something else: ignore line, but tell user what to do
I only provide one example implementation for this, but as you can see, it can be implemented in many ways.
total = 0
count = 0
# good practice to tell the user what to do
print("Average calcuator. Enter numbers one per line to calulate average of, enter empty line to print result & exit!")
while True:
line = input("Enter your number here: ")
if line == "":
print(f"Average is: {total / count}")
break
else:
try:
total += float(line)
count += 1
except ValueError:
print("You should enter a number or an empty line to calculate & exit!")

Python how to stop adding into list after hitting certain criteria

I'm doing a project whereby a user has to input the value. The loop should end if the user key in the value of more than 300 for 3 times. If the user key in a value lesser than 300, a warning message should be prompted. And another criteria is that I need to allow the user to get out of the loop if the user do not meet the condition above. For now, I tried to do by using the list but my code doesn't seem to count the number of inputs.
list1 = list()
counter = 1
while counter <= 3:
ask = float(input("Please enter each of the value: "))
while ask != "":
list1.append(str(ask))
ask = float(input("Please enter each of the value: "))
if ask >= 50:
counter += 1
else:
print("Value must be more than 300. If you do not meet the criteria, please press 'enter'. ")
print(list1)
The following code is my original code which doesn't take into account of the minimum input value.
counter = 1
while counter <= 3:
ask = float(input("Please enter each of the value: "))
if ask >= 50:
counter += 1
else:
print("Value must be more than 300 ")
I would appreciate if anyone of you can help me out.
The problem is your inner while loop can't exit since ' "" ' (your exit signal) cannot be converted to float. Instead it will raise a ValueError.
One possible solution to this would be to try converting input to float and except the ValueError. It could look something like this.
list1 = list()
counter = 1
while counter <= 3:
try:
ask = float(input("Please enter each of the value: "))
except ValueError:
break
list1.append(str(ask))
if ask >= 50:
counter += 1
else:
print("Value must be more than 300. If you do not meet the criteria, please press 'enter'. ")
print(list1)
I think the program doesn't work as you want because you made two while loops:
the first while's condition is while counter<=3, ok but then you made another while which condition is ask !="", so the program will run inside this second while loop until the condition is no more true and the first while does not "see" the counter's changes.
By the way, I think you can simply use only one while loop(the first one), and write an if condition that verify the value(>300).
When you try to cast a string element into a float type it will throw an error if the value could not be casted to that type, you could use a try-except block.
while counter < 3:
try:
ask = float(input("xxxxx")
if ask >= 50:
counter += 1
else:
print("xxxxx")
except ValueError:
break
print(list1)

creating a python program which ask the user for a number - even odd

I am new to python and I am taking a summer online class to learn python.
Unfortunately, our professor doesn't really do much. We had an assignment that wanted us to make a program (python) which asks the user for a number and it determines whether that number is even or odd. The program needs to keep asking the user for the input until the user hit zero. Well, I actually turned in a code that doesn't work and I got a 100% on my assignment. Needless to say our professor is lazy and really doesn't help much. For my own knowledge I want to know the correct way to do this!!! Here is what I have/had. I am so embarrassed because I know if probably very easy!
counter = 1
num = 1
while num != 0:
counter = counter + 1
num=int(input("Enter number:"))
while num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
There are a couple of problems with your code:
You never use counter, even though you defined it.
You have an unnecessary nested while loop. If the number the user inputs is even, then you're code will continue to run the while loop forever.
You are incorrectly using the else clause that is available with while loops. See this post for more details.
Here is the corrected code:
while True:
# Get a number from the user.
number = int(input('enter a number: '))
# If the number is zero, then break from the while loop
# so the program can end.
if number == 0:
break
# Test if the number given is even. If so, let the
# user know the number was even.
if number % 2 == 0:
print('The number', number, 'is even')
# Otherwise, we know the number is odd. Let the user know this.
else:
print('The number', number, 'is odd')
Note that I opted above to use an infinite loop, test if the user input is zero inside of the loop, and then break, rather than testing for this condition in the loop head. In my opinion this is cleaner, but both are functionally equivalent.
You already have the part that continues until the user quits with a 0 entry. Inside that loop, all you need is a simple if:
while num != 0:
num=int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
I left out the counter increment; I'm not sure why that's in the program, since you never use it.
Use input() and If its only number specific input you can use int(input()) or use an If/else statement to check
Your code wasn't indented and you need to use if condition with else and not while
counter = 1
num = 1
while num != 0:
counter = counter + 1
num = int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
Sample Run
Enter number:1
Odd 1
Enter number:2
Even 2
Enter number:3
Odd 3
Enter number:4
Even 4
Enter number:5
Odd 5
Enter number:6
Even 6
Enter number:0
Even 0

Python While Loop: sum of all numbers but the greatest

Hi so my problem is that i must create a function that asks the user to enter a series of
numbers greater than or equal to zero, one at a time. The user types end to indicate that
there are no more numbers. The function computes the sum of all the values entered
except for the maximum value in the series. (Think of this as dropping the highest
homework score from a series of homework scores.) The function then both prints the
sum and returns the sum. You may assume the user inputs are valid: they will either be a
number greater than or equal to zero, or the string end. Here are some examples of how
the function should behave:
>>> allButMax()
Enter next number: 20
Enter next number: 30
Enter next number: 40
Enter next number: end
The sum of all values except for the maximum value is: 50.0
50.0
>>> allButMax()
Enter next number: 1.55
Enter next number: 90
Enter next number: 8.45
Enter next number: 2
Enter next number: end
The sum of all values except for the maximum value is: 12.0
12.0
>>> x = allButMax()
Enter next number: 3
Enter next number: 2
Enter next number: 1
Enter next number: end
The sum of all values except for the maximum value is: 3.0
>>> print(x)
3.0
>>> allButMax()
Enter next number: end
The sum of all values except for the maximum value is: 0
0
can anyone help me with this?? so far i have this (also this has to be a while loop)
def allButMax():
while True:
number=float(input("Enter next number: "))
if number="end":
break
"end"=0
what i dont know is that i dont know how to add every value other than the max value. how would the function know which value is the maximum value? Also would i have to use another while loop to add all numbers?
I wrote the answer out for this but then saw from a previous answer that I'm not meant to do that. It's true, you do need to do your homework and work this out yourself but here are a few pointers:
Your function operates within a while loop but you can track variables outside of the while loop, your "max_number" can be reassigned a differnt value each time you go through the loop:
def allButMax():
max_number = 0
while True:
print "running while loop"
break
You don't need to use a list, the output number is simply all of the numbers added up minus the largest number.
return total_numbers - max_numer
Your function needs to return a value so use the "return" keyword.
lastly, you might want to look up the "try" and "except" keywords to evaluate the user's input. Did the user give you a number or a string?
try:
int(user_input)
except ValueError:
#user input is a string
Hope this helps without giving away too much :)
All the best!

Categories