I'm writing for creating a list of number from input and get the average of the list. The requirement is: when the user enters a number, the number will be appended to the list; when the user press Enter, the input section will stop and conduct and calculation section.
Here is my code:
n = (input("please input a number"))
numlist = []
while n != '':
numlist.append(float(n))
n = float(input("please input a number"))
N = 0
Sum = 0
for c in numlist:
N = N+1
Sum = Sum+c
Ave = Sum/N
print("there are",N,"numbers","the average is",Ave)
if I enter numbers, everything works fine. But when I press Enter, it shows ValueError. I know the problem is with float(). How can I solve this?
You don't need the float() around the input() function inside your loop because you call float() when you append n to numlist.
this should solve ur prob ,by adding a try,catch block around ur print statement
n = (input("please input a number"))
numlist = []
while True :
numlist.append(float(n))
#####cath the exception and break out of
try :
n = float(input("please input a number"))
except ValueError :
break
N = 0
Sum = 0
for c in numlist:
N = N+1
Sum = Sum+c
Ave = Sum/N
print("there are",N,"numbers","the average is",Ave)
Related
I'm trying to do a def function and have it add the digits of any number entered and stop when I type the number "0", for example:
Enter the number: 25
Sum of digits: 7
Enter the number: 38
Sum of digits: 11
Enter the number: 0
loop finished
I have created the code for the sum of digits of the entered number, but when the program finishes adding, the cycle is over, but what I am looking for is to ask again for another number until finally when I enter the number "0" the cycle ends :(
This is my code:
def sum_dig():
s=0
num = int(input("Enter a number: "))
while num != 0 and num>0:
r=num%10
s=s+r
num=num//10
print("The sum of the digits is:",s)
if num>0:
return num
sum_dig()
Use list() to break the input number (as a string) into a list of digits, and sum them using a list comprehension. Use while True to make an infinite loop, and exit it using return. Print the sum of digits using f-strings or formatted string literals:
def sum_dig():
while True:
num = input("Enter a number: ")
if int(num) <= 0:
return
s = sum([int(d) for d in list(num)])
print(f'The sum of the digits is: {s}')
sum_dig()
In order to get continuous input, you can use while True and add your condition of break which is if num == 0 in this case.
def sum_dig():
while True:
s = 0
num = int(input("Enter a number: "))
# Break condition
if num == 0:
print('loop finished')
break
while num > 0:
r=num%10
s=s+r
num=num//10
print("The sum of the digits is:",s)
sum_dig()
A better approach would be to have sum_dig take in the number for which you want to sum the digits as a parameter, and then have a while loop that takes care of getting the user input, converting it to a number, and calling the sum_digit function.
def sum_dig(num): # takes in the number as a parameter (assumed to be non-zero)
s=0
while num > 0: # equivalent to num != 0 and num > 0
r = num % 10
s = s + r
num = num // 10
return s
while True:
num = int(input("Enter a number: "))
if num == 0:
break
print("The sum of the digits is: " + sum_dig(num))
This enables your code to adhere to the Single-Responsibility Principle, wherein each unit of code has a single responsibility. Here, the function is responsible for taking an input number and returning the sum of its digits (as indicated by its name), and the loop is responsible for continuously reading in user input, casting it, checking that it is not the exit value (0), and then calling the processing function on the input and printing its output.
Rustam Garayev's answer surely solves the problem but as an alternative (since I thought that you were also trying to create it in a recursive way), consider this very similar (recursive) version:
def sum_dig():
s=0
num = int(input("Enter a number: "))
if not num: # == 0
return num
while num>0:
r= num %10
s= s+r
num= num//10
print("The sum of the digits is:",s)
sum_dig()
Dear stackoverflow community!
I just started learning python and want to figure out how to write following program:`
number = int(input('Enter ten numbers:'))
for i in range(1, 10):
while True:
try:
number = int(input("Enter another number: "))
break
except:
print("This is a string")
for i in range(1, 10):
res = 0
res += int(input())
print('The sum of these 10 numbers is:', res)
I want the user to input 10 numbers and during the process I want to check if the numbers are actually integers. So the number input works, it checks if its an integer, but then how can make this work at the same time? (To sum up the 10 integers that I got as input) :
for i in range(1, 10):
res = 0
res += int(input())
print('The sum of these 10 numbers is:', res)
So basically i want two conditions for those 10 numbers that I got as Input.
Thanks for your help.
You are simply checking the user input, not storing it somewhere. Use this instead:
numbers = []
while len(numbers) != 10:
try:
numbers.append(int(input("Enter another number: ")))
except ValueError:
print("This is not an integer!")
res = sum(numbers)
print('The sum of these 10 numbers is: {}'.format(res))
I am making a program that calculates the sum of all even and odd numbers between two number which are user inputted. I'm new to Python and am not sure how to use the range in a loop to make my program work. Here is my code. I know its sloppy and not well put together and not finished but any help works thanks.
n = int(input(" please enter a number"))
m= int(input(" please enter another number"))
count =0
sum =0
for x in range(n,m+1,2):
if x%2==0:
count=count+x
sum = count
print(" the total sum of odd numbers are",sum)
It's important to know if n is greater than m and invert situation if so. Other than that, you need to know if the smallest number is odd or even and begin the two ranges accordingly:
n = int(input("Please enter a number: "))
m = int(input("Please enter another number: "))
# n will always be the smaller one
if n > m:
n, m = m, n
n_is_odd = n % 2 # Gives 1 if n is odd
n_even = n + n_is_odd # Sum 1 if n is odd
n_odd = n + (not n_is_odd) # Sum 1 if n is even
print("the total sum of even numbers is %d" % sum(range(n_even, m+1, 2)) )
print("the total sum of odd numbers is %d" % sum(range(n_odd, m+1, 2)) )
Input validation is a big part of good coding. A good overview can be found here:
Asking the user for input until they give a valid response
To make the validation it reusable I put the validation in a function that only accept integers and (if a minval is provided, makes sure that the input is bigger that the minval.
def while_invalid_ask_input_return_integer(text, minval = None):
"""Aks for input until a number is given that is > minval if minval not None
returns an integer."""
while True:
c = input (text)
try:
c = int(c)
if minval is not None and c < minval:
raise ValueError # its too small, raise an erros so we jump to except:
return c
except ValueError:
if minval is not None:
print("must be a number and greater ", minval)
else:
print("not a number")
I use it to get the first number, and the second number gets the first one as "constraint" so it will be bigger. For summation I just use the range starting once with n once with n+1 till m and a range step of 2. I check what even/oddness n has and print text accordingly:
n = while_invalid_ask_input_return_integer("please enter a number ")
m = while_invalid_ask_input_return_integer("enter number bigger then {}".format(n),n)
print( "Odd sum:" if n % 2 == 1 else "Even sum:", sum(range(n,m+1,2)) )
print( "Even sum:" if n % 2 == 1 else "Odd sum:", sum(range(n+1,m+1,2)) )
Output:
please enter a number k
not a number
please enter a number 55
enter number bigger then 55 2
must be a number and greater 55
enter number bigger then 55 150
Odd sum: 4896
Even sum: 4944
Doku:
sum(iterable)
try: except: error handling
python ternary operator (thats the thing # "Odd sum:" if n % 2 == 1 else "Even sum:" in the print statement)
Here's a function I think fits into the description of what you asked above. It returns None if the user doesn't enter the type of query he or she wants.
So query can either be odd or even and depending on this, it calculates the sum that you want. The function makes use of list comprehension which is super cool too.
def calculate_odd_or_even_sum(query):
start = int(input(" please enter a number"))
end = int(input(" please enter another number"))
count = 0
if query == 'even':
return sum([x for x in range(start, end) if x % 2 == 0])
elif query == 'odd':
return sum([x for x in range(start, end) if x % 2 != 0])
else:
return 0
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))
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.")