Error string to float - python

This is my code. I am doing a beginer execise. When I run the program
I can put the values, but when I go out of the loop the following error message appears:
a + = float (input ("Enter the product cost"))
ValueError: could not convert string to float:
Can someone help me?
Here it goes:
e = 0.25
f = 0.18
a = 0.0
while True:
a += float(input("Enter the product cost: "))
if a == "":
break
b = a*e
c = a*f
d = a+b+c
print ("tax: " + b)
print ("tips: " + c)
print ( "Total: " + d)

You are combining two operations on the same line: the input of a string, and the conversion of the string to a float. If you enter the empty string to end the program, the conversion to float fails with the error message you see; the error contains the string it tried to convert, and it is empty.
Split it into multiple lines:
while True:
inp = input("Enter the product cost: ")
if inp == "":
break
a += float(inp)

There are a couple of issues:
the check for a being an empty string ("") comes after the attempt to add it to the float value a. You should handle this with an exception to make sure that the input is numerical.
If someone doesn't enter an empty or invalid string, ever, then you get stuck in an infinite loop and nothing prints. That's because the indentation of your b, c, d calculations and the prints is outside of the scope of the while loop.
This should do what you want:
e = 0.25
f = 0.18
a = 0.0
while True:
try:
input_number = float(input("Enter the product cost: "))
except ValueError:
print ("Input is not a valid number")
break
a += input_number
b = a*e
c = a*f
d = a+b+c
print ("tax: ", b)
print ("tips: ", c)
print ( "Total: ", d)

Related

Prompting user to enter string until string starts with "A" then prints longest string

Problem
I'm trying to write a program where (1) the user inputs lines until he enters a line that has "A" in position 0 of the input, (2) then the program will print the line that had greater length.
The desired output is:
Enter a string: Faces all glow.
Enter a string: Time for summer fun
Enter a string: As the happy faces show.
Longest string: "As the happy faces show."
Attempt
This is what I tried at first but it doesn't work at all.
a, b, c, d, e, f, g = input("Enter seven values: ").split()
print("Enter a String: ", a)
print("Enter a String: ", b)
print("Enter a String: ", c)
print("Enter a String: ", d)
print("Enter a String: ", e)
print("Enter a String: ", f)
print("Enter a String: ", g)
print()
I must say what you are expecting and your sample code are not relevant at all. However, I think you are asking something like the following code can do
longestString = ""
a = " "
while a[0].capitalize() != 'A':
a = input("Enter a String: ")
if not a:
a = " "
if len(a) > len(longestString):
longestString = a
print(longestString)
Use a while loop and a flag (boolean variable) to achieve this:
#initialize
stringWithA = False #a flag, will be set to True if user enters string starting with A
currentMaxLength = 0
currentLongestStr = ''
while stringWithA == False: #haven't seen a string starting with A so far
x = input("Enter a string: ")
if x[0] == 'A':
stringWithA = True
if len(x) > currentMaxLength:
currentMaxLength = len(x)
currentLongestStr = x
print('"' + currentLongestStr + '"')
Your wording seems quite confusing and other comments seem to agree with me, but from what I understand the following code should give you the desired output:
inp = " "
longestString = ""
while inp[0] != 'A':
inp = input("Enter a String: ")
if len(inp) > len(longestString):
longestString = inp
# To make sure empty input does not break code
if len(inp) == 0:
inp+=" "
continue
print("Longest string: ", longestString)
A similar solution but with consideration to lines with the same length that it is the longest length.
inp = " "
longest = list()
length = 0
while inp[0] != 'A':
inp = input("Enter a String: ")
if len(inp) > length:
longest.clear()
length = len(inp)
# append will happen in the next if
if len(inp) == length:
longest.append(inp)
inp += " " # to avoid empty input
print("Longest :")
for x in longest:
print(x)
Notes
Most of the answers stop getting input after 'A' or 'a' when the question says only 'A'.

Python If Statements - Display numeric Results

I am writing a python code that returns me the larger of two inputs.
def bigger_num(a, b):
if a < b:
print ("First number is smaller than the second number.")
elif a > b:
print ("First number is greater than the second number.")
else:
print ("Two numbers are equals.")
a = input("Enter first number: ")
a = float(a)
b = input("Enter second number : ")
b = float(b)
print(bigger_num(a, b))
Result:
Enter first number: 19
Enter second number : 9
First number is greater than the second number.
None
How do I display the numeric result (a/b) in the print?
Ideal solution example: First number, 19 is greater than the second number
Also, is there a way to remove none from the print result?
You can use the format() method or simply concatenate the number to display it. To remove the None, just call the function without the wrapping it with a print() because you print the output inside the function
def bigger_num(a, b):
if a < b:
print ("First number, {0} is smaller than the second number.".format(a))
elif a > b:
print ("First number, {0} is greater than the second number.".format(a))
else:
print ("Two numbers are equals.")
a = input("Enter first number: ")
a = float(a)
b = input("Enter second number : ")
b = float(b)
bigger_num(a, b)

Average Function in Pycharm

I'm just starting to learn Python from a book. But I keep running into the same problem when I run my script, it says:
File "C:/Users/bob/Desktop/Python/Part3 A.py", line 8, in <module> print(' the average is: ', avg())
File "C:/Users/Bob/Desktop/Python/Part3 A.py", line 6, in avg average = a + b + c / 3
TypeError: unsupported operand type(s) for /: 'str' and 'int'
Did I install "Pycharm" wrong?
Here is my code
def avg():
a = input('please enter a: ')
b = input('please enter b: ')
c = input('please enter c: ')
average = a + b + c / 3
print(' the average is: ', avg())
Did I install "Pycharm" wrong? NO
in python 3 input returns a string
a = int(input("please enter a:")) #this will make the input an integer
# warning if the user enters invalid input it will raise an error
should work fine
you should also change your print line to
print(' the average is: ', avgerage)
you also need to pay attention to order of operations when you calculate the average
average = (a + b + c) / 3
is what you want
you also have indentation problems but im pretty sure thats cause you copied and pasted wrong ... otherwise you would have a different error
def avg():
a = intinput('please enter a: ')
b = input('please enter b: ')
c = input('please enter c: ')
average = a + b + c / 3
print(' the average is: ', avg())
try this instead
def avg():
a = input('please enter a: ')
b = input('please enter b: ')
c = input('please enter c: ')
average = int(a) + int(b) + int(c) / 3
print(' the average is: ', avg())
return;
P.S: Python is indent sensitive
You've got many errors, which are as follows:
def avg():
a = int(input('Please enter a: '))
b = int(input('Please enter b: '))
c = int(input('Please enter c: '))
average = (a + b + c) / 3
print('The average is:', average)
avg() # call function outside
Indent 4 spaces under the scope of the function.
Cast the string input to integers with built-in int.
Use parenthesis, otherwise math is wrong by PEMDAS.
Lastly, print the average, don't call function recursively.
You are trying to divide a string by an integer.
You need to convert your inputs to integers.
def avg():
a = int(input('please enter a: '))
b = int(input('please enter b: '))
c = int(input('please enter c: '))
average = (a + b + c) / 3
return average
print(' the average is: ', avg())
You are applying arithmetic operations on string input. Convert it to int before using
int(input('please enter a: '))

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

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.

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