How to break a while loop by not entering a value? - python

I'm trying to write a very simple program that uses a while loop to read in a series of float values and calculate their mean, terminating the loop when the user simply presses Enter without supplying a value.
This is what I have so far, but obviously it produces an error:
total = 0
num_values = 0
a = 0
while a != None:
a = raw_input("Number: ")
total = total + float(a)
num_values = num_values + 1
print "The number of values entered was ",num_values
print "The mean is ",total/num_values
Error:
total = total + float(a)
ValueError: could not convert string to float:
I understand why I get this error but I'm not sure what to do about it. Also, I know this could be done with lists or try and except, but I need to do it using a while loop.

You need to test for an empty string, and do so before converting to a float:
while True:
a = raw_input("Number: ")
if not a:
break
total = total + float(a)
num_values = num_values + 1
This loop is simply endless, and a break is executed to exit the loop.

Related

Python - script counts wrong, but why?

I'm just at the beginning to learn Python.
As an exercise I wrote this little script:
Write a program which repeatedly reads numbers until the user enters "done". Once "done" is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number,
detect their mistake using try and except and print an error message and skip to the next number.
It does what it should in general, but: When I played with it a little I noticed one strange behavior: As it takes several (int) numbers after the prompt it won't - and shouldn't - take characters. So far so good, but then I tried a float as input. The script won't take it as valid input but would count it and put the truncated number into the total.
Code:
total = float(0) # sum of items
count = int(0) # number of items
avrg = float(0) # average of items
input_in = True
while input_in:
try:
line = input('Enter a number: ')
if line == 'done':
print('total:', str(total),' count:', str(count),' average:', str(avrg))
break
print(line)
for itervar in line:
total = total + float(itervar)
count = count+1
avrg = total / count
except:
print('Invalid input')
Output:
Enter a number: 1.5
1.5
Invalid input
Enter a number: 5
5
Enter a number: 5
5
Enter a number: 5
5
Enter a number: done
total: 16.0 count: 4 average: 4.0
What I tried - and didn't work: Assign the variables line and/or itervar as float().
I tried the included Debugger but I'm not able to understand it.
I have no clue how this could work.
Your line:
for itervar in line:
Is walking over each character of the input, which for your first input (1.5) results in three iterations:
1
.
5
So for the first iteration, your total is increased by 1, and for the second iteration, you're trying to use . as a number, and failing. (Hence why your final value, after adding 5 + 5 + 5, is 16)
Instead of using a for loop to iterate over your input, you should look into converting the entire input string into a number.
And as an added bonus...
Consider whether you actually need to be recalculating your average each loop. Since you have the total, and the count, I'd recommend instead calculating your average value on-demand, as a result of those two numbers.
As you've already figured out, input() returns a string.
When you iterate through a string with a for loop, you iterate over each character individually. This means that, when you enter '1.5', you get three iterations:
itervar = '1'
itervar = '.'
itervar = '5'
Due to how you wrote your code, the first one goes correctly, but then when it tries to convert '.' to a float, it produces an error.
Why not just consider the entire input as a whole, instead of character-by-character?
line = input('Enter a number: ')
if line == 'done':
print('total:', str(total),' count:', str(count),' average:', str(avrg))
break
print(line)
total = total + float(line)
count = count+1
avrg = total / count

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!

Checking if input value is integer, command, or just bad data (Python)

