How to calculate average / mean on python 2.7 - python-2.7

Im trying to calculate the average when an user will enter the numbers and will stop when he decide. I manage to get the sum however I cant divided it because I need somehow get the quantity of the inputs before he stops entering. Here is my code so far:
print (" please enter all the numbers you want to calculate the avarage. After you enter all of them press 'f' to finish.")
s = 0
x = raw_input ('please enter the number')
while (num != 'f'):
x = eval (x)
s = s + x
x = raw_input ('please enter the number')
print (' the average is'), s
Like you see I manage to get the sum however I dont know how I can get the quantity of the input to then divide the sum with this to get the average. Any help will be appreciated

You just needed to add a counter inside your while loop:
print (" please enter all the numbers you want to calculate the avarage. After you enter all of them press 'f' to finish.")
s = i = 0 #declare counter: i = 0
x = raw_input ('please enter the number')
while (x != 'f'):
x = eval (x)
s = s + x
i+=1 #increment counter: i=i+1 or i+=1 (these 2 options are equivalent)
x = raw_input ('please enter the number')
print (' the average is'), s/i #divide the sum by counter

Related

Why am I getting an infinite loop? [PYTHON 2.7]

I am trying to run a very basic while loop and am still new to python I have learned obviously:
numbers = []
def print_numbers(x):
i = 0
counter = x
while i < counter:
print "top of the list"
numbers.append(i)
print i
i += 1
#print "Numbers nows:", numbers
#print"At the bottom i is %d" % i
#print "The numbers:"
y = raw_input("Pleast enter the number:")
print_numbers(y)
#for num in numbers:
# print num
So, this loop does what it says it does, takes a number and add's it to the list one at a time, the length of the list is defined by user input. Seem straight forward enough correct. Well when I run it I get an infinite loop. Why is that?
Your y variable is of type str, so it's never less than i. You need to parse it as an int after reading it from stdin.
numbers = []
def print_numbers(x):
i = 0
counter = x
print i,counter
while i < counter:
print "top of the list"
numbers.append(i)
print i
i += 1
# print "Numbers nows:", numbers
# print"At the bottom i is %d" % i
# print "The numbers:"
y = int(raw_input("Pleast enter the number:"))
print_numbers(y)

How To Make raw_input Not A String In python

I want to make this program do the summation of something with their input. My code thus far
def summation():
start = int(raw_input("Start value of n?: "))
end = int(raw_input("End value of n?: "))
eqn = lambda n: raw_input("Equation?: ")
sum = 0
for i in range(start , end + 1):
sum += eqn(i)
return sum
print summation() # start will be 1, end will be 5 , equation will be n + 1. Should print 20
I get the error that I can't add an integer and a string together so is there any way to make the raw_input for equation not a string. Like instead of it being 'n + 1', I want it to be n + 1.
You could use input instead of raw_input, but this isn't really a good idea, since every time eqn is called it will call a input and prompt you for the equation.
A better method is to store the equation beforehand (using raw_input), and then use eval in the lambda function. Something like:
def summation():
start = int(raw_input("Start value of n?: "))
end = int(raw_input("End value of n?: "))
fx = raw_input("Equation: ")
eqn = lambda n: eval(fx)
sum = 0
for i in range(start , end + 1):
sum += eqn(i)
return sum
print summation()
Don't you need to surround your raw_input in your eqn variable with an int()?
I use python 3, but that should fix your problems.

This code is saying Invalid Syntax, and pointing out at my "guessNum" variable. What is wrong?

from random import randint
myNumber = randint(1000,9999)
guessNum = 0
correctNumbers = 0
Input = False
Userguess = 0
print ("Welcome to Guess The Number")
print ("try to guess my number between 1000 and 9999")
while Input == False:
Userguess = int(raw_input("Guess a number betweeb 1000 and 9999: ")
guessNum += 1
if Userguess == myNumber:
print("Well Done, you guessed the number in" + str(NumberGuesses) + "guesses")
Input = True
The program is a guess the number game where the user has to guess a randomly generated number between 1000 and 9999.
Missing bracket at line no 13.
Userguess = int(raw_input("Guess a number betweeb 1000 and 9999: "))

How to find the min and max in a number list [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 6 years ago.
I'm having trouble with a project for class and I was looking for some help. I need to make a code where it will ask for numbers repeatedly and then print out the min and max in the list. My teacher said we can do this anyway we wish.
num_list = []
while True:
num = raw_input("Enter a number: ")
if num == "done" : break
if num >= 0:
num_list.append(num)
print min(num_list)
print max(num_list)
This is what I have so far, it asks for the number inputs and will break when I enter done, but it will only print out "Done" for the min and max in the list.
you need to convert the numbers to an integer or float type before calling min/max.
# under n >= 0:
num = int(num) # or num = float(num)
num_list.append(num)
so an example of working code would be:
num_list = []
while True:
num = raw_input("Enter a number: ")
if num == "done" :
break
try: # use a try except to verify user input is in fact a number
num = int(num) + 0 # alternatively use float(num) if non integer numerical inputs will be used
if num >= 0:
num_list.append(num)
print "min: ",min(num_list)
print "max: ",max(num_list)
except:
print "invalid input"
Not calling max/min every iteration:
num_list = []
_min, _max = None, None
while True:
num = raw_input("Enter a number: ")
if num == "done" :
break
try: # use a try except to verify user input is in fact a number
num = int(num) # alternatively use float(num) if non integer numerical inputs will be used
if num >= 0:
if not _min or not _max:
_min,_max = num, num
elif num < _min:
_min = num
elif num > _max:
_max = num
num_list.append(num)
except:
print "invalid input"
print "min:", _min
print "max:", _max

How to run the code from start after calculation?

What if i want to ask the user whether he wants to perform another calculation or not everytime the user makes a calculation and gets the answer? I just want the code to run again from start everytime user performs calculation
var = int(raw_input("Enter 1,2,3 or 4 for add,subtract,multiplication,division respectively: "))
if var == 1:
print "You chose to add.Lets add!! :)"
def main ():
total = 0.0
while True:
number = float(raw_input('enter a number: '))
total+=number
if number == 0:
break
print "your answer is:",total
main()
elif var == 3:
print "You chose to multiply.Lets multiply!! :) "
def main ():
total = 1.0
while True:
number = float(raw_input('enter a number:'))
total*=number
if number == 1:
break
print "the answer is", total
main()
Just put
while True:
around the whole thing. This will continue looping indefinitely. If you want the user to be able to choose to end the program, try:
while True:
...
continue = raw_input("Continue? (Y/N) ")
if continue.lower in ("n", "no"):
break