Converting string to float with Python 3.2 - python

The purpose of this program is to display the sum, average, max, and min of use based input.
count=0.0
Sum=0.0
average=0.0
data=float(input("Enter a number or just ENTER to quit:"))
Min=data
Max=data
while data!="":
count+=1
number=float(data)
Sum+=number
average=Sum/count
if data<Min:
Min=data
if data>Max:
Max=data
data=float(input("Enter a number or just ENTER to quit:"))
print(count,("numbers entered."))
print("Sum:",Sum)
print("Average:",average)
print("Min:",Min)
print("Max:",Max)
The problem is with line 20:
data=float(input("Enter a number or just ENTER to quit:"))
When i press ENTER to end the loop it says that it was unable to convert string to float and errors. What am I doing wrong ?????

Well, you shouldn't convert to float immediately. Also, this is not how you do do..while loop in Python.
while True:
data = input('Enter a number or ENTER to quit: ')
if not data: break
data = float(data)
# ...
This way you don't have to duplicate code, or to prolong the life of data name unnecessarily.

By default, the data type of input is string. Pressing ENTER will return an empty string which cannot be casted into a float, since the string is empty and there is nothing to be casted, which is generating the error. Here are two solutions to handle this error.
Solution 1
Do not cast input into float directly, but cast it when assigning the value of input to any variable.
data=input("Enter a number or just ENTER to quit:")
Add the following statement before the loop to handle the condition when the user wants to exit without entering any number.
if not data: # If user wants to exit without entering any number
Max = 0
Min = 0
else: # Cast the inputs by user to float
Max = float(data)
Min = float(data)
Lastly add the following line at the beginning inside the loop.
data = float(data)
Complete Code
count=0.0
Sum=0.0
average=0.0
data=input("Enter a number or just ENTER to quit:")
if not data:
Max = 0
Min = 0
else:
Max = float(data)
Min = float(data)
while data!='':
data = float(data)
count+=1
number=float(data)
Sum+=number
average=Sum/count
if data<Min:
Min=data
if data>Max:
Max=data
data=input("Enter a number or just ENTER to quit:")
print(count,("numbers entered."))
print("Sum:",Sum)
print("Average:",average)
print("Min:",Min)
print("Max:",Max)
Solution 2
What you can also do is set a default value for empty inputs. Here since you are casting input into a float, you can set any number as the default value for empty inputs. However, I will not prefer this because if the user enters the same number as the default value, the loop will be terminated. In the following example I've only modified two lines of your code and set the default value for empty inputs as 0.
count=0.0
Sum=0.0
average=0.0
data=float(input("Enter a number or just ENTER to quit:") or 0)
Min=data
Max=data
while data!=0:
count+=1
number=float(data)
Sum+=number
average=Sum/count
if data<Min:
Min=data
if data>Max:
Max=data
data=float(input("Enter a number or just ENTER to quit:") or 0)
print(count,("numbers entered."))
print("Sum:",Sum)
print("Average:",average)
print("Min:",Min)
print("Max:",Max)

The float() function raises an exception for blank inputs. You must catch this exception for your loop to work as intended. Here is the simplest fix:
In Python 2.x, it is actually the input() call that raises the exception, not float(). So, if you are using Python 2.x, my solution is the only one here that works.
while True:
count+=1
Sum+=data
average=Sum/count
if data<Min:
Min=data
if data>Max:
Max=data
try:
data=float(input("Enter a number or just ENTER to quit:"))
except:
break

Your variable names are incorrect, because sum, min, and max are all functions. Change them to different names such as "datasum", "datamin", and "datamax", so that the program does not confuse them with the functions.

Python by default takes input in the string format only. Don't do direct type casting in python like string to float. It will give an error immediately.
The best way to conversion of type string to float is::
string_data = input("enter the data")
enter the data 123
string_data '123'
float_data = float(string_data)
float_data 123.0

Related

How to detect if input is not given in a python program

