How can I solve this exercise on iteration in python? - 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)

Related

Unable to break on empty string

I'm attempting to get not more than 10 user inputs. The user can choose to stop giving input by inputing an empty string
container_size = []
for i in range(10):
while True:
container_size.append(float(input('What is the size of your container?: ')))
if input('What is the size of your container?: ') == '':
break
if i <= 1:
refund = 0.10
else:
refund = 0.25
print(refund)
I keep getting an error when trying to break if no input is given. What can I do? I am also getting more than 10 inputs.
You call for input() twice: once for add to container, and second time in the if. So for every iteration, you are asking for 2 inputs. Therefore you have a total of 20 inputs instead of ten. Put it in a variable, and ask if the variable is empty/add variable to container.
your break statement currently refer to the if statement and not the while, because it interacts with closest statement which is the if. You can overcome this by using flag and check it at the end of the while statement.
container_size = []
refund = []
i = 0
for i in range(10):
try:
container_size.append(float(input('What is the size of your container?: ')))
except ValueError:
break
for x in container_size:
if x <= 1:
refund.append(0.10)
else:
refund.append(0.25)
print(sum(refund))
I corrected the code already. Thank you.

Creating a loop and calculating the average at the end

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)`

Does While loop ends when the program return value?

I am a new learner for Python. I have a question about while loop.
I wrote a program below to look for square roots.
When I input anything but integers, the message "is not an integer" shows up and it repeats itself until I input correct data(integers).
My question is, why does it end loop when it return value on line 5, return(int(val))?
Thank you for your attention.
def readInt():
while True:
val = input('Enter an integer: ')
try:
return(int(val))
except ValueError:
print(val, "is not an integer")
g = readInt()
print("The square of the number you entered is", g**2)
To answer your original question, 'return' effectively exits the loop and provide the result that follows the 'return' statement, but you have to explicity print it like so:
def read_int(num1, num2):
while True:
return num1 + num2
print(read_int(12, 15))
If you simply put 'read_int(12, 14)' instead of 'print(read_int(12, 15))' in this scenario, you won't print anything but you will exit the loop.
If you allow me, here are some modifications to your original code:
def read_int(): # functions must be lowercase (Python convention)
while True:
val = input('Enter an integer: ')
try:
val = int(val) # converts the value entered to an integer
minimum_value = 0 # There is no need to evaluate a negative number as it will be positive anyway
maximum_value = 1000000 # Also, a number above 1 million would be pretty big
if minimum_value <= val <= maximum_value:
result = val ** 2
print(f'The square of the number you entered is {result}.')
# This print statement is equivalent to the following:
# print('The square of the number you entered is {}.'.format(result))
break # exits the loop: else you input an integer forever.
else:
print(f'Value must be between {minimum_value} and {maximum_value}.')
except ValueError: # If input is not an integer, print this message and go back to the beginning of the loop.
print(val, 'is not an integer.')
# There must be 2 blank lines before and after a function block
read_int()
With the final 'print' that you actually have at the end of your code, entering a string of text in the program generates an error. Now it doesn't ;). Hope this is useful in some way. Have a great day!

Having issues with a program to input multiple numbers from the user, till the user types “Done". To compute their average and print the results

So here is how the program is supposed to work. The user would input something like this and the output would give them the answer.
Input:
1
2
2
1
Done
Output:
1.5
So far I was able to come up with the input question and got it to loop until you put Done.
nums = [] # Empty list.
while True:
num = input("Enter number, or Done to end:")
if num == "Done":
break
else:
nums.append(int(num))
I don't know how to make the program perform the calculation to print out the average. I am very new to programming in python and I would appreciate any help I can get on fixing this program. Thanks in advance!
Break while loop when 'Done' is the input, else save the number as float. This throws an error if you try to enter 'finish'. Finally calculate and print the Average.
nums = [] # Empty list.
while True:
num = input("Enter number, or Done to end:")
if num == "Done": # This has to be tested inside the while loop
break
# Only append after testing for 'Done'
nums.append(float(num)) # Ensure valid input by convert it into the desired type.
print('average: %s' % (sum(nums) / len(nums)))
It is a good practice to give the user useful error messages, when some input is not as the program needs it. It can save the user lots of trouble. If you just want to tell the user what the problem was when an invalid input is given, you can do it with a try statement as below:
nums = [] # Empty list.
while True:
num = input("Enter number, or Done to end:")
if num == "Done":
break
try:
nums.append(float(num))
except Exception:
print('Please enter a number. Input "%s" will be ignored.' % num)
print('average: %s' % (sum(nums) / len(nums)))

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

Categories

Resources