I am working on a project for school in python 2 and I am having a lot of trouble with one of the problems:
Write a program that computes the following sum:
sum = 1.0/1 + 1.0/2 + 1.0/3 + 1.0/4 + 1.0/5 + .... + 1.0/N
N is an integer limit that the user enters.
For example:
Enter N: 4
Sum is: 2.08333333333
The code I currently have written is:
NumOfN = int(input("What is N? : "))
total = 0
for i in range (NumOfN):
NextNum = 1.0/(NumOfN)
total = NextNum
NumOfN = NumOfN-1
print "the sum is", total
However whenever I run this I get an output of "1.0" any help would be greatly appreciated.
-Thank you.
You were not incrementing total with itself and NextNum. I changed total = NextNum to total += NextNum:
NumOfN = int(input("What is N? : "))
total = 0
for i in range(NumOfN):
NextNum = 1.0/(NumOfN)
total += NextNum
NumOfN = NumOfN-1
print "the sum is ", total
or more simply:
NumOfN = int(input("What is N? : "))
runningTab = []
for i in range(NumOfN, -1, -1):
if i != 0:
runningTab.append(1.0/(i))
print "the sum is ", sum(runningTab)
It is better to use lists and sum at the end than to keep a running tally of numbers.
Second line of the for loop:
total = NextNum
The variable total should have NextNum added to it, not just reassigned. This is because total must be added over and over by adding NextNum to itself. Let's change that to:
total = total + NextNum
This would mean: total needs to add NextNum to itself, so we will add them together so that the new total is now equal to the old total + NextNum.
A side note:
You may have noticed that #heinst used += in his line of code, total += NextNum. This is the same as total = total + NextNum , but it is like an abbreviation. You can do this with += , -= , *=,and /=. All of them are ways to abbreviate the line of code that would reassign a variable after doing some arithmetic on it.
With that being said, the following line of code:
NumOfN = NumOfN-1
Can become:
NumOfN -= 1
This is an abbreviation.
Related
I need help figuring out how to ask the user if they would like to repeat the program. Any help is much appreciated. I am relatively new to Python and it would be great to receive some advice!
X = int(input("How many numbers would you like to enter? "))
Sum = 0
sumNeg = 0
sumPos = 0
for i in range(0,X,1):
number = float(input("Please enter number %i : " %(i+1) ))
# add every number to Sum
Sum = Sum + number # Sum += number
#only add negative numbers to sumNeg
if number < 0:
sumNeg += number # sumNeg = sumNeg + number
#only add positive numbers to sumPos
if number > 0:
sumPos += number # sumPos = sumPos + number
print ("------")
print ("The sum of all numbers = ", Sum)
print ("The sum of negative numbers = ", sumNeg)
print ("The sum of positive numbers = ", sumPos)
I'm not sure if I need to use a while loop, but how would I enter a (y/n) into my code because I am asking for an integer from the user in the beginning.
Ask the user for input at the end of the loop to continue or not. If the user doesn't want to continue, use a break statement to break out of the loop.
https://www.simplilearn.com/tutorials/python-tutorial/break-in-python#:~:text='Break'%20in%20Python%20is%20a,condition%20triggers%20the%20loop's%20termination.
Have an outer loop that comprises your whole processing.
It's an infinite loop.
You exit from this loop thanks to the break statement once the user has answered no.
In fact once he has answered everything else than Y or y. The user string is converted to lower() before comparison for more convenience.
while True:
X = int(input("How many numbers would you like to enter? "))
Sum = 0
sumNeg = 0
sumPos = 0
for i in range(0, X, 1):
number = float(input("Please enter number %i : " % (i + 1)))
# add every number to Sum
Sum = Sum + number # Sum += number
# only add negative numbers to sumNeg
if number < 0:
sumNeg += number # sumNeg = sumNeg + number
# only add positive numbers to sumPos
if number > 0:
sumPos += number # sumPos = sumPos + number
print("------")
print("The sum of all numbers = ", Sum)
print("The sum of negative numbers = ", sumNeg)
print("The sum of positive numbers = ", sumPos)
resp = input("Would you like to repeat the program ? (y/n)")
if resp.lower() != "y":
break
As an alternative to the while True loop.
You could declare at the top of the script a variable user_wants_to_play = True.
The while statement becomes while user_wants_to_play.
And set the variable to False when the user answers no.
The following program will keep on executing until user enter 0 to break the loop.
while True:
X = int(input("How many numbers would you like to enter? "))
Sum, sumNeg, sumPos = 0
for i in range(X):
number = float(input("Please enter number %i : " %(i+1) ))
Sum += number
if number < 0:
sumNeg += number
if number > 0:
sumPos += number
print ("------")
print ("The sum of all numbers = ", Sum)
print ("The sum of negative numbers = ", sumNeg)
print ("The sum of positive numbers = ", sumPos)
print ("------")
trigger = int(input("The close the program enter 0: "))
if trigger == 0:
break
I want to calculate the sum of the natural numbers from 1 up to an input number. I wrote this code:
number=int(input("enter a natural number"))
if number<0:
print("The number is not positive")
else:
n=0
for i in range (1,number+1):
n+=i
print(n)
But it prints multiple numbers instead. For example, if the user puts five, the program should print 15, but I get this:
1
3
6
10
15
How can I fix the code so that only 15 appears?
You have all the steps because your print statement is in your for loop.
Change it like this:
number = int(input("Enter a positive natural number: "))
if number < 0:
print("The number needs to be positive")
exit() # Stops the program
result = 0
for i in range(1, number + 1):
result += i
print(result) # We print after the calculations
There's also a mathematical alternative (see here):
number = int(input("Enter a positive natural number: "))
if number < 0:
print("The number needs to be positive")
exit() # Stops the program
print(number * (number + 1) / 2)
As I've pointed out and suggested earlier in comments, you could move the print statement out of for-loop to print the final sum.
Or you could try to use generator expression to get all number's total (sum), because we don't care the intermediate sums.
This simple sum of all up to the number in one shot.
number=int(input("enter a natural number"))
if number < 0:
print("The number is not positive")
# exit or try again <---------
else:
print(sum(range(1, number + 1))) # given 5 -> print 15
Something like this?
number = int(input("enter a natural number"))
if number < 0:
print("The number is not positive")
else:
n = 0
for i in range (1,number + 1):
n += i
print(n)
The answer to your question is that you are printing the n every time you change it. You are looking for the last answer when you run the code. This code should solve it.
number = int(input("enter a natural number"))
if number < 0:
print("The num < 0")
else:
n = 0
l = []
for i in range (0, number+1):
n+=i
l.append(n)
print(l[len(l)-1])
Write a python application that allows a user to enter any number of student test scores until the user enters 999. If the score entered is less than 0 or more than 100, display an appropriate message and do not use the score. After all the scores have been entered, display the number of scores entered and the arithmetic average.
I am having trouble breaking the loop when the score entered is less than 0 or more than 100.
The code I have is
total_sum = 0
count = 0
avg = 0
numbers = 0
while True:
num = input("Enter student test score: ")
if num == "999":
break
if num < "0":
break
print("Number is incorrect")
if num > "100":
break
print ("Number is incorrect")
total_sum += float(num)
count += 1
numbers = num
avg = total_sum / count
print("The average is:", avg)
print("There were " +str(count) + " numbers entered")
There are multiple issues with your code.
You want to compare numbers, not strings. Try using float(input(...))
break will break out of the loop in exactly the same way for numbers under 0, above 100, or for the "finished" token 999. That's not what you described that you want. Rather, for "incorrect numbers" just print the message, and don't add the numbers and counter...But no need to break the loop, amirite?
You've got an indentation problem for the < 100 case. Your print is missing an indentation.
No need to have avg = 0
numbers isn't used
Try something like -
total_sum = 0
count = 0
while True:
num = float(input("Enter student test score: "))
if num == 999:
break
elif num < 0 or num > 100:
print("Number is incorrect")
else:
total_sum += num
count += 1
avg = total_sum / count
print("The average is:", avg)
print("There were " +str(count) + " numbers entered")
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)
i = 0
integers = []
total = 0
while i < 10:
num = input('Enter an integer: ')
try:
integers.append(int(num))
i = i + 1
except:
print('Bad input')
for i in integers:
total = total + 1
average = total / 10
print('this is the list of integers you entered: ',(integers))
print('The lowest number is: ',min(integers))
print('The highest number is: ',max(integers))
print('This is the average of all integers: ',(average))
sorted_list = sorted(integers)
print('The integers list sorted in ascending sequence: ',(sorted_list))
sorted_list.reverse()
print('The integers list sorted in descending sequence: ',(sorted_list))
currently the total is equal to however many integers i enter i understand its from
total = total + 1 how would i go about getting the total to be the total of all integers entered?
Just do
total = total + i
and check the indentation in the line
num = input('Enter an integer: ')
it should be one level indside
You don't need a loop. Python has a sum function
total = sum(integers)