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.
Related
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
I have this code in Python
def receipt(array):
sum = 0.0
for i in range(len(array)):
sum = sum + array[i]
return sum
array = []
while True:
print("Calculating Price")
n = input("Enter a price: ")
if n == "":
print("Goodbye")
break
array.append(n)
totalCost = receipt(n)
print("The total cost is " + str(totalCost))
And I'm wondering why this code won't work. There seems to be some error in the fourth line
sum = sum + array[i]
But I can't figure out which part of it is wrong. I believe I used the array[i] component correctly. Perhaps it's a string issue?
Question:
Which part of the code doesn't work?
What is my error?
I'm relatively new to computer science in general. Thanks for the help. Anything is appreciated!
I ran your code and got this error:
$ python test.py
Calculating Price
Enter a price: 24
Traceback (most recent call last):
File "test.py", line 14, in <module>
totalCost = receipt(n)
File "test.py", line 4, in receipt
sum = sum + array[i]
TypeError: unsupported operand type(s) for +: 'float' and 'str'
This means that in your sum = sum + array[i] line, the types don't match up. You need to wrap array[i] in a float() function to match array[i] to the type of sum, which is a float since you initialized it to 0.0. The docs say the input() function returns a string, and since you're appending n to array, you are trying to sum a string with a float. The line should look like this:
sum = sum + float(array[i])
Try running it again and the code works. Here is the documentation for input()
Edit: now to fix the issues were were having with the sum.
Here is a version of your code I have revised with corrections to do the addition the way you want.
1 def receipt(sumvar, n):
2 sumvar = sumvar + float(n)
3 return sumvar
4
5 array = []
6 sumvar = 0.0
7
8 while True:
9 print("Calculating Price")
10 n = input("Enter a price: ")
11 if n == "":
12 print("Goodbye")
13 break
14 totalCost = receipt(sumvar, n)
15 sumvar = totalCost
16 print("The total cost is " + str(totalCost))
As mentioned by others, sum isn't a great variable name so I've renamed it sumvar. Notice the sumvar declaration that is outside the function. When you initialize sumvar inside receipt() like you did, you will always be adding n to 0.0. I doubt this is what you want. Instead, you want to keep a running total of the item count, which needs to be passed into the function. I've also eliminated the loop from your function. This loop was actually iterating over the characters in array, not the elements as you expected it to.
First of there are several things wrong. I will explain each and everything.
Here is your complete working code:
def receipt(array):
total = 0.0
for i in array:
total = total + i
return total
array = []
while True:
print("Calculating Price")
n = input("Enter a price: ")
if n=="":
print("Goodbye")
break
array.append(float(n))
totalCost = receipt(array)
print("The total cost is " + str(totalCost))
Your Mistakes:
1)array.append(n) - First one. Pretty common for beginner.
input() in python gets user input as string. So your n is a String.
See there are data types in all languages. And Python is a Strongly typed language while perl is not. How to say if a language is strongly typed or weakly typed ? Simple. Try this in your interpreter.
>>> a=5
>>> b='9'
>>> a+b
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
a+b
TypeError: unsupported operand type(s) for +: 'int' and 'str'
See the error now try this,
>>> a=5
>>> b='9'
>>> a+int(b)
14
Works perfectly fine right. Python doesn't allow just a+b while some languages do example perl. Read more about it. So you can't add them you have to typecast. So change that into
array.append(int(n))
or
array.append(float(n))
If you are going to work with float values.
2) totalCost = receipt(n) See you are passing n to the function. But your function definition has def receipt(array):. What actually happens here is
receipt(n) ----> (calls) ---->def receipt(array):
Where n ------> array So your array is nothing but n. What you should do intead is
totalCost = receipt(array)
3) sum = 0.0 NEVER I said never use built-in or keyword names (ex ample : sum,min,max,int,str etc) as variable names. Read more about naming in PEP 8
So maybe rename sum to sum_ (it's the convention to be followed) However why can't you just rename sum to total much simpler right?
4) And finally
for i in range(len(array)):
sum = sum + array[i]
Why range(len(array)) when you can simply do for i in array:
Can't understand this take a look at this example:
>>> a = [1,2,3]
>>> for i in a:
print(i)
1
2
3
See for item in something would just take each and every item from a group of something ( iterable (list,tuple,set etc..))
So just change those lines to
for i in array:
total = total + i
And voila you got what you wanted,
Output:
Calculating Price
Enter a price: 10
The total cost is 10.0
Calculating Price
Enter a price: 20
The total cost is 30.0
Calculating Price
Enter a price: 15
The total cost is 45.0
Calculating Price
Enter a price:
Goodbye
UPDATE:
As mentioned in comments you need to learn more about indentation. Check out the link in the comments.
You have some problems, I will comment one by one:
First, you had some indentation problems, be careful with that.
The rest are comments in the code
update
def receipt(array):
sum = 0.0
for i in range(len(array)):
sum = sum + array[i]
return sum
array = []
while True:
print("Calculating Price")
n = input("Enter a price: ") #If you convert the str into float here it will cause an error in the if
if n == "": #here, when you hit enter, it sends the "" (empty string)
print("Goodbye")
break
array.append(float(n)) #So an option is transform the string here
totalCost = receipt(array) #and here, you gave to receipt() function the wrong param, you gave "n" and it was waiting for an array
print("The total cost is " + str(totalCost))
You shouldn't use sum as a variable, since it's a built-in in Python, besides, convert your array[i] to a float type when adding it to another float, also notice you never use your initialized array, you are missing that when calculating totalCost:
def receipt(array):
summ = 0.0
for i in range(len(array)):
summ = summ + float(array[i])
return summ
array = []
while True:
print("Calculating Price")
n = input("Enter a price: ")
if n == "":
print("Goodbye")
break
array.append(n)
totalCost = receipt(array)
print("The total cost is " + str(totalCost))
I have corrected what is causing your issue, you are in fact passing in 'n' into receipt instead of 'array'.
def receipt(array):
sum = 0.0
for i in range(len(array)):
sum = sum + array[i]
return sum
array = []
while True:
print('Calculating Price')
n = input("Enter a price: ")
if n == "":
print("Goodbye")
break
array.append(n)
totalCost = receipt(array) #receipt takes a list as a parameter (what you call array)
print("The total cost is " + str(totalCost))
Additional issues are:
indentation (I suspect that was just copy paste)
input will also give you errors the way you are using it, take a look at this to solve that issue
Consider also making your loop based on the value of n as while true is generally unsafe
or at least changing your if statement to be 'not n' as point out here is more pythonic. Also in the future make sure to note the version of python you are using.
Dont use sum as a variable name, it is a Python built-in.
Fixed:
def receipt(array):
total = 0.00 # avoiding 'sum'
for price in array:
total += float(price) # equivalent to 'total = total + float(price)'
return total
array = []
print ("Calculating Price...") # outside 'while' to not reprint each time!
while True:
price = input("Enter a price: ")
if not price: # equivalent to 'if price is False, or 0 in CompSci speak
print ("Goodbye!")
break
array.append(price)
total = receipt(array)
print("The current total cost is", total) # no need to convert to str()
Some words of advice:
When writing a function, its better to be explicit rather than
implicit. So use variables that make sense!
We can use the same variable names because Python uses the LEBG
rule
for variable scope.
When calculating a price (which we know usually ends in 2 decimals)
its better to use integers rather than floats as you will run into
the [problem](
Limiting floats to two decimal points)
with floating point numbers.
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)
I've just started with Python (3.x), and while it is fairly easy to pick up, I'm trying to learn how to work with lists.
I've written a small program which asks for the amount of numbers to input, then asks for the numbers. Where I'm scratching my head a little is here;
t += numList[int(i)]
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
I'm sure it's obvious to someone else. I thought that lists used an integer index? And that referencing that index would return the contents?
(I have a C++ background, so I'm finding that some things don't work how I thought they would).
Full program here;
runLoop = True
numList = []
def avg():
t = 0
i = 0
while i < len(numList):
t += numList[i]
i += 1
print (" total is " + str(t))
while runLoop == True:
maxLen = int(input("Average Calculator : "
"Enter the amount of number "
"to calculate for"))
while len(numList) < maxLen:
numList.append(input("Enter number : "))
avg()
if input("Would you like to run again? (y/n) ") == "n":
quit()
Type casting:
Type casting is missing in following statement
numList.append(input("Enter number : "))
e.g. Use input() method for python 3.x
>>> a = raw_input("Enter number:")
Enter number:2
>>> type(a)
<type 'str'>
>>> b = int(a)
>>> type(b)
<type 'int'>
>>>
Add Integer type variable with Integer type variable: This will raise exception at t += numList[i] statement because we are adding integer variable with string variable, it is not allowed.
e.g.
>>> 1 + "1"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>
No need to check length of list in while loop while i < len(numList):. We can iterate directly on list.
e.g.
>> numList = [1,4,10]
>>> total = 0
>>> for i in numList:
... total += i
...
>>> print total
15
>>>
Inbuilt sum() function: We can use inbuilt function sum() to get from list.
e.g.
>>> numList = [1,4,10]
>>> sum(numList)
15
>>>
Exception handling: It is good programming to handle exception on user input. Use exception handling during type casting. If user enters any non integer number and we are type casting that non integer string into integer that time python interpreter raise ValueError.
e.g.
>>> try:
... a = int(raw_input("Enter Number:"))
... except ValueError:
... print "Wrong number. Enters only digit."
...
Enter Number:e
Wrong number. Enters only digit.
Thanks to Vivik for the answer.
I have now adjusted my simple program and solved the issue I had; code as follows.
runLoop = True
numList = []
def avg(workList):
t = sum(workList)
print ("Average is " + str(t/len(workList)) )
print ("Total is " + str(t) )
while runLoop == True:
maxLen = int(input("Average Calculator : "
"Enter the amount of number "
"to calculate for : "))
while len(numList) < maxLen:
numList.append(int(input("Enter number : ")))
avg(numList)
if input("Would you like to run again? (y/n) ") == "n":
quit()
I can see that I could quite easily shorten it down to;
runLoop = True
numList = []
while runLoop == True:
maxLen = int(input("Average Calculator: Enter the amount of number to calculate for : "))
while len(numList) < maxLen:
numList.append(int(input("Enter number : ")))
print ("Average is " + str(sum(numList)/len(numList)) )
print ("Total is " + str(sum(numList)) )
if input("Would you like to run again? (y/n) ") == "n":
quit()
But, the point of my little !/pointless exercise was to explore the relationships of lists, input to lists, and printing lists.
Cheers!
I am very newbie to programming and stack overflow. I choose python as my first language. Today as I was writing some code to refresh and to improve my skills I wrote a little program. But with complete errors.
Here is the Program
a = [1 , 2, 3]
def list_append():
numbers = int(raw_input("Enter the number please"))
a.append(numbers)
print a
def average(list):
for marks in list:
print marks
total = float(sum(list))
total = total / len(list)
print ("Your total average is : %d" %total )
def loop():
add_numbers = raw_input("Do you want to add another number")
if add_numbers == ("y"):
return list_append()
else:
return average()
while True:
loop()
print average(a)
Basically the function of this program is to ask user for the input of the number. Then append to the list and then show the average which is an easy one.
But I want the program to stop after the first input and ask user if they want to give another input ?
Can't understand where is the problem. ** I am not asking for the direct solution. I would rather want an explanation than the solution itself.**
Following is missing in your code:
Need to break any loop, your while loop in going into infinite loop.
while True:
loop()
2. Handle exception during type casting.
numbers = int(raw_input("Enter the number please"))
Create user enter number list in loop function and pass to list_append function to add numbers.
Also return from the loop function to pass argument into average function.
code:
def list_append(numbers):
while 1:
try:
no = int(raw_input("Enter the number please:"))
numbers.append(no)
break
except ValueError:
print "Enter only number."
return list(numbers)
def average(number_list):
avg = float(sum(number_list))/ len(number_list)
return avg
def loop():
numbers = []
while 1:
add_numbers = raw_input("you want to add number in list(Y):")
if add_numbers.lower()== ("y"):
numbers = list_append(numbers)
else:
return list(numbers)
numbers = loop()
avg = average(numbers)
print "User enter numbers:", numbers
print "average value of all enter numbers:", avg
output:
vivek#vivek:~/Desktop/stackoverflow$ python 17.py
you want to add number in list(Y):y
Enter the number please:10
you want to add number in list(Y):y
Enter the number please:e
Enter only number.
Enter the number please:20
you want to add number in list(Y):Y
Enter the number please:30
you want to add number in list(Y):n
User enter numbers: [10, 20, 30]
average value of all enters numbers: 20.0
vivek#vivek:~/Desktop/stackoverflow$
do not use variable names which are already define by python
e.g. list
>>> list
<type 'list'>
>>> list([1,2,3])
[1, 2, 3]
>>> list = [2]
>>> list([1,2,3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
>>>
a = []
def average(list):
total = float(sum(list))
total = total / len(list)
print ("Your total average is : %d" %total )
while True:
numbers = raw_input("Enter the number please or 'q' to quit : ")
if numbers == "q":
average(a)
break
else:
a.append(int(numbers))
Hope this helps