Puzzled about why I can't add strings together - python

I am trying to write a program that gets user information and adds it to a list and then I want to total how many user inputs there were, but I can't do it. I have tried running an accumulator, but I get TypeError: unsupported operand type(s) for +: 'int' and 'str'.
def main():
#total = 0
cel_list = []
another_celeb = 'y'
while another_celeb == 'y' or another_celeb == 'Y':
celeb = input('Enter a favorite celebrity: ')
cel_list.append(celeb)
print('Would you like to add another celebrity?')
another_celeb = input('y = yes, done = no: ')
print()
print('These are the celebrities you added to the list:')
for celeb in cel_list:
print(celeb)
#total = total + celeb
#print('The number of celebrities you have added is:', total)
main()
Here is the output as desired without the accumulator, but I still need to add the input together. I have commented out the accumulator.
Enter a favorite celebrity: Brad Pitt
Would you like to add another celebrity?
y = yes, done = no: y
Enter a favorite celebrity: Jennifer Anniston
Would you like to add another celebrity?
y = yes, done = no: done
These are the celebrities you added to the list:
Brad Pitt
Jennifer Anniston
>>>
Thanks in advance for any suggestions.

Total is an integer ( declared earlier on as )
total = 0
As the error code suggest, you are trying to join an integer with a string. That is not allowed. To get pass this error, you may :
## convert total from int to str
output = str(total) + celeb
print(" the number of celebrities you have added is', output)
or even better you can try using string formatting
##output = str(total) + celeb
## using string formatting instead
print(" the number of celebrities you have added is %s %s', % (total, celeb))
I hope this will work for you

Python is a dynamically typed language. So, when you type total = 0, the variable total becomes an integer i.e Python assigns a type to a variable depending on the value it contains.
You can check the type of any variable in python using type(variable_name).
len(object) returns integer value.
for celeb in cel_list:
print(celeb)
#end of for loop
total = 0
total = total + len(cel_list) # int + int
print('The number of celebrities you have added is:', total)

You can get the number of entries in a Python list by using the len() function. So, just use the following:
print('These are the celebrities you added to the list:')
for celeb in cel_list:
print(celeb)
total = len(cel_list)
print('The number of celebrities you have added is: ' + str(total))
Note the decreased indentation of the last two lines - you only need to run them once, after you've finished printing out the celeb's names.

Related

A way to get python to receive input and sum it? [duplicate]

This question already has answers here:
Loop that adds user inputted numbers and breaks when user types "end"
(4 answers)
How to sum numbers from input?
(2 answers)
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
sorry for the stupid question, but I can't get out of this thing in any way, I'm a beginner.
I need to write a code that asks the user to write a series of int one at the time using a while function. When the user has inserted all the numbers, to stop the series he'll write a specific string. When it's done, I need the code to print the sum and the average of all the numbers inserted.
The user can't insert them all in one time, he needs to enter one at the time.
I tried something like this: but there's no way it'll work. Implementing items in a list and then operate on the list is possible, but I had no idea on how to do that more easily than summing every element each time.
(my initial code:)
count = 0
total = 0
while():
new_number = input('> ')
if new_number == 'Done' :
break
count = count + 1
total = total + number
print(total)
print(total / count)
Don't mind about data being a string or an int, as long as it's just an error that IDLE would tell me. I just would like to know what's logically wrong in my code.
Thank you in advance.
You were really close, I made a couple of changes - firstly I changed while(): to while True:, so that the loop runs until break is hit. Secondly I altered total = total + number to total = total + int(new_number) - corrected variable name and convert string returned by input() to an int. Your logic is fine.
Corrected Code:
count = 0
total = 0
while True:
new_number = input('> ')
if new_number == 'Done' :
break
count = count + 1
total = total + int(new_number)
print(total)
print(total / count)
Using a list is actually not that hard. Here's how:
Firstly make the corrections from CDJB's answer.
Create an empty list. Add each new_number to the list. Use sum() and len() to get the total and count.
nums = []
while True:
new_number = input('> ')
if new_number == 'Done':
break
nums.append(int(new_number))
total = sum(nums)
count = len(nums)
print(total)
print(total / count

Creating a list with inputs prompted by the user?

I'm a beginner and taking an intro Python course. The first part of my lab assignment asks me to create a list with numbers entered by the user. I'm a little confused. I read some other posts here that suggest using "a = [int(x) for x in input().split()]" but I'm not sure how to use it or why, for that matter. The code I wrote before based on the things I've read in my textbook is the following:
while True:
num = int(input('Input a score (-99 terminates): '))
if num == -99:
break
Here's the problem from the professor:
Your first task here is to input score values to a list called scores and you
will do this with a while loop. That is, prompt user to enter value for scores
(integers) and keep on doing this until user enters the value of -99.
Each time you enter a value you will add the score entered to list scores. The
terminating value of -99 is not added to the list
Hence the list scores should be initialized as an empty list first using the
statement:
scores = []
Once you finish enter the values for the list, define and called a find called
print_scores() that will accept the list and then print each value in the list in
one line separate by space.
You should use a for-loop to print the values of the list.
So yeah, you want to continually loop a scan, asking for input, and check the input every time. If it's -99, then break. If its not, append it to the list. Then pass that to the print function
def print_list(l):
for num in l:
print(num, ' ', end='')
l = []
while True:
s = scan("enter some number (-99 to quit)")
if s == "-99":
break
l.append(int(s))
print_list(l)
the print(num, ' ', end='') is saying "print num, a space, and not a newline"
I think this will do the job:
def print_scores(scores):
for score in scores:
print(str(score), end = " ")
print("\n")
scores = []
while True:
num = int(input('Input a score (-99 terminates)'))
if num == -99:
break
scores.append(num)
print_scores(scores)
scores = [] creates an empty array and scores.append() adds the element to the list.
print() will take end = ' ' so that it separates each result with a space instead of a newline (\n') all while conforming to the requirement to use a loop for in the assignment. str(score) ensures the integer is seen as a string, but it's superfluous here.
This is actually not an elegant way to print the scores, but the teacher probably wanted to not rush things.

Debugging a simple Python price code

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.

Rounding a float that is an str and used in int

I'm trying to replicated a program I made on a Scratch-like application. My problem here is I'm trying to display the user with different numerical data (subtotal, tax and total cost), but when it shows the total cost it gives repeating or terminating decimals. I'd like it to be rounded to two decimals. I've tried adding the round() command inside the program but it's difficult because I'm trying to round a variable rather than an actual number. This is my code so far (line 25 and 28 I believe is where I'm suppose to add a round() or on a new line). I'm very new to Python, I'm using version 3.5.0. I also have searched on here, but the answers were too complex for me. In addition, I got this error: typeerror type str doesn't define __round__ method when adding the round() function in places I assume won't work. Thanks. (ignore after the last else: statement)
#This program asks for the size of pizza and how many toppings the customer would like and calculates the subtotal, tax and total cost of the pizza.
largePizza = 'large'
extraLargePizza = 'extra large'
print ('Answer the follwing question in all lowercase letters.')
print ('Would you like a large or an extra large pizza?')
sizeOfPizza = input()
if sizeOfPizza == largePizza:
print('Large pizza. Good choice!')
else:
print('Extra large pizza. Good choice!')
costOfLargePizza = str(6)
costOfExtraLargePizza = str(10)
oneTopping = 'one'
twoToppings = 'two'
threeToppings = 'three'
fourToppings = 'four'
print ('Answer the following question using words. (one, two, three, four)')
print ('How many toppings would you like on your pizza?')
numberOfToppings = input()
tax = '13%'
if numberOfToppings == oneTopping:
print('One topping, okay.')
if sizeOfPizza == largePizza:
subtotalCostOfLargePizza = str(int(costOfLargePizza) + 1)
**totalCostOfLargePizza = str(int(subtotalCostOfLargePizza) * 1.13)**
print('Your subtotal cost is ' + str(subtotalCostOfLargePizza))
print('Your tax is ' + str(tax))
**print('Your total cost is ' + str(totalCostOfLargePizza))**
else:
print('One topping, okay.')
subtotalCostOfExtraLargePizza = str(int(costOfExtraLargePizza) + 1)
totalCostOfExtraLargePizza = str(int(subtotalCostOfExtraLargePizza) * 1.13)
print('Your subtotal cost is ' + str(subtotalCostOfExtraLargePizza))
print('Your tax is ' + str(tax))
print('Your total cost is ' + str(totalCostOfExtraLargePizza))

Why does this loop have only one iteration instead of the number of iterations entered by the user? [duplicate]

This question already has answers here:
Python: raw_input and unsupported operand type(s)
(3 answers)
Closed 7 years ago.
I am trying to ask the user to enter any number and then ask the user to enter any names, then store this input in a list.
However, when I enter any number, it asks to enter name only one time and shows the output in list:
def main():
# a = 4
a = input("Enter number of players: ")
tmplist = []
i = 1
for i in a:
pl = input("Enter name: " )
tmplist.append(pl)
print(tmplist)
if __name__== "__main__":
main()
output:
Enter number of players: 5
Enter name: Tess
['Tess']
The for loop should run 5 times and user entered 5 values get stored in a list.
You need to convert the number of players to integer and then loop for that much amount of times, you can use the range() function for this . Example -
def main():
num=int(input("Enter number of players: "))
tmplist=[]
for _ in range(num):
pl=input("Enter name: " )
tmplist.append(pl)
print(tmplist)
Since you are using Python3
a=input("Enter number of players: ")
means a is a string "5". Since this is only one character long - the loop will run just once
You need to use
a = int(input("Enter number of players: "))
You'll also need to change the loop
for i in range(a):
I recommend using more meaningful variable names - especially if this is homework
def main():
number_of_players = int(input("Enter number of players: "))
player_list = []
for i in range(number_of_players):
player = input("Enter name: " )
player_list.append(player)
print(player_listlist)
if __name__== "__main__":
main()
You got a string a which presumably contained something like '5'. Then you initialize a counter i. Then you loop through this string, which, since it's '5', resulted in one iteration, because there's only one character in '5'.
First you have to change it into a number, with a = int(a).
With a as a number, you still can't loop through that, because a number isn't an iterable.
So then you should create a range object to loop over, with for i in range(a):.
Then you will be able to carry out your operations as expected.
Since the input a is a string
you need to convert it to a number and then use a different for.
it should be
def main():
#a=4
a=int(input("Enter number of players: "))
tmplist=[]
i=0
while i < a:
pl=input("Enter name: ")
tmplist.append(pl)
i+=1
print(tmplist)
main()

Categories

Resources