Alright so this problem has been grinding me for a good hour. I am taking a zybooks course and I'm presented with the prompt,
Statistics are often calculated with varying amounts of input data. Write a program that takes any number of integers as input, and outputs the average and max.
Ex: If the input is:
15 20 0 5
the output is:
10 20
currently I have it 'working' with my code but the issue is I cannot figure out how to keep the input open for more or less inputs as zybooks runs through multiple different tests. i'm sure its something simple im overlooking. anything helps!
nums = []
for i in range(0, 4):
number = int(input('Enter number'))
nums.append(number)
avg = sum(nums) / len(nums)
print(max(nums), avg)
This code continually asks the user to enter values until they enter a blank (just press enter without typing).
This is the code:
nums = []
# initialse
number = 0
# loop until there isn't an input
while number != "":
# ask for user input
number = input('Enter number:')
# validate the input isn't blank
# prevents errors
if number != "":
# make input integer and add it to list
nums.append(int(number))
avg = sum(nums) / len(nums)
print(max(nums), avg)
Alternatively, if you have the list of numbers:
def maxAndAvg(nums):
avg = sum(nums) / len(nums)
return max(nums), avg
One solution is to have the user specify how many numbers they want to take the average of. For instance:
nums = []
n = int(input('How many numbers: '))
for i in range(n):
number = int(input('Enter number: '))
nums.append(number)
avg = sum(nums) / n
print(max(nums), avg)
Alternatively, if you want a function that itself takes a variable number of arguments, you'll need to use the "*args" operator. For instance,
def my_average(*args):
return sum(args)/len(args)
An example usage:
print(my_average(1),my_average(1,2),my_average(1,2,3))
Result:
1.0 1.5 2.0
Ok, guys this is the correct code to figure this lab out. Did some data mining and some line manipulation to pass all ten tests:
nums = []
while not nums:
number = input()
nums = [int(x) for x in number.split() if x]
avg = int(sum(nums) / len(nums))
print(avg, max(nums))
Related
I am gitting stuck here, please help. The code has to promt the user to enter a number, pass the number to a python function and let the function calculate the average of all the numbers from 1 to the number entered by the user.
def SumAverage(n):
sum=0
for idx in range(1,n+1):
average =sum/idx
return average
num =int(input("Enter a number"))
result=SumAverage(num)
print("The average of all numbers from 1 to {} is {}".format(num,result))
The sum of the series 1 + 2 + 3 + ... + n where n is the user inputted number is:
n(n+1)/2 (see wikipedia.org/wiki/1+2+3+4+...)
We have that the average of a set S with n elements is the sum of the elements divided by n. This gives (n(n+1)/2)/n, which simplifies to (n+1)/2.
So the implementation of the average for your application is:
def sum_average(n):
return (n + 1) / 2
This has the added benefit of being O(1).
Your version is not working because the average is always set to the last calculation from the for loop. You should be adding the idx for each iteration and then doing the division after the loop has completed. However, all of that is a waste of time because there is already a function that can do this for you.
Use mean from the statistics module.
from statistics import mean
num = int(input("Enter a number"))
result = mean(list(range(1, num+1)))
print(f'The average of all numbers from 1 to {num} is {result}')
If you are determined to do the logic yourself it would be done as below, if we stick with your intended method. #zr0gravity7 has posted a better method.
def SumAverage(n):
sum=0
for i in range(1,n+1):
sum += i
return round(sum / n, 2)
num = int(input("Enter a number"))
result = SumAverage(num)
print(f'The average of all numbers from 1 to {num} is {result}')
I'm not recommending this, but it might be fun to note that if we abuse a walrus (:=), you can do everything except the final print in one line.
from statistics import mean
result = mean(list(range(1, (num := int(input("Enter a number: ")))+1)))
print(f'The average of all numbers from 1 to {num} is {result}')
I went ahead and wrote a longer version than it needs to be, and used some list comprehension that would slow it down only to give some more visibility in what is going on in the logic.
def SumAverage(n):
sum=0
l = [] # initialize an empty list to fill
n = abs(n) # incase someone enters a negative
# lets fill that list
while n >= 1:
l.append(n)
print('added {} to the list'.format(n), 'list is now: ', l)
n = n - 1 # don't forget to subtract 1 or the loop will never end!
# because its enumerate, I like to use both idx and n to indicate that there is an index and a value 'n' at that index
for idx, n in enumerate(l):
sum = sum + n
# printing it so you can see what is going on here
print('length of list: ', len(l))
print('sum: ', sum)
return sum/len(l)
num =int(input("Enter a number: "))
result=SumAverage(num)
print("The average of all numbers from 1 to {} is {}".format(num,result))
Try this:
def SumAverage(n):
sum=0
for i in range(1,n+1):
sum += i
average = sum/n
return average
[its the better plz see this.
(short description):- user enter the list through functions then that list is converted into int. And the average is calculated all is done through functions thanx
]1
I want to store integers and return the sum, using random.randint() for random values.
The code looks like this:
import random
val = int(input('How many numbers?: '))
for i in range(val):
print(random.randint(1,99))
I need to print the integers to the console and then sum them and return the final sum.
Example:
How many numbers?: 4
84
50
35
35
Final number: 204
I need it to work for an infinite amount of numbers too.
right now you are not keeping track of the numbers you are printing out in val.
In order to keep track and sum up all of the numbers, you need to store them in an array.
import random
val = int(input('How many numbers?: '))
#random number is stored as val
for i in range(val):
#this will run from 1-val
print(random.randint(1,99))
#these numbers are simply being printed, not stored
So what we could do is store the numbers, and then print them
sum=0
for i in range(val):
num=(random.randint(1,99))
sum=sum+num
print"random number:", num
print"The total sum is:", sum
Use a list to store the numbers.
Use sum() to add them up.
Use join() to print them out.
import random
val = int(input('How many numbers?: '))
numbers = [random.randint(1,99) for i in range(val)]
print('\n'.join(str(i) for i in numbers))
print('Final number: {}'.format(sum(numbers)))
Example output:
How many numbers?: 5
60
70
51
65
18
Final number: 264
You will not be able to provide a sum for an infinite series of random numbers, nor will you be able to store them.
This solution only covers dealing with no end point, there are good solution already for the other aspects of the question.
There is no way to sum up an infinite amount of numbers but you can just keep generating numbers until the program receives a KeyboardInterrupt
nums = []
try:
while True:
nums.append(random.randint(1,99))
except KeyboardInterrupt:
pass
total = sum(nums)
amount_finished = len(nums)
Or to support a potential but not necessary limit you can use:
str_limit = input("enter the limit (accepts 'inf') ")
if str_limit=="inf":
limit = float("inf")
print ("you will need to stop the program with a KeyboardInterrupt")
else:
limit = int(str_limit)
nums = []
try:
while limit>0:
nums.append(random.randint(1,99))
limit-=1
except KeyboardInterrupt:
pass
total = sum(nums)
amount_finished = len(nums)
What is wrong with this? I need to get it to sum negative numbers too.
Result = int(input('Enter a number: ')) M = (result) For I in range(m): Result = result + i Print(result)
Probably an indentation error, but your for loop should read,
"for i in range(m):"
not "for I in range(m):"
The print function should be in lowercase letters as well.
Python is case sensitive so make sure all of your variables are matching up.
This code works for you.
n = int(input())
result=0
for i in range(n):
print "Enter number"
num = int(input())
result+=num
print"The sum is", result
This fixes it for negative input values; it still has a problem if input is 0.
upto = int(input("Enter a number: "))
sign = abs(upto) // upto # +1 or -1
upto = abs(upto)
total = sign * sum(range(upto + 1))
print("The result is {}".format(total))
I've managed to get factors in a list but I can't finish because I'm doing something wrong in the end, the count variable is not updating with the products.
I want to solve it without using the factorial function.
Question:
Write a program which can compute the factorial of a given number.
The results should be printed in a comma-separated sequence on a single line.
Suppose the following input is supplied to the program:
8
Then, the output should be:
40320
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
user = int(input("Input a number: "))
factors = []
while user > 0:
n = user * (user - 1)
if user == 1:
factors.append(1)
break
else:
factors.append(user)
user -= 1
count = 0 # this should be updating but it's not
for f in range(factors[0]): # I'm not sure if this is the correct range
counting = factors[f] * factors[f + 1] # I'm not sure about this either
count = count + counting
f = f + 1
Just change the last part of your program to:
result = 1
for f in factors:
result *= f
print result
Finding the factorial of a number is simple. I'm no python expert, and it could probably be written simpler but,
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
I think #erip may be right in the comment section.
num = int(input("Input a number: "))
factorial = 1
for i in range(2,num+1): # range isn't inclusive
factorial*=i
This question already has answers here:
Determine whether integer is between two other integers
(16 answers)
Closed 4 years ago.
Here's my code:
total = int(input("How many students are there "))
print("Please enter their scores, between 1 - 100")
myList = []
for i in range (total):
n = int(input("Enter a test score >> "))
myList.append(n)
Basically I'm writing a program to calculate test scores but first the user has to enter the scores which are between 0 - 100.
If the user enters a test score out of that range, I want the program to tell the user to rewrite that number. I don't want the program to just end with a error. How can I do that?
while True:
n = int(input("enter a number between 0 and 100: "))
if 0 <= n <= 100:
break
print('try again')
Just like the code in your question, this will work both in Python 2.x and 3.x.
First, you have to know how to check whether a value is in a range. That's easy:
if n in range(0, 101):
Almost a direct translation from English. (This is only a good solution for Python 3.0 or later, but you're clearly using Python 3.)
Next, if you want to make them keep trying until they enter something valid, just do it in a loop:
for i in range(total):
while True:
n = int(input("Enter a test score >> "))
if n in range(0, 101):
break
myList.append(n)
Again, almost a direct translation from English.
But it might be much clearer if you break this out into a separate function:
def getTestScore():
while True:
n = int(input("Enter a test score >> "))
if n in range(0, 101):
return n
for i in range(total):
n = getTestScore()
myList.append(n)
As f p points out, the program will still "just end with a error" if they type something that isn't an integer, such as "A+". Handling that is a bit trickier. The int function will raise a ValueError if you give it a string that isn't a valid representation of an integer. So:
def getTestScore():
while True:
try:
n = int(input("Enter a test score >> "))
except ValueError:
pass
else:
if n in range(0, 101):
return n
You can use a helper function like:
def input_number(min, max):
while True:
n = input("Please enter a number between {} and {}:".format(min, max))
n = int(n)
if (min <= n <= max):
return n
else:
print("Bzzt! Wrong.")