I am having trouble figuring out how to multiply my users input.
I have tried changing the functions of the variables for 'int' to 'float' and to 'str' but i cant seem to figure it out. My code:
pops = input("Enter your favorite pop: ")
cost = input("Enter how much they cost: ")
how_many = input("Enter how many pops you have: ")
print('My favorite pop is ' + pops + '!')
print('They cost about ' + cost + ' dollars.')
print('I have about ' + how_many + ' pops!')
result = str(cost) * str(how_many)
print("You have spent over " + result + " dollars on pops!")
I've got next error:
result = str(cost) * str(how_many)
TypeError: can't multiply sequence by non-int of type 'str'
First of all, I highly recommend you to start with some guides/tutorials or at least read official python docs to get in touch with language basics.
Regarding your problem. I'll show you basic algorithm how to use official docs to find solution.
Let's check docs of input() function.
The function then reads a line from input, converts it to a string, and returns that.
Strings in python are represented as str. So, after execution of input() variables pops, cost and how_many contains str values.
In your code you're using str() function. Let's check in docs what does this function perform:
Return a str version of object.
Now you understand that expressions str(cost) and str(how_many) convert str to str which means .. do nothing.
How to multiply values from input?
You need to multiply two values, which requires converting str to one of numeric types.
For cost we will use float, cause it can contain fractional number. For how_many we can use int cause count normally is integer. To convert str to numbers we will use float() and int() functions.
In your code you need just edit line where error occurred and replace useless call of str() with proper functions:
result = float(cost) * int(how_many)
Result of multiplication float and int will be float.
How to print result?
Code you're using will throw an error, cause you can't sum str and float. There're several ways how to print desired message:
Convert result to str.
It's the most obvious way - just use str() function:
print("You have spent over " + str(result) + " dollars on pops!")
Use features of print() function:
In docs written:
print( *objects, sep=' ', end='\n', file=sys.stdout, flush=False )
Print objects to the text stream file, separated by sep and followed by end.
As we see, default separator between objects is space, so we can just list start of string, result and ending in arguments of print() function:
print("You have spent over", result, "dollars on pops!")
String formatting.
It's very complex topic, you can read more information by following provided link, I'll just show you one of methods using str.format() function:
print("You have spent over {} dollars on pops!".format(result))
You are trying to multiply two strings.
You should multiply like this:
result = float(cost) * int(how_many)
But don't forget to reconvert the result to string in the last line or it will give you another error (TypeError in this case)
print("You have spent over " + str(result) + " dollars on pops!")
str(item) converts item to a string. Similarly, float(item) converts item to a float (if possible).
The code:
result = float(cost) * int(how_many)
will not produce the same error as you indicated occurred, but may introduce a ValueError, if the input given is not what you are expecting.
Example:
a = "b"
float(a)
Output
ValueError: could not convert string to float: 'b'
result = int(cost) * int(how_many) can fix the issue. Cost and how_many are non-numeric and converting them to int gives the desired output.
pops = input("Enter your favorite pop: ")
cost = input("Enter how much they cost: ")
how_many = input("Enter how many pops you have: ")
print('My favorite pop is ' + pops + '!')
print('They cost about ' + cost + ' dollars.')
print('I have about ' + how_many + ' pops!')
result = float(cost) * int(how_many)
print("You have spent over " + str(result) + " dollars on pops!")
The problem is that you are trying to convert the cost to a string, conversion from one type to another except when using the bool() is illegal. That is why the program is raising a TypeError.
pops = input("Enter your favorite pop: ")
cost = input("Enter how much they cost: ")
how_many = input("Enter how many pops you have: ")
print('My favorite pop is ' + pops + '!')
print('They cost about ' + cost + ' dollars.')
print('I have about ' + how_many + ' pops!')
result = cost * how_many
print("You have spent over " + result + " dollars on pops!"
Related
Hello everyone I am very new to Python I am taking a beginner course at my college, and I am stuck on one portion of my project. Basically the goal of my code is to produce the output so that when I enter any age and name the result is supposed to find the sum of the age and number of letters in the entered name. So far this what I have typed up.
print('What is your name?')
myName = input()
print('What is your age?')
myAge = input()
sum = myAge + str(len(myName))
print(myName + ', if we add the number of letters in your name to your age then you will be ' + sum + ' in ' + str(len(myName)) + ' years.')
When I run the script all I get is the age+length of name which gives me a combination and not a sum. example 21 + 4 = 214.
Basically my issue with this is that I don't understand how to find the sum of both inputs so that I get result of adding age and the length of letters in a name. The last portion that I am trying write should in other words be this "Name, if we add the number of letters in your name to your age then you will be # in # years."
If anyone can explain to me how I can accomplish this then I would greatly appreciate it I have spent hours looking into this issue but can't figure it out.
When you use input() it returns a string.
So when setting it to sum, you end up with "21" + "4" (which will result in a string) -> "214"
Try converting myAge to an int like so
sum = int(myAge) + len(myName)
This will make it where you add 21 + 4 (now both numbers), so you'll get 25
Result of "input()" always is a string. You need to convert your input to integer using:
myAge = int(input('What is your age?'))
During the sum of the two variables should be converted to integers or decimals
print('What is your name?')
myName = input()
print('What is your age?')
myAge = input()
sum = float(myAge) + float((len(myName)))
print(myName + ', if we add the number of letters in your name to your age then you will be ' + str(sum) + ' in ' + str(len(myName)) + ' years.')
I simply have to make a sum of three numbers and calculate the average
import sys
sums=0.0
k=3
for w in range(k):
sums = sums + input("Pleas input number " + str(w+1) + " ")
print("the media is " + str(sums/k) + " and the Sum is " + str(sums))
And the error :
Pleas input number 1 1
Traceback (most recent call last):
File "/home/user/Python/sec001.py", line 5, in <module>
sums = sums + input("Pleas input number " + str(w+1) + " ");
TypeError: unsupported operand type(s) for +: 'float' and 'str'
Why not do the simple version then optimize it?
def sum_list(l):
sum = 0
for x in l:
sum += x
return sum
l = list(map(int, input("Enter numbers separated by spaces: ").split()))
sum_list(l)
Your problem was that you were not casting your input from 'str' to 'int'. Remember, Python auto-initializes data types. Therefore, explicit casting is required. Correct me if I am wrong, but that's how I see it.
Hope I helped :)
The input() function returns a string(str) and Python does not convert it to float/integer automatically. All you need to do is to convert it.
import sys;
sums=0.0;
k=3;
for w in range(k):
sums = sums + float(input("Pleas input number " + str(w+1) + " "));
print("the media is " + str(sums/k) + " and the Sum is " + str(sums));
If you want to make it even better, you can use try/except to deal with invalid inputs. Also, import sys is not needed and you should avoid using semicolon.
sums=0.0
k=3
for w in range(k):
try:
sums = sums + float(input("Pleas input number " + str(w+1) + " "))
except ValueError:
print("Invalid Input")
print("the media is " + str(sums/k) + " and the Sum is " + str(sums))
input returns a string and you need to create an int or float from that. You also have to deal with the fact that users can't follow simple instructions. Finally, you need to get rid of those semicolons - they are dangerous and create a hostile work environment (at least when you bump into other python programmers...!)
import sys
sums=0.0
k=3
for w in range(k):
while True:
try:
sums += float(input("Pleas input number " + str(w+1) + " "))
break
except ValueError:
print("That was not a number")
print("the media is " + str(sums/k) + " and the Sum is " + str(sums))
The line
question = str(input("What is",randomNumber1,"+",randomNumber2,"x",randomNumber3,"?\n"))
in my code is giving me trouble.
This is the error I get:
question = str(input("What is",randomNumber1,"+",randomNumber2,"x",randomNumber3,"?\n"))
TypeError: input expected at most 1 arguments, got 7
If you could help it would be much appreciated as I don't know what I have done wrong.
You are using , in your parentheses for your strings. So Python thinks, these are parameters for your called function. You need to append your strings together (via + as already mentioned).
Furthermore, you should consider raw_input in Python2, because input is interpreted as Python code: look here
Like the output already says.
question = str(input("What is"+randomNumber1+"+"+randomNumber2+"x"+randomNumber3+"?\n"))
You are using , while calling the function input(). As a result, python interprets it to be 7 different arguments.
I guess, the following code will do what you require.
question = str(input("What is " + str(randomNumber1) + " + " + str(randomNumber2) + " x " + str(randomNumber3) + " ?\n"))
Do note, this will store the answer provided by the user as a string in the variable question.
If you require to accept the answer as an integer (number) use the following instead.
question = input("What is " + str(randomNumber1) + " + " + str(randomNumber2) + " x " + str(randomNumber3) + " ?\n")
Are you Python 3? If you are Python 2 then you should use raw_input() instead of input(). If you are using Python 3 then please try to use that tag (most will assume "Python" means Python 2).
input() and raw_input() both return strings (no need to force it), and they only take one argument, as the error message said. Also your comparison for the correct answer uses different types, you are comparing a string with an int.
Best to construct the question first as a string:
question = "What is %d + %d x %d? " % (randomNumber1,randomNumber2,randomNumber3)
users_answer = input(question)
answer = randomNumber1 + randomNumber2 * randomNumber3
# users_answer and answer are different types
if int(users_answer) == answer:
print("\n[ Correct ]\n")
playerScore = playerScore + 1
print("Your score is",playerScore)
questionNumber = questionNumber + 1
else:
print("\n[ Incorrect ]\n")
questionNumber = questionNumber + 1
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))
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.