I'm trying to write a small python code that prints out a sum of data provided by a user. More specifically I need the code to be able to calculate it when the number of data is not known in advance. To achieve that I need the code to recognize that the user did not indicate the size of the list and to know what is the last entry to be included by typing in "F". The problem I encountered with my code (see below) is that when I use "F" instead of "-1" the code crashes with the following message "ValueError: could not convert string to float: 'F' python". Can anyone help me to understand what am I doing wrong, so I can fix it.
numberList = []
count = int(input("Enter the list size :"))
stopList = False
F = -1
mysum = 0
num = 0
if count >= 0:
for i in range(0, count):
item = int(input("Enter number :"))
numberList.append(item)
mysum = sum(numberList)
print("The sum is", mysum)
if count < 0:
while stopList is False:
nextnum = float(input("Enter number :"))
if nextnum == F:
stopList = True
if stopList is False:
num += 1
mysum += nextnum
print("The sum is", mysum)
I will address only the problematic part of your code, which is everything after if count < 0:.
You should first take the input as-is and check if it is 'F' and only then convert if to float, if necessary:
while stopList is False:
nextnum = input("Enter number :")
if nextnum == 'F':
stopList = True
if stopList is False:
num += 1
mysum += float(nextnum)
print("The sum is", mysum)
As a side note, don't use the condition like this for the loop, I would use it like that:
while True:
nextnum = input("Enter number :")
if nextnum == 'F':
break
num += 1
mysum += float(nextnum)
print("The sum is", mysum)
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()
in my program, I am taking user input (integers 1-9) and having the user keep typing in numbers until they type 0 to exit. once they type 0 I want to print the sum of the integers and then exit. Im new to python so any help would be appreciated. Im getting an invalid syntax error when using the > and < symbol not sure why.
def createList():
myList=[]
return myList
def fillList(myList):
for number in myList:
if number >=1 and <= 9:
number=int(input(" enter a number 1-9, and 0 to quit"))
myList.append(number)
return myList
def printList(myList):
for number in myList:
print ( " the sum is" ,sum(myList))
print(number)
if number ==0:
exit()
def main():
myList = createList()
fillList(myList)
printList(myList)
main()
You're only missing a word, try this:
if number >=1 and number <= 9:
So close!
_sum = 0
looping = True
while looping:
num = input("Enter a number (1-9) or 0 to exit.")
if num.isdigit() and 0 <= int(num) <= 9:
_sum += num
if num is 0:
looping = False
print("Sum is", _sum)
if number >=1 and number <= 9:
You need to place the variable on both sides of the and since they are two separate conditions.
Also, since you're initially creating an empty list, you will never get to the part where you get user input. To fix this you should use a while loop.
while number != 0:
The full program might look like this:
def createList():
myList=[]
return myList
def fillList(myList):
number = 5
while number != 0:
if number >=1 and number <= 9:
number=eval(input(" enter a number 1-9, and 0 to quit"))
myList.append(number)
return myList
def printList(myList):
for number in myList:
print ( " the sum is" ,sum(myList))
print(number)
if number ==0:
exit()
def main():
myList = createList()
fillList(myList)
printList(myList)
main()
Fellow python developers. I have a task which I can't seem to crack and my tutor is MIA. I need to write a program which only makes use of while loops, if, elif and else statements to:
Constantly ask the user to enter any random positive integer using int(raw_input())
Once the user enters -1 the program needs to end
the program must then calculate the average of the numbers the user has entered (excluding the -1) and print it out.
this what I have so far:
num = -1
counter = 1
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
anyNumber = int(raw_input("Enter another number: "))
counter += anyNumber
answer = counter + anyNumber
print answer
print "Good bye!"
Try the following and ask any question you might have
counter = 0
total = 0
number = int(raw_input("Enter any number: "))
while number != -1:
counter += 1
total += number
number = int(raw_input("Enter another number: "))
if counter == 0:
counter = 1 # Prevent division by zero
print total / counter
You need to add calculating average at the end of your code.
To do that, have a count for how many times the while loop runs, and divide the answer at the end by that value.
Also, your code is adding one to the answer each time because of the line - answer = counter + anyNumber, which will not result in the correct average. And you are missing storing the first input number, because the code continuously takes two inputs. Here is a fixed version:
num = -1
counter = 0
answer = 0
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
counter += 1
answer += anyNumber
anyNumber = int(raw_input("Enter another number: "))
if (counter==0): print answer #in case the first number entered was -1
else:
print answer/counter #print average
print "Good bye!"
There's another issue I think:
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
anyNumber = int(raw_input("Enter another number: "))
The value of the variable anyNumber is updated before the loop and at the beginning of the loop, which means that the first value you're going to enter is never going to be taken in consideration in the average.
A different solution, using a bit more functions, but more secure.
import numpy as np
numbers = []
while True:
# try and except to avoid errors when the input is not an integer.
# Replace int by float if you want to take into account float numbers
try:
user_input = int(input("Enter any number: "))
# Condition to get out of the while loop
if user_input == -1:
break
numbers.append(user_input)
print (np.mean(numbers))
except:
print ("Enter a number.")
You don't need to save total because if the number really big you can have an overflow. Working only with avg should be enough:
STOP_NUMBER = -1
new_number = int(raw_input("Enter any number: "))
count = 1
avg = 0
while new_number != STOP_NUMBER:
avg *= (count-1)/count
avg += new_number/count
new_number = int(raw_input("Enter any number: "))
count += 1
I would suggest following.
counter = input_sum = input_value = 0
while input_value != -1:
counter += 1
input_sum += input_value
input_value = int(raw_input("Enter any number: "))
try:
print(input_sum/counter)
except ZeroDivisionError:
print(0)
You can avoid using two raw_input and use everything inside the while loop.
There is another way of doing..
nums = []
while True:
num = int(raw_input("Enter a positive number or to quit enter -1: "))
if num == -1:
if len(nums) > 0:
print "Avg of {} is {}".format(nums,sum(nums)/len(nums))
break
elif num < -1:
continue
else:
nums.append(num)
Here's my own take on what you're trying to do, although the solution provided by #nj2237 is also perfectly fine.
# Initialization
sum = 0
counter = 0
stop = False
# Process loop
while (not stop):
inputValue = int(raw_input("Enter a number: "))
if (inputValue == -1):
stop = True
else:
sum += inputValue
counter += 1 # counter++ doesn't work in python
# Output calculation and display
if (counter != 0):
mean = sum / counter
print("Mean value is " + str(mean))
print("kthxbye")
I saw a similar post, but it included functions, which mine does not.
Objective: Write a program that reads an unspecific number of integers, determines how many positive and negative values have read, and computes the total and average of the input values (not counting 0's) while the program will halt at 0.
ISSUE I AM HAVING: When using the following test values
1,
2,
-1,
3
I get the following:
The number of positives: 1
The number of negatives: 2
The total amount of numbers used: 3
The average is 1.33 which is 4 / 3
It should be:
The number of positives: 1
The number of negatives: 3
The total amount of numbers used: 4
The average is 1.25 which is 5 / 4
My Attempt below:
positive_number = 0
negative_number = 0
average = 0
count = 0
new_number = 0
user_input = eval(input("Enter enter as many integers as you want, 0 will halt: "))
if user_input == 0:
print("You didn't enter any number, code ended")
else:
while user_input != 0:
user_input = eval(input("Enter enter as many intergers as you want, 0 will halt: "))
if user_input == 0:
print("You didn't enter any number, code ended")
elif user_input != 0 and user_input > 0:
new_number += user_input
positive_number += 1
count += 1
else:
user_input != 0 and user_input < 0
new_number += user_input
negative_number += 1
count += 1
average = (new_number / count)
print("\nThe number of positives:", positive_number)
print("The number of negatives:", negative_number)
print("The total amount of numbers used:", count)
print("The average is", format(average,".2f"), "which is", str(new_number), "/", str(count))
What is causing such error? I can only assume that this is a minor fix?
I've fixed the problems in your code and refactored to trap error conditions and removed unnecessary complications:
positive_number = 0
negative_number = 0
average = 0
count = 0
total = 0
user_input = None
while user_input != 0:
try:
user_input = int(input("Enter enter as many intergers as you want, 0 will halt: "))
except ValueError:
user_input=0
if user_input > 0:
total += user_input
positive_number += 1
count += 1
elif user_input<0:
total += user_input
negative_number += 1
count += 1
if count==0:
print("You didn't enter any number, code ended")
else:
average = total / count
print("\nThe number of positives:", positive_number)
print("The number of negatives:", negative_number)
print("The total amount of numbers used:", count)
print("The average is", format(average,".2f"), "which is", str(total), "/", str(count))
First, the first if statement is redundant as you test for user_input != 0 as the loop condition. Second, the reason it was going wrong was because on your first input you immediately overwrote the value of user_input, so I put the reprompt code at the end of the loop. Finally, I cleaned up the if elif else statement as this does the exact same with fewer characters. The print statement for the closing line is also executed once we pull out of the loop - sinc eby definition that means user_input == 0
positive_number = 0
negative_number = 0
average = 0
count = 0
new_number = 0
user_input = eval(input("Enter enter as many integers as you want, 0 will halt: "))
while user_input != 0:
if user_input > 0:
new_number += user_input
positive_number += 1
count += 1
else:
new_number += user_input
negative_number += 1
count += 1
average = (new_number / count)
print("\nThe number of positives:", positive_number)
print("The number of negatives:", negative_number)
print("The total amount of numbers used:", count)
print("The average is", format(average,".2f"), "which is", str(new_number), "/", str(count))
user_input = eval(input("Enter enter as many intergers as you want, 0 will halt: "))
print("You didn't enter any number, code ended")
Like it was said in the comments, your first input is getting ignored. Here is an alternative that should work. I excluded a few redundant check statements.
positive_number = 0
negative_number = 0
average = 0
count = 0
new_number = 0
user_input = 1
while user_input != 0:
user_input = eval(input("Enter enter as many integers as you want, 0 will halt: "))
if user_input == 0:
print("You didn't enter any number, code ended")
elif user_input > 0:
new_number += user_input
positive_number += 1
count += 1
else:
new_number += user_input
negative_number += 1
count += 1
average = (new_number / count)
print("\nThe number of positives:", positive_number)
print("The number of negatives:", negative_number)
print("The total amount of numbers used:", count)
print("The average is", format(average,".2f"), "which is", str(new_number), "/", str(count))
There are a number of issues with your code. First of all, the first number that the user prompts is not being evaluated by the code; it's being overwritten once you get to the while loop. There are multiple ways to fix this, but the best would be along the lines:
cont = True
while cont is True:
user_input = int(input("Prompt user"))
if user_input == 0:
cont = False
You could do a break statement too, it doesn't matter.
So that takes care of why the first number isn't being read, and why the code thinks there were only 3 inputs (as well as your count being off). Now what about the two negatives? I don't know why you got that. When I inputted the numbers you listed, I got one negative and two positives. Try it again and see if it works now, I suspect you must've mistyped.
I was tasked with creating a program that takes all the inputted numbers and adds them together except the highest integer out of that list. I am suppose to use while and if then logic but I cannot figure out how to exclude the highest number. I also had to make the program break when the string "end" was put into the console. So far I have,
total = 0
while 1 >= 1 :
value = input("Enter the next number: ")
if value != "end":
num = float(value)
total += num
if value == 'end':
print("The sum of all values except for the maximum value is: ",total)
return total
break
I just have no idea how to make it disregard the highest inputted number. Thanks in advance! I am using python 3 fyi.
Is this what you're trying to do?
total = 0
maxValue = None
while True:
value = input("Enter the next number: ")
if value != "end":
num = float(value)
maxValue = num if maxValue and num > maxValue else num
total += num
else:
print("The sum of all values except for the maximum value is: ",total-maxValue )
# return outside a function is SyntaxError
break
Here you go in regards to keeping it close to your original. Using lists is great in python for this sort of thing.
list = []
while True:
num = input("Please enter value")
if num == "end":
list.remove(max(list))
return sum(list)
else:
list.append(int(num))
if you input 1,2 and 3 this would output 3 - it adds the 1 and 2 and discards the original 3.
You've said it's an assignment so if lists aren't allowed then you could use
max = 0
total = 0
while True:
num = input("Please enter value")
if str(num) == "end":
return total - max
if max < int(num):
max = int(num)
total += int(num)
the easiest way to achieve the result you want is to use python's builtin max function (that is if you don't care about performance, because this way you are actually iterating over the list 2 times instead of one).
a = [1, 2, 3, 4]
sum(a) - max(a)
This not exactly the same as you want it to do, but the result is going to be the same (Since instead of not adding the largest item you can just subtract it in the end).
This should work for you.
total = 0
highest = None
while True:
value = input("Enter the next number: ")
if value != 'end':
num = float(value)
if highest is None or num > highest:
highest = num
total += num
else:
break
print("The sum of all values except for the maximum value is: ",total-highest )
print(total-highest)