How to get Python functions to calculate maths operations? - python

I have this assignment to create a program that asks user to input any positive integer repeatedly or type anything else to end and generate the sum, count and average of the numbers. My teacher wants all the code in these this structure with these three def’s only
This is the code I have, any suggestions on how to get it to work?
def calcAverage(total,count):
sum = 0
count = 0
average = sum / count
def inputNumber(message):
while True:
try:
userInput = int(input(message))
count = count + 1
sum = sum + entry
if userInput < 0:
raise ValueError
except ValueError:
main()
else:
return userInput
break
entry = inputNumber('Type any positive integer, anything else to quit')
def main():
print('Sum')
print(sum)
print('Average')
print(average)
print('Total Numbers')
print(count)

The question is not well explained + we don't really get what the boundaries are. Moreover, you should clearly state what is not working. Now, to give you some hint, this is how I would do it:
input = None
L = list()
while True:
try:
input = int(input('Type any positive integer, anything else to quit: '))
if input < 0:
break
else:
L.append(input)
except:
break
S = sum(L)

I think you don't need to use exceptions here. Condition statements would make it clearer.
I would put the valid inputs in a list until the user make a invalid input. When it happens, just get out of your while loop using a break statement and return the result.

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)

How do I break out of a While loop when either the variable becomes True/False or a certain amount of times?

import sys
ok = True
count = 0
while ok == True:
try:
a = int(input("What is a? Put number pls "))
ok = False
count = count + 1
except ValueError:
print("no u")
if (count >= 3):
sys.exit()
What I'm trying to do here is get the user to input an integer. If the user inputted an integer or the loop has ran 3 times, the program stops. I have tried putting the if statement both in the try and except statements, it still keeps on looping.
I have also tried this:
ok = True
count = 0
while ok == True:
try:
a = int(input("What is a? Put number pls "))
ok = False
count = count + 1
except ValueError:
print("no u")
if (count >= 3):
break
It still doesn't break out of the loop.
I have inputted numbers, breaks out of the loop as what I expected. I then tried to input random letters and hoped that the loop stops after 3 times, it still continues to loop until I have inputted a number. Happens to both versions.
Here's an approach which you might not have thought of:
count = 0
while count < 3:
try:
a = int(input("What is a? Put number pls "))
break
except ValueError:
print("no u")
count = count + 1
There is no need for ok because you can just use a break statement if you want to end the loop. What you really want to be testing for is if count is less than three, and incrementing count every time the user gets it wrong.
There is no reason to increment count if the loop is about to end, so you want to increment count whenever there is a ValueError (in the except-block) and the loop is about to start again.
I would recommend a slightly expanded version of michaels solution, that takes advantage of the while/else mechanism to determine when no good input was provided
count = 0
while count < 3:
try:
a = int(input("What is a? Put number pls "))
break
except ValueError:
print("no u")
count = count + 1
else: # is triggered if the loop completes without a break
print("No Break... used up all tries with bad inputs")
sys.exit(-1)
print(f"You entered a number {a}")

Python return list not working for some reason

I've been trying to work on this assignment but for some reason the function I wrote won't return the list I specified and throws a name 'numbers' is not defined error at me when printing the list outside the function.
def inputNumbers():
try:
initial_number_input = int(input("Please enter the first number: "))
except ValueError:
print("This is not a number.")
return inputNumbers()
else:
numbers = []
numbers.append(initial_number_input)
if initial_number_input == 0:
return numbers
else:
i = 0
while True:
try:
number_input = int(input("Please enter the next number: "))
except ValueError:
print("This is not a number.")
continue
else:
numbers.append(number_input)
i += 1
if number_input == 0:
break
return numbers
inputNumbers()
print(numbers)
I'm still very new to programming so I am open to whatever suggestions you may have :D
Note that if I print(numbers) above return numbers at the end of the function, it does print the list.
Thanks
When you return a value from a function it needs to be assigned to something. At the moment you are returning numbers but nothing is using it.
To actually use the returned value your last 2 lines should be
numbers = inputNumbers()
print(numbers)
You can also just print the returned value without assigning it to a variable with
print(inputNumbers())

How can I sum a list of numbers?

My program needs to read a set of integers from the user and store them in a list. It should read numbers from the user until the user enters 0 to quit. Then it needs to add them up and display the sum to the user. If the user types anything that is not an integer, it needs to display an error to the user.
I'm having a hard time figuring out how to make a list that the user can infinitely input numbers into.
From what I have tried to do and looked up, I've only been able to make a defined list and make a program that takes in a specific amount of inputs.
This is what I have. Obviously, it doesn't work, but it shows what I'm going for.
n, ns = 0, 0 # count of numbers, sum of numbers
print("Enter numbers or any other 0 to quit.")
while(1):
grades = input("enter = ")
if (int):
ns += int
n += 1
else:
if (0):
print(ns)
break
Use this:
list_of_nums = []
loop = True
while loop == True:
try: num = int(input("Enter Integer: "))
except ValueError: num = "invalid"
if num == "invalid": print("\nPlease Print A Valid Integer!\n");
elif num != 0: list_of_nums.append(num)
else: loop = False
print("\nSum of Inputed Integers: " + str(sum(list_of_nums)) + "\n")
Python 3
lists=[]
while(True):
i=int(input("Enter The Input"))
if i==0:
break
else:
lists.append(i)
print(lists)

How to accept user input of a sequence?

I'm new to python and I'm trying to help out a friend with her code. The code receives input from a user until the input is 0, using a while loop. I'm not used to the python syntax, so I'm a little confused as to how to receive user input. I don't know what I'm doing wrong. Here's my code:
sum = 0
number = input()
while number != 0:
number = input()
sum += number
if number == 0:
break
In your example, both while number != 0: and if number == 0: break are controlling when to exit the loop. To avoid repeating yourself, you can just replace the first condition with while True and only keep the break.
Also, you're adding, so it is a good idea to turn the read input (which is a character string) into a number with something like int(input()).
Finally, using a variable name like sum is a bad idea, since this 'shadows' the built-in name sum.
Taking all that together, here's an alternative:
total = 0
while True:
number = int(input())
total += number
if number == 0:
break
print(total)
No need last if, and also make inputs int typed:
sum = 0
number = int(input())
while number != 0:
number = int(input())
sum += number
You can actually do:
number=1
while number!=0:
number = int(input())
# Declare list for all inputs
input_list = []
# start the loop
while True:
# prompt user input
user_input = int(input("Input an element: "))
# print user input
print("Your current input is: ", user_input)
# if user input not equal to 0
if user_input != 0:
# append user input into the list
input_list.append(user_input)
# else stop the loop
else:
break
# sum up all the inputs in the list and print the result out
input_sum = sum(input_list)
print ("The sum is: ", input_sum)
Or
If you don't want to use list.
input_list = 0
while True:
user_input = int(input("Input an element: "))
print("Your current input is: ", user_input)
if user_input != 0:
input_list += user_input
else:
break
print ("The sum is: ", input_list)
Note:
raw_input('Text here') # Python 2.x
input('Text here') # Python 3.x

Categories