Creating a loop and calculating the average at the end - python

I have an assignment as follows
Write a program that repeatedly asks the user to enter a number, either float or integer until a value -88 is entered. The program should then output the average of the numbers entered with two decimal places. Please note that -88 should not be counted as it is the value entered to terminate the loop
I have gotten the program to ask a number repeatedly and terminate the loop with -99 but I'm struggling to get it to accept integer numbers (1.1 etc) and calculate the average of the numbers entered.

the question is actually quite straightforward, i'm posting my solution. However, please show us your work as well so that we could help you better. Generally, fro beginners, you could use the Python built-in data types and functions to perform the task. And you should probably google more about list in python.
def ave_all_num():
conti = True
total = []
while conti:
n = input('Input value\n')
try:
n = float(n)
except:
raise ValueError('Enter values {} is not integer or float'.format(n))
if n == -88:
break
total.append(n)
return round(sum(total)/len(total),2)
rslt = ave_all_num()

Try the following python code. =)
flag = True
lst=[]
while(flag):
num = float(raw_input("Enter a number. "))
lst+=[num]
if(num==-88.0): flag = False
print "Average of numbers: ", round( (sum(lst[:-1])/len(lst[:-1])) , 2)

enter code hereThank you for the prompt replies. Apologies. This is the code i was working on:
`#Assignment2, Question 3
numbers=[]
while True:
num=int(input("Enter any number:"))
if num==float:
continue
if num==-88:
break
return print(" the average of the numbers entered are:",sum(numbers)/len(numbers)`

Related

Python beginner taking Python for Everybody course on Coursera - struggling with numbers assignment 5.2

So the task is to:
"Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below."
I'm still kind of new to Python but I can't seem to achieve this assignment on my own. I kind of want to avoid just copying someone else's code because the teacher of the module Charles Severence, says that's not a good idea. But I'm also getting tired of this assignment that probably does not reflect anything I would normally want to use python for as a programmer.
This is my code at the moment. It seems like no matter what I change there is always a new error:
Please help, suggest solutions and tell me the mistakes I'm making.
EDIT:
I have received comments about the indentation errors and I wanted to clarify that these were typos I caused when copying my code into this forum. Anyway, I have adjusted my code and it no longer has the problem of not accepting 'done' or not continuing the loop after an invalid input. Now, the difficulty I'm having is retrieving the maximum and minimum values with or without a list function. Also, at this point I'm so stuck I wouldn't mind receiving some direct answers with working code.
largest = None
smallest = None
number_list = []
while True:
num = input('Enter a number:')
if num == 'done' : break
try:
num = int(num)
number_list.append(num)
except:
print ('Invalid Input')
continue
def max(num):
for largest in number_list[num]:
if largest < num:
largest = num
return largest
def min(num):
for smallest in number_list[num]:
if smallest is None:
smallest = num
if smallest > num:
smallest = num
return smallest
print ('Maximum is',max(num))
print ('Minimum is',min(num))
While not giving away the complete code due to the reasons your teacher stated, there are quite a few things to look at there:
The values aren't currently being returned since input always returns a string, and you need integers to compare, so after you input, you should add a line that tries to convert the input to an integer variable, something like this:
num = input('Enter a number:')
if num != "done":
try:
num = int(num)
number_list.append(num)
except ValueError:
print("Must be a number or the word 'done'")
Note that I also checked for a number_list variable that should be defined as an empty list beforehand. Lists are great for the purpose of storing many numbers on a single variable and then checking it for the largest and smallest number with the max() and min() arguments.
I assume you haven't heard of lists yet.
The way I would solve it would be to use a list to store all the values and then applying the max(list) and min(list) built-in functions.
alln = list()
num=""
while num!='done':
num = input('Enter a number:')
try:
alln.append(float(num))
except:
print('invalid input')
print ('Maximum is',max(alln))
print ('Minimum is',min(alln))
Like this
Check this and this to understand the basics of lists and how to work with those two functions.
Now the problems with your code
1. You have several indentation errors.
for largest_num in [uval]:
if largest is not None or uval > largest:
^here, the 'if' should be inside the 'for' block and it wasn´t. You have this problem twice in your code
while True:
num = input('Enter a number:')
uval = float(num)
if num == str:
elif num == str('done'):
^here, all four need an extra space to be properly indented
2. Because of this
num = input('Enter a number:')
uval = float(num)
When you write "done", you get another error. Try doing this instead:
while True:
if num == 'done':
break
#check if it's not a number
else:
num = float(num)
#store the value as a float
That way you can avoid converting a string to a float, which is why you are getting the error
Other problems I found
Both prints have indentation errors. But assuming that's just a typo, the indentation itself will make the loop print every single time it runs because it's inside the 'for' block.
str('done') this doesn't work because str() will transform the argument to a string. Remember that 'done' is already considered a string by python, so you can just write num == 'done'