I'm trying to do something (admittedly) simple. I want my function to take an input, run a few lines if it's an integer or print an error message if it's a string or exit the loop if it's a specific command (done). My problem is that it never detects an integer, instead always displaying the error message unless I'm exiting the loop.
#The starting values of count (total number of numbers)
#and total (total value of all the numbers)
count = 0
total = 0
while True:
number = input("Please give me a number: ")
#the first check, to see if the loop should be exited
if number == ("done"):
print("We are now exiting the loop")
break
#the idea is that if the value is an integer, they are to be counted, whereas
#anything else would display in the error message
try:
int(number)
count = count + 1
total = total + number
continue
except:
print("That is not a number!")
continue
#when exiting the code the program prints all the values it has accumulated thus far
avarage = total / count
print("Count: ", count)
print("Total: ", total)
print("Avarage: ", avarage)
From poking around a bit with the code, it seems like the problem lies with the (count = count + 1) and (total = total + 1), but I'm unable to see why. Any help greatly appreciated.
You aren't assigning your int(number) to anything, so it remains a string.
Two things you need to do. Change your exception handling to print the actual error, so that you have some clue as to what's going on. This code does the following.
except Exception as e:
print("That is not a number!", e)
continue
Output:
That is not a number! unsupported operand type(s) for +: 'int' and 'str'
Which means you are adding a string and an integer together, which you can't do. Looking at your code, you do that at:
try:
int(number) <------- This is not doing anything for your program
count = count + 1
total = total + number
You think it's permanently changing number to an int, so you can use it later, but it's not. It's just for that one line, so you'll need to move it two lines down like this:
try:
count = count + 1
total = total + int(number)

Python GTIN 8 Product calculator

This is my code below:
while True:
try:
number = int (str("Enter"))
if len(str(number)) != 7:
print('Incorrect')
if len(str(number)) == 7:
print('Okay')
multiplier = [3,1]
times = ""
total = 0
for index, digit in enumerate(list(str(number))):
total = total + int(digit)*multiplier[index%2]
times = times+str(int(digit)*multiplier[index%2])+", "
mof10 = total + (10 - total%10)
checkdigit = mof10 - total
final = str(number) + str(checkdigit)
print (times[:-1])
print(total)
print(mof10)
print(checkdigit)
print(final)
break
except ValueError:
print("Not a number")
When I run the code the except ValueError is the only thing that prints, but it does not stop printing it.
I would like to know how to make this code accept 8 digit numbers, then validate if its a multiple of 10 or not, if it is it should be valid.
Your program runs into an exception from the start.
number = int(str("Enter"))
The program is creating an integer called 'number'. However, your code is saving the text "Enter" as a string, then converting it into an integer.
What you need to do is replace 'str' with 'input'. This means the program will print 'Enter', and save the user input as an integer. What you were doing before was saving the text 'Enter' as a string, then converting to an int, which caused the exception and made Python run the 'except' code.

How to allow input only string value of "stop", "", then check and convert to float

Hi I am having trouble with the end of my loop. I need to accept the input as a string to get the "stop" or the "" but I don't need any other string inputs. Inputs are converted to float and then added to a list but if the user types "bob" I get the conversion error, and I cant set the input(float) because then I can't accept "stop".
Full current code is below.
My current thinking is as follows:
check for "stop, ""
check if the input is a float.
if its not 1 or 2, then ask for a valid input.
Any ideas please? If its something simple just point me in the direction and i'll try churn it out. Otherwise...
Thanks
# Write a progam that accepts an unlimited number of input as integers or floating point.
# The input ends either with a blank line or the word "stop".
mylist = []
g = 0
total = 0
avg = 0
def calc():
total = sum(mylist);
avg = total / len(mylist);
print("\n");
print ("Original list input: " + str(mylist))
print ("Ascending list: " + str(sorted(mylist)))
print ("Number of items in list: " + str(len(mylist)))
print ("Total: " + str(total))
print ("Average: " + str(avg))
while g != "stop":
g = input()
g = g.strip() # Strip extra spaces from input.
g = g.lower() # Change input to lowercase to handle string exceptions.
if g == ("stop") or g == (""):
print ("You typed stop or pressed enter") # note for testing
calc() # call calculations function here
break
# isolate any other inputs below here ????? ---------------------------------------------
while g != float(input()):
print ("not a valid input")
mylist.append(float(g))
I think the pythonic way would be something like:
def calc(mylist): # note the argument
total = sum(mylist)
avg = total / len(mylist) # no need for semicolons
print('\n', "Original list input:", mylist)
print("Ascending list:", sorted(mylist))
print ("Number of items in list:", len(mylist))
print ("Total:", total)
print ("Average:", avg)
mylist = []
while True:
inp = input()
try:
mylist.append(float(inp))
except ValueError:
if inp in {'', 'stop'}:
calc(mylist)
print('Quitting.')
break
else:
print('Invalid input.')

Categories

Resources