I'm trying to write a small program to calculate numbers from the user. There's also some conditions to check if the number is positive or the user just hits enter. For some reason, I can't get the data variable to convert into a float.
The error occurs on line 5 where I get the error "ValueError: could not convert string to float:" I've tried so many combinations now, and tried to search StackOverflow for the answer, but without any luck.
How can I convert the input into a float? Thanks in advance for any help!
sum = 0.0
while True:
data = float(input('Enter a number or just enter to quit: '))
if data < 0:
print("Sorry, no negative numbers!")
continue
elif data == "":
break
number = data
sum += data
print("The sum is", sum)
Instead of having the user press enter to quit, you can instead write:
sum = 0.0
while True:
data = float(input('Enter a number or "QUIT" to quit: '))
if data.upper() != "QUIT":
if data < 0:
print("Sorry, no negative numbers!")
continue
elif data == "":
break
number = data
sum += data
print("The sum is", sum)
You can't convert an empty string to a float.
Get the user's input, check if it's empty, and if it's not, then convert it to a float.
You can check if the data is empty before convert to float with this way:
sum = 0.0
while True:
data = input('Enter a number or just enter to quit: ')
if data != "":
data = float(data);
if data < 0:
print("Sorry, no negative numbers!")
continue
number = data
sum += data
print("The sum is", sum)
else:
print("impossible because data is empty")
You have to first check for the empty string and then convert it to float.
Also you might want to catch malformed user input.
sum = 0.0
while True:
answer = input('Enter a number or just enter to quit: ')
if not answer: # break if string was empty
break
else:
try:
number = float(data)
except ValueError: # Catch the error if user input is not a number
print('Could not read number')
continue
if number < 0:
print('Sorry, no negative numbers!')
continue
sum += data
print('The sum is', sum)
In python, empty things like '' compare like False, it's idiomatic to use this in comparisons with if not <variable> or if <variable>.
This also works for empty lists:
>>> not []
True
And for None
>>> not None
True
And pretty much everything else that could be described as empty or not defined like None:
Related
I'm trying to work out the average of numbers that the user will input. If the user inputs nothing (as in, no value at all) I want to then calculate the average of all numbers that have been input by the user upto that point. Summing those inputs and finding the average is working well, but I'm getting value errors when trying to break the loop when the user inputs nothing. For the if statement I've tried
if number == ''
First attempt that didn't work, also tried if number == int("")
if len(number) == 0
This only works for strings
if Value Error throws up same error
Full code below
sum = 0
while True :
number = int(input('Please enter the number: '))
sum += number
if number == '' :
break
print(sum//number)
Error I'm getting is
number = int(input('Please enter the number: '))
ValueError: invalid literal for int() with base 10:>
Any help much appreciated!
EDIT: Now getting closer thanks to the suggestions in that I can get past the problems of no value input but my calculation of average isn't working out.
Trying this code calculates fine but I'm adding the first input twice before I move to the next input
total = 0
amount = 0
while True :
user_input = input('Please enter the number: ')
try:
number = int(user_input)
total = number + number
amount += 1
except:
break
total += number
print(total/amount)
Now I just want to figure out how I can start the addition from the second input instead of the first.
sum = 0
while True :
number = input('Please enter the number: '))
if number == '' :
break
sum += int(number)
print(sum//number)
try like this
the issue is using int() python try to convert input value to int. So, when its not integer value, python cant convert it. so it raise error. Also you can use Try catch with error and do the break.
You will always get input as a string, and if the input is not a int then you cant convert it to an int. Try:
sum = 0
while True :
number = input('Please enter the number: ')
if number == '' :
break
sum += int(number)
print(sum//number)
All of the answers dont work since the print statement referse to a string.
sum = 0
while True :
user_input = input('Please enter the number: ')
try:
number = int(user_input)
except:
break
sum += number
print(sum//number)
including a user_input will use the last int as devisor.
My answer also makes sure the script does not crash when a string is entered.
The user has to always input something (enter is a character too) for it to end or you will have to give him a time limit.
You can convert character into int after you see it isn't a character or
use try & except.
sum = 0
i = 0
while True :
try:
number = int(input('Please enter the number: '))
except ValueError:
break
i += 1
sum += number
try:
print(sum/number)
except NameError:
print("User didn't input any number")
If you try to convert a character into int it will show ValueError.
So if this Error occurs you can break from the loop.
Also, you are trying to get the average value.
So if a user inputs nothing you get NameError so you can print an Error message.
I need some help regarding calculating averages and ranges. I am using built-in functions such as sum(), len(), etc. and cannot seem to calculate the average or range. I am using it to write a small piece of code for fun but cannot seem to get it to work. any help is much appreciated. Thank you!
x = 1
number_list = []
while x == 1:
input_number = input("PLease input an integer")
if str.isdigit(input_number) == True:
number_list.append(input_number)
else:
print("Please input a valid integer only.")
continueornot = input("Would you like to continue adding data? PLease input 'Yes' to continue, and anything else to quit.")
if continueornot == 'Yes':
x = 1
else:
print("Here is the maximum number:", max(number_list))
print("Here is the minimum number:", min(number_list))
print("Here is the count:", len(number_list))
print("Here is the average:" + sum(number_list) / len(number_list))
print("Here is the range:", range(number_list))
quit()
Change
if str.isdigit(input_number) == True:
number_list.append(input_number)
to
if input_number.isdigit():
number_list.append(int(input_number))
The error is because you're trying to do those operations on a list of strings.
You can also remove the check against True since that is implicitly checking the truthiness and since input_number is already a str, you can call the isdigit() method directly.
The problem is that you are appending strings to the list rather than integers and then you are applying arithmetic operations on it. So first you should convert the input number to int type.
Secondly range function will not give you the range of a list rather then it returns a sequence.
x = 1
number_list = []
while x == 1:
input_number = input("PLease input an integer")
if str.isdigit(input_number) == True:
input_number=int(input_number)
number_list.append(input_number)
else:
print("Please input a valid integer only.")
continueornot = input("Would you like to continue adding data? PLease input 'Yes' to continue, and anything else to quit.")
if continueornot == 'Yes':
x = 1
else:
print("Here is the maximum number:", max(number_list))
print("Here is the minimum number:", min(number_list))
print("Here is the count:", len(number_list))
print("Here is the average:" , sum(number_list) / len(number_list))
print("Here is the range:", max(number_list)-min(number_list))
I am creating a function for my python course that receives a list and returns the same list without the smallest number. However, I wanted to extend the function to ask the user for inputs to create the list after performing some data validations on the inputs.
I was able to validate the first input. However, I got stuck at the second data validation as I need to guarantee that the program should accept only integers in the list and throw and prompt the user again for every wrong input something like while not (type(number) == int) which breaks as soon as the user input matches an int.
How should I do this?
def smallest():
# This function asks the user for a list
# and returns the same list without the smallest number or numbers
list_range = 'Not a number'
list_created = []
while not (type(list_range) == int):
try:
list_range = int(input('Please enter the total number of elements for your list: '))
except:
print('Please provide a number!')
for number in range(1,list_range + 1):
try:
list_element = int(input('Please enter the value of the %d element: ' %number))
list_created.append(list_element)
except:
print('Please provide a number!')
smallest = min(list_created)
result = []
for num in list_created:
if num != smallest:
result.append(num)
return result
Thanks for the help in advance!
You could use a while loop until an int value is entered:
for number in range(1, list_range + 1):
while True:
list_element = input('Please enter the value of the %d element: ' % number)
try:
list_element = int(list_element)
list_created.append(list_element)
break
except ValueError:
print('Please provide a number!')
numbers = []
first_input = input('Write any number.When you are done just write "done":')
numbers.append(first_input)
while first_input:
input_numb = input("Write next number")
if input_numb == int():
numbers.append(input_numb)
elif input_numb == "done":
print("The largest number is "+max(numbers))
print("The smallest number is "+min(numbers))
break
Can someone look at this code and tell me what I did wrong please? After I put the input numbers I want to print the biggest and smallest number from the list numbers but I don't know why the max function does not return the biggest number, instead it returns the smallest one (just like the min function. Why?
numbers = []
first_input = input('Write any number.When you are done just write "done":')
numbers.append(int(first_input))
while first_input:
input_numb = input("Write next number")
try:
numbers.append(int(input_numb))
except:
if input_numb == "done":
print("The largest number is ", max(numbers))
print("The smallest number is ", min(numbers))
break
else:
print('invalid input!')
out:
Write any number.When you are done just write "done":1
Write next numbera
invalid input!
Write next number2
Write next number3
Write next number6
Write next numberdone
The largest number is 6
The smallest number is 1
int() will return 0:
class int(x, base=10)
Return an integer object constructed from a number or string x, or
return 0 if no arguments are given.If x is a number, return x.__int__(). For floating point numbers, this truncates towards
zero.
In [7]: int() == 0 == False
Out[7]: True
you should use max in a list of number not a list of string, convert string to int before you append it to list
"The largest number is " + max(numbers)
return :
TypeError: Can't convert 'int' object to str implicitly, just use , to concate the string and int.
you should convert your inputs to integers using int(my_input) then add them to the list my_list.append(int(my_input)) and use the max or min functions max(my_list) after getting all the inputs from the user
numbers = []
user_input = input('Write any number.When you are done just write "done": ')
while user_input != "done":
try:
numbers.append(int(user_input))
user_input = input("Write next number : ")
except ValueError:
user_input = input("please enter a valid number : ")
print("The largest number is ", max(numbers))
print("The smallest number is ", min(numbers))
I'm very new to python and trying to write some code so that the user enters something. If it's an integer it's sorted into the Numbers list, if it's a string it goes into the String list.
I want to be able to find the mean of all the numbers that are in the list and print out the result.
And in the String section I want to be able to print out everything within the string and its length.
User types 'save' to exit and if input is valid that's caught.
Numbers = []
String = []
while(True):
user_input = input("What's your input? ")
if user_input == "save":
break
elif user_input.isdigit():
Numbers.append(user_input)
for i in range(len(Numbers)):
Numbers[i] = int(Numbers[i])
print(sum(Numbers)/len(Numbers)
elif isinstance(user_input, str):
String.append(user_input)
print(String)
print (len(String)-1)
else:
print("Invalid input.")
break
#use isalpha to check enterted input is string or not
#isalpha returns a boolean value
Numbers = []
String = []
while(True):
user_input = input("input : ")
if user_input == "save":
break
elif user_input.isdigit():
Numbers.append(int(user_input))
print(sum(Numbers)/len(Numbers))
elif user_input.isalpha():
String.append(user_input)
print(String)
print (len(String))
else:
print("Invalid input.")
break
There is good thing called statistics.mean:
from statistics import mean
mean(your_list)
You are using Length, which has not been defined. I think what you wanted was
print(sum(Numbers)/len(Numbers))
and you probably don't want it inside the loop, but just after it (although that might be another typo).
I found other more convenient way to produce the mean: Use statistics model and output the mean.
#import useful packages
import statistics
#Create an empty list
user_list = []
#get user request
user_input = input("Welcome to the average game. The computer is clever enough to get the average of the list of numbers you give. Please press enter to have a try.")
#game start
while True:
#user will input their number into a the empty list
user_number = input("Type the number you want to input or type 'a' to get the average and quit the game:")
#help the user to get an average number
if user_number == 'a':
num_average = statistics.mean(user_list)
print("The mean is: {}.".format(num_average))
break #Game break
else:
user_list.append(int(user_number))
print(user_list)