I have a python program where it prompts a user input for position or index and deletes the element in the list based on the position or index. The python program works but I'm having issues with the condition where if no user input is given, it automatically deletes the whole line in the list.
Example:
lst = [1,2,3,4,5]
enter position: 2
output: [1,2,4,5]
enter position: #user just pressed enter without giving any input
output: []
I'm writing the function within a class whereby:
def delete(self,index):
"""
This function deletes an item based on the index
:param self: the array
:param index: the index of an item in the array
:return: the array is updated
:raises: IndexError if out of range
"""
if not index:
self.__init__()
if index<0:
index = index + self.count
for i in range(index, self.count -1):
self._array[i] = self._array[i+1]
self.count-=1
and prompting the user input is as such:
position = int(input("Enter position:"))
it's not possible to just press 'enter' without receiving an error due to the position only receiving integers hence I'm looking for a method where if the user doesn't give any position, it registers it and prints just an empty list instead of an error message.
What you're looking for is the try-except block. See the following for an example:
input_invalid = true
while input_invalid:
user_input = input("Enter position: ")
try:
user_input = int(user_input)
input_invalid = false
except ValueError:
print("Please enter a valid integer!")
Here, the try-except block catches any errors (of the type specified
in except) thrown within the code block. In this case, the error results from trying to call int() on a string that does not contain an integer (ValueError). You can use this to explicitly prevent the error and control the logic flow of your program like shown above.
An alternate solution without using try-except is to use the .isdigit() method to validate the data beforehand. If you were to use .isdigit() (which I personally think is better), your code would look something like this:
input_invalid = true
while input_invalid:
user_input = input("Enter position: ")
if user_input.isdigit():
input_invalid = false
else:
print("Please enter a valid integer!")
Hope this helped!

Python2.7-: Storing user input values input in a list

I am new to python and came around a scenario explained below-:
This is one from the .pdf I am referring to learn. Would be great if anyone could guide or share some other resources.
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.
Enter a number: 4
Enter a number: 5
Enter a number: bad data
Invalid input
Enter a number: 7
Enter a number: done
16 3 5.333333333333333*
I am unable to store the values into list.
Tried going with this logic-:
while True:
line = input('Enter Number-: ')
if type(line) == int():
continue
if line == 'done':
break
print(line)
print('Done!')
Just need to know how to store into lists without using spaces or commas,
The user should be able to enter the value as shown in example above and those should get stored in a list.
Thanks in advance.
In Python 2.7, input will evalulate any entry and will fail if the input is not a correct Python type to begin with. It's better to use raw_input here as any entry will be considered a string. If you move to Python 3, raw_input was removed and input acts how raw_input did. So your example expects you to give it '45' or 'done' instead of 45 or done.
But the reason you're unable to store any values into a list is because you're not adding them to a list in the first place. But since we've also switched to raw_input, we don't know if the entry is a valid number or not. So we need to try to convert it to a number and if it isn't one, then check to see if it's the keyword telling the code to stop.
values = [] # make an empty list
while True:
line = raw_input('Enter Number-: ') # all entries here are considered strings
try:
num = int(line) # convert to an integer
values.append(num) # add to list
continue # return to input query
except: # int(line) threw an error, so not a valid number input
if line == 'done': # check if should stop
break # get out of loop
else: # anything else
print 'bad data, invalid input'
continue # return to input query
print 'Done!\n'
print 'total:', sum(values)
print 'count:', len(values)
print 'average:', sum(values) / float(len(values))
If you're entering more than just integers, you may wish to change num = int(line) to num = float(line) to handle decimal inputs, as int only accepts integers.
Enter Number-: 4
Enter Number-: 5
Enter Number-:
bad data, invalid input
Enter Number-: 7
Enter Number-: done
Done!
total: 16
count: 3
average: 5.33333333333
The Tutorial may also be helpful in learning Python.

While loop to identify integer in Python

I'm trying to write a program to calculate densities, and I have tried to create a while loop the prevents the user from entering nothing or a non-number for the volume.
But when I run the program the it just loops "You have to type a value" forever. I've tried the same code in a for loop and it does work after inputing 2 numbers.
def GetVolume():
print("How many cublic cm of water does the item displace")
Volume = input()
while Volume == ("") or type(Volume) != int:
print("You have to type a value")
Volume = input()
return float(Volume)
This solution is written assuming you are using Python 3. The problem in your code is that you are assuming that if you type in a number, the input method will return a type int. This is incorrect. You will always get a string back from your input.
Furthermore, if you try to cast int around your input to force an int, your code will raise if you enter a string, with:
ValueError: invalid literal for int() with base 10:
So, what I suggest you do to make your implementation easier is to make use of try/exceptinstead to attempt to convert your value to a float. If it does not work, you prompt the user to keep entering a value until they do. Then you simply break your loop and return your number, type casted to a float.
Furthermore, because of the use of the try/except, you no longer need to put in a conditional check in your while loop. You simply can set your loop to while True and then break once you have satisfied your condition in your code.
Observe the code below re-written with what I mentioned above:
def GetVolume():
print("How many cublic cm of water does the item displace")
Volume = input()
while True:
try:
Volume = float(Volume)
break
except:
print("You have to type a value")
Volume = input()
return Volume
def GetVolume():
Volume = input("How many cublic cm of water does the item displace")
while not Volume.replace('.', '').replace(',', '').isdigit():
Volume = input("You have to type a value")
return float(Volume)
x = GetVolume()
print(x)
You have to modify your while because is validating that is str or different than int. An input will always be an str by default unless you modified the type with int() or float() in your case.
You can use 'try' instead to check for this:
while True:
x = input("How many cubic cm of water does the item displace")
try:
x = float(x)
break
except ValueError:
pass
print('out of loop')

Program asks twice for number if wrong data is input first

I am very new to Python (started 2 days ago). I was trying to validate positive integers. The code does validate the numbers but it asks twice after a wrong input is entered. For example if I enter the word Python, it says: This is not an integer! like is supposed to but if I enter 20 afterwards, it also says it is not an integer and if I enter 20 again it reads it.
def is_positive_integer(input):
#error: when a non-integer is input and then an integer is input it takes two tries to read the integer
flag = 0
while flag != 1:
try:
input = int(input)
if input <= 0:
print "This is not a positive integer!"
input = raw_input("Enter the number again:")
except ValueError:
print "This is not an integer!"
input = raw_input("Enter the number again: ")
if isinstance(input, int):
flag = 1
return input
number = raw_input("Enter the number to be expanded: ")
is_positive_integer(number)
number = int(is_positive_integer(number))
Any help is appreciated.
The main bug is that you call is_positive_integer(number) twice with the same input (the first thing you enter).
The first time you call is_positive_integer(number), you throw away the return value. Only the second time do you assign the result to number.
You can "fix" your program by removing the line with just is_positive_integer(number) on its own.
However, your code is a little messy, and the name is_positive_integer does not describe what the function actually does.
I would refactor a little like this:
def input_positive_integer(prompt):
input = raw_input(prompt)
while True:
try:
input = int(input)
if input <= 0:
print "This is not a positive integer!"
else:
return input
except ValueError:
print "This is not an integer!"
input = raw_input("Enter the number again: ")
number = input_positive_integer("Enter the number to be expanded: ")
The problem stems from the fact that you're calling is_positive_integer twice. So, the first time it's called, you send it a string like 'hello', then it says it's not an integer and tells you to try again. Then you enter '20', which parses fine, and it's returned.
But then you don't save a reference to that, so it goes nowhere.
Then you call the function again, this time saving a reference to it, and it first tries the original bad string, which was still there in number. Then it complains that it's a bad input, asks you for a new one, and you provide it, terminating the program.

IF statement error new variable input python

The problem here is that I just cant get python to check if Currency1 is in string, and if its not then print that there is an error,but if Currency1 IS in string then move on and ask the user to input Currency2, and then check it again.
You can use try-except:
def get_currency(msg):
curr = input(msg)
try:
float(curr)
print('You must enter text. Numerical values are not accepted at this stage')
return get_currency(msg) #ask for input again
except:
return curr #valid input, return the currency name
curr1=get_currency('Please enter the currency you would like to convert:')
curr2=get_currency('Please enter the currency you would like to convert into:')
ExRate = float(input('Please enter the exchange rate in the order of, 1 '+curr1+' = '+curr2))
Amount = float(input('Please enter the amount you would like to convert:'))
print (Amount*ExRate)
output:
$ python3 foo.py
Please enter the currency you would like to convert:123
You must enter text. Numerical values are not accepted at this stage
Please enter the currency you would like to convert:rupee
Please enter the currency you would like to convert into:100
You must enter text. Numerical values are not accepted at this stage
Please enter the currency you would like to convert into:dollar
Please enter the exchange rate in the order of, 1 rupee = dollar 50
Please enter the amount you would like to convert: 10
500.0
You were actually trying for:
if type(Currency1) in (float, int):
...
but isinstance is better here:
if isinstance(Currency1,(float,int)):
...
or even better, you can use the numbers.Number abstract-base class:
import numbers
if isinstance(Currency1,numbers.Number):
Although ... Currency1 = str(raw_input(...)) will guarantee that Currency1 is a string (not an integer or float). Actually, raw_input makes that guarantee and the extra str here is just redundant :-).
If you want a function to check if a string can be converted to a number, then I think the easiest way would be to just try it and see:
def is_float_or_int(s):
try:
float(s)
return True
except ValueError:
return False

Categories