How can I solve this exercise on iteration in python?

I'm new to programming and I'm stuck with an exercise, I hope someone can help.
The problem is the following:
1)Write a function that repeatedly asks the user to insert a number and computes the sum of those numbers
2)When the user inserts 0, exit and print the value of the sum.
Now this is the code i managed to write, but if my variable keeps increasing the input will never b 0 and the program will run forever...
def mysum():
n=1
while n>0:
n=n+int(input('Insert a value: '))
print(n)
Now when I call the function it keeps addings the sum of the numbers the users wrote, but how can I going on with the 2nd point of the exercise?
thank you
You're close! Loop forever (while True) and break when the user gives a 0
def mysum():
n = 0
while True:
new = input('Insert a value: ')
# validate the new input can be made a number
try:
new = float(new)
except ValueError:
print('invalid input, try again')
continue
if not new: # or new == 0
break
n += new
print(n)

Accumulator using For Loop in Python

My teacher wants a program to ask the user for a positive integer number value, which the program should loop to get the sum of all integers from 1 up to the numbered entered. In For Loop using Python.
Here's what I came up with for the For Loop but it is not's not looping when I type in a negative number and it won't display an answer when I input a positive number after inputting a negative number.
x=int(input("Please pick a positive integer"))
sum=0
for i in range(1,x):
sum=sum+1
print(sum)
else:
x=int(input("Please pick a positive integer"))
Help?
How about implementing something like the following. There are a few problems with your program, most notably:1. The sum is being repeatedly printed for every value. 2. You are simply adding 1 to the sum instead of adding the integer i. 3. You are not returning on your function if your user does not enter a positive integer. 4. You have no if statement for if the integer is greater than 0.
def intpicker():
x=int(input("Please pick a positive integer"))
sum=0
if x >= 0:
for i in range(1,x):
sum=sum+i
print(sum)
else:
return intpicker()
This code could be further abbreviated, but for all intents and purposes you should probably just try and understand this implementation as a start.
There are a few fatal flaws in your program. See below:
x=int(input("Please pick a positive integer")) #what if the user inputs "a"
sum=0
for i in range(1,x): # this will not include the number that they typed in
sum=sum+1 # you are adding 1, instead of the i
print(sum)
else:
x=int(input("Please pick a positive integer")) # your script ends here without ever using the above variable x
This is what I might do:
while True: # enters loop so it keeps asking for a new integer
sum = 0
x = input("Please pick an integer (type q to exit) > ")
if x == "q": # ends program if user enters q
break
else:
# try/except loop to see if what they entered is an integer
try:
x = int(x)
except:
print "You entered {0}, that is not a positive integer.".format(x)
continue
for i in range(1, x+1): # if the user enters 2, this will add 1 and 2, instead of 1.
sum += i
print sum

How to add a set of numbers that the user inputted in Python?

How do I add numbers in between two numbers the user inputted in Python 2.7. So a person would input 75 and 80 and I want my program to add the numbers in between those two numbers. I am very new to programming and python so any help would be awesome!
This example excludes 75 and 80. If you need to include them replace with print sum(range(n1,n2+1))
n1=input('Enter first number ')
n2=input('Enter second number ')
print sum(range(min(n1,n2)+1,max(n1,n2)))
#DSM is right!
n1=input('Enter first number ')
n2=input('Enter second number ')
print (n2-n1+1)*(n2+n1)/2
to capture user input use number1 = raw_input('Input number'). From there I'm not exactly sure what you mean from adding numbers between the two? If you want 76+77+78+79 in that example
number1 = raw_input('Input number')
number2 = raw_input('Second number')
result = 0
for n in range(int(number1)+1, int(number2)):
result+=n
print result
Here's a quick sample that should handle a few different situations. Didn't go that in-depth since I don't know the scope of the situation. Realistically you should do some form of type-checking and loop until valid input is entered. However this should get you started:
def sumNums(a, b):
total = 0
if a < b:
total = sum(range(a+1, b))
elif b < a:
total = sum(range(b+1, a))
return total
num1 = int(raw_input("First Number: "))
num2 = int(raw_input("Second Number: "))
print sumNums(num1, num2)
However I'm sure there's a more comprehensive way using lists and sum() but it seems like you only need a basic working example.
easy you just go
def add(x,y):
if True:
return add(x, y)
else:
return None
add([1,2,3,4][0], [1,2,3,4][2])

Adding up the sum of digits

I need to make a program that the user will enter in any number and then try guess the sum of those digits.
How do i sum up the digits and then compare then to his guess?
I tried this:
userNum = raw_input("Please enter a number:\n")
userGuess = raw_input("The digits sum is:\n")
if sum(userNum, userGuess):
print"Your answer is True"
else:
print "Your answer is False"
and it didnt work
You have 2 problems here :
raw_input() doesn't return an integer, it returns a string. You can't add strings and get an int. You need to find a way to convert your strings to integers, THEN add them.
You are using sum() while using + whould be enough.
Try again, and come back with your results. Don't forget to include error messages and what you think happened.
Assuming you are new to Python and you've read the basics you would use control flow statements to compare the sum and the guess.
Not sure if this is 100% correct, feel free to edit, but it works. Coded it according to his(assuming) beginner level. This is assuming you've studied methods, while loops, raw_input, and control flow statements. Yes there are easier ways as mentioned in the comments but i doubt he's studied map Here's the code;
def sum_digits(n):
s = 0
while n:
s += n % 10
n /= 10
return s
sum_digits(mynumber)
mynumber = int(raw_input("Enter a number, "))
userguess = int(raw_input("Guess the digit sum: "))
if sum_digits(mynumber) == userguess:
print "Correct"
else:
print "Wrong"
Credit to this answer for the method.
Digit sum method in Python
the python code is :
def digit_sum(n):
string = str(n)
total = 0
for value in string:
total += int(value)
return total
and the code doesnot use the API:
def digit_sum1(n):
total=0
m=0
while n:
m=n%10
total+=m
n=(n-m)/10
return total
Firstly you neet to use something such as int(raw_input("Please enter a number:\n")) so the input returns an integer.
Rather than using sum, you can just use + to get the sum of two integers. This will work now that your input is an integer.
Basically I would use a generator function for this
It will iterate over the string you get via raw_input('...') and create a list of the single integers
This list can then be summed up using sum
The generator would look like this:
sum([ int(num) for num in str(raw_input('Please enter a number:\n')) ])
Generators create lists (hence the list-brackets) of the elements prior to the for statement, so you could also take the double using:
[ 2 * int(num) for num in str(raw_input('Please enter a number:\n')) ]
[ int(num) for num in str(123) ] would result in [1,2,3]
but,
[ 2 * int(num) for num in str(123) ] would result in [2,4,6]

Categories

Resources