I'm trying to validate an array of user inputs (pints of blood collected per hour over 7 hours) for negative numbers, spaces, and/or letters. Currently, with an if statement checking user input is below 0, the program receives type error: "'<' not supported between instances of 'list' and 'int'."
inputPints = []
totalPints = 0
hours = ["#1", "#2", "#3", "#4", "#5", "#6", "#7"]
def userInput():
for hour in hours:
inputPints.append(int(input("Enter pints collected for hour {}: ".format(hour))))
if inputPints<0:
inputPints.append(int(input("Please enter a whole number {}: ".format(hour))))
userInput()
def userOutput():
print("")
print("Average number of pints donated is: ", "{:.2f}".format(import_functions.averagePints(totalPints, 7)))
print("Most pints donated is: ", import_functions.maxPints())
print("Least pints donated is: ", import_functions.minPints())
print("")
userOutput()
I think you should define your userInput() method like this …
def userInput():
for hour in hours:
user_input = -1
while user_input < 0:
try:
user_input = int(input("Enter pints collected for hour {}: ".format(hour)))
except:
user_input = -1
if user_input > -1:
inputPints.append(user_input)
You can use regex to validade your input.
To allow only the form #number.numbers, you can use the following for instance:
# test for matches on the regex expression.
if len(re.findall('^#\d+.\d+$', "#-1.30")) > 0:
# It is valid
return true
Just as Torxed commented, you are comparing an object of the "list" type vs an object of the "int" type. This rises the error:
'<' not supported between instances of 'list' and 'int'
Yo should either validate user input before appending it to the list, or you could loop over the complete list to find wrong/right inputs.
Checking input before appending:
if int(input("Enter pints collected for hour {}: ".format(hours))) > 1:
#This is ok
Checking input with complete list
for a in inputPints:
if int(a) > 1:
#a is OK.
I recommend you put those validations inside a try catch block, since the int() casting may break your code if it detects a non-castable character.
Hope this helps!
Regards
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 am completing questions from a python book when I came across this question.
Write a program which repeatedly reads numbers until the user enters "done". Once done is entered, print out total, count, and average of the numbers.
My issue here is that I do not know how to check if a user specifically entered the string 'done' while the computer is explicitly checking for numbers. Here is how I approached the problem instead.
#Avg, Sum, and count program
total = 0
count = 0
avg = 0
num = None
# Ask user to input number, if number is 0 print calculations
while (num != 0):
try:
num = float(input('(Enter \'0\' when complete.) Enter num: '))
except:
print('Error, invalid input.')
continue
count = count + 1
total = total + num
avg = total / count
print('Average: ' + str(avg) + '\nCount: ' + str(count) + '\nTotal: ' + str(total))
Instead of doing what it asked for, let the user enter 'done' to complete the program, I used an integer (0) to see if the user was done inputting numbers.
Keeping your Try-Except approach, you can simply check if the string that user inputs is done without converting to float, and break the while loop. Also, it's always better to specify the error you want to catch. ValueError in this case.
while True:
num = input('(Enter \'done\' when complete.) Enter num: ')
if num == 'done':
break
try:
num = float(num)
except ValueError:
print('Error, invalid input.')
continue
I think a better approach that would solve your problem would be as following :
input_str = input('(Enter \'0\' when complete.) Enter num: ')
if (input_str.isdigit()):
num = float(input_str)
else:
if (input_str == "done"):
done()
else:
error()
This way you control cases in which a digit was entered and the cases in which a string was entered (Not via a try/except scheme).
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.
My program is designed to let the user type in temperatures for a whole month. Then I've created functions that are supposed to let the user know a certain temperature for a day by typing in a requested date to see waht temperature he/she typed in for that day. Then there's funktions written to show an average temoerature, the lowest and the highest temperature (by finding these values from a list, where the user typed in the temperatures).
The programming isn't working that well, it answers the user without crashing but it doesn't show the right results. It "skips" to show the requested date, and prints out the whole list when the user asks for highest/lowest temperatures. When I try to get the average value, it crashes with the messange:
Traceback (most recent call last):
File "C:\Users\Linnea\Documents\Studier\HT 2014\Introduktion till programmering\Linnea_Andersson.py", line 58, in <module>
main ()
File "C:\Users\Linnea\Documents\Studier\HT 2014\Introduktion till programmering\Linnea_Andersson.py", line 9, in main
functions(temp_list)
File "C:\Users\Linnea\Documents\Studier\HT 2014\Introduktion till programmering\Linnea_Andersson.py", line 53, in functions
print("Average temperature was: " + str(sum(temp_list)/float(len(temp_list), str(round(total,2)))))
TypeError: unsupported operand type(s) for +: 'int' and 'list'
This is my code:
def main ():
temp_list = create_temp_list()
search()
functions(temp_list)
def create_temp_list ():
NUM_DAYS = 31
temp_list = [];
temperatur = [0] * NUM_DAYS
index = 0
print("Hi! Type in a temperature for each day in december!: ")
while index < NUM_DAYS:
print(index + 1, "/12", ": ", sep="", end="")
temperatur[index] = float(input())
index +=1
temp_list.append(temperatur)
return temp_list
def search():
temp_list = [1-31]
index = int(input("Vänligen skriv in en dag då du vill se temperaturen för: "))
while (index >= 1 and index < len(temp_list)):
print("The temperature this day was : ",(temp_list([index - 1])))
else:
print ("Ok")
x = [1,2,3]
try:
x[10]
except IndexError:
print("What are you trying to pull?")
def functions(temp_list):
svar1 =(input("To see the highest value, print 'ja': "))
if svar1 == "ja":
print("The highest temperature was: ", str(max(temp_list)))
else:
print ("This date wasn't found! You are now going to the next function.")
svar2 = (input("Too see the lowest temperature, print 'ja': "))
if svar2 == "ja":
print("Lowest temperature: ", str(min(temp_list)))
else:
print("This date wasn't found! You are now going to the next function.")
nyfiken = (input("To get the average temperature, print 'ja': "))
if nyfiken == "ja":
print("Average temperature was: " + str(sum(temp_list)/float(len(temp_list), str(round(total,2)))))
else:
print("This date wasn't found! The program is now closing.")
#Funktionen skriver ut medelsnittsvärdet
main ()
Could anybody help me??
> TypeError: unsupported operand type(s) for +: 'int' and 'list'*`
You trying to summation between int and list. Make a for loop on lists first, access the every element of them, then you can make summation.
if nyfiken == "ja":
print("Average temperature was: " + str(sum(temp_list)/float(len(temp_list),str(round(total,2)))))
Problem is here, as I said make a for loop on temp_list and access every element, then make summation.
Also you converting them to string, I dont think you can make summation with strings. You will get an output like :
>>> a=10
>>> b=20
>>> str(a)+str(b)
'1020'
>>>
Besides you can sum values by following this way:
sum1=0
timer=0
y=int(input("How much values do you want to sum?: "))
while True:
x=int(input("Entry values: "))
timer+=1
sum1+=x #sum1=0, we summing every value with eachother. 0 is ineffective value in summation.
if timer==y:
print ("Summation of your values: ",sum1)
break
You have a number of problems; we will approach them in order:
create_temp_list is supposed to return a list of float - but because of the way you use temp_list and temperatur and the way Python handles object assignment, it is actually returning a list of references to a list of float, ie temp_list[0] == temp_list[1] == temp_list[2] ... == temperatur. Instead, try
NUM_DAYS = 31
def get_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
pass
def create_temp_list():
print("Hi! Type in a temperature for each day in december!: ")
make_prompt = "{}/12: ".format
return [get_float(make_prompt(day)) for day in range(1, NUM_DAYS+1)]
You never pass temp_list to search(); your program should look more like
def main():
temp_list = create_temp_list()
search(temp_list) # <= pass the data to search!
functions(temp_list)
def search(temp_list):
...
Because of (2), temp_list is not in scope (you cannot see that variable in search). To fix this, you tried to make test data like temp_list = [1-31]. This doesn't do what you think; it makes a one-item list containing the value -30. Then len(temp_list) is always 1, and index >= 1 and index < len(temp_list) is always False - which is good, because otherwise you would be stuck in an endless while loop! (It should be if ... else, not while ... else).
Hope that helps.
I'm currently working on a program in Python and I need to figure out how to convert a string value to a float value.
The program will ask the user to enter a number, and uses a loop to continue asking for more numbers. The user must enter 0 to stop the loop (at which point, the program will give the user the average of all the numbers they entered).
What I want to do is allow the user to enter the word 'stop' instead of 0 to stop the loop. I've tried making a variable for stop = 0, but this causes the program to give me the following error message:
ValueError: could not convert string to float: 'stop'
So how do I make it so that 'stop' can be something the user can enter to stop the loop? Please let me know what I can do to convert the string to float. Thank you so much for your help! :)
Here is some of my code:
count = 0
total = 0
number = float(input("Enter a number (0, or the word 'stop', to stop): "))
while (number != 0):
total += number
count += 1
print("Your average so far is: " , total / count)
number = float(input("Enter a number (0, or the word 'stop', to stop): "))
if (number == 0):
if (count == 0):
print("")
print("Total: 0")
print("Count: 0")
print("Average: 0")
print("")
print("Your average is equal to 0. Cool! ")
else:
print("")
print("Total: " , "%.0f" % total)
print("Count: " , count)
print("Average: " , total / count)
Please let me know what I should do. Thanks.
I'd check the input to see if it equals stop first and if it doesn't I'd try to convert it to float.
if input == "stop":
stop()
else:
value = float(input)
Looking at your code sample I'd do something like this:
userinput = input("Enter a number (0, or the word 'stop', to stop): ")
while (userinput != "stop"):
total += float(userinput) #This is not very faulttolerant.
...
You could tell the user to enter an illegal value - like maybe your program has no use for negative numbers.
Better, would be to test if the string you've just read from sys.stdin.readline() is "stop" before converting to float.
You don't need to convert the string to a float. From what you've said it appears that entering 0 already stops the loop, so all you need to do is edit you're currently existing condition check, replacing 0 with "stop".
Note a few things: if the input is stop it will stop the loop, if it's not a valid number, it will just inform the user that the input were invalid.
while (number != 0):
total += number
count += 1
print("Your average so far is: " , total / count)
user_input = input("Enter a number (0, or the word 'stop', to stop): ")
try:
if str(user_input) == "stop":
number = 0
break
else:
number = float(user_input)
except ValueError:
print("Oops! That was no valid number. Try again...")
PS: note that keeped your code "as is" mostly, but you should be aware to not use explicit counters in python search for enumerate...