This question already has answers here:
How to print list item + integer/string using logging in Python
(2 answers)
Closed 7 years ago.
I am coding in Python, and have reached an error that I cannot seem to solve. Here's the part of the code that it affects.
import random
a = raw_input("Enter text")
b = random.randrange(1,101)
print (a+b)
When I try to run the code, I get the error "TypeError: cannot concatenate 'str' and 'int' objects"
I want to know how to print the result of a+b.
To answer to the question in the title, you can convert an integer into a string with str. But the print function already applies str to its argument, in order to be able to print it.
Here, your problem comes from the fact that a is a string while b is an integer. The + operator works on two strings, or two ints, but not a combination of this two types. If you have two strings, the + will mean concatenate. If you have two ints, the + will mean add. It then depends on the result you want to get.
You can convert a string to an integer by using int.
Try this code:
import random
a = int (raw_input ("Enter int "))
b = random.randrange (1, 101)
print a + b
Related
This question already has an answer here:
How can I concatenate str and int objects?
(1 answer)
Closed 3 years ago.
I am unable to place an integer inside my print statement alongside a string, and concatenate them together.
pounds = input("Please type in your weight in pounds: ")
weight = int(pounds) * 0.45
print("You " + weight)
I thought that I would be able to put these together, why am I unable to?
Python doesn't let you concatenate a string with a float. You can solve this using various methods:
Cast the float to string first:
print("You " + str(weight))
Passing weight as a parameter to the print function (Python 3):
print("You", weight)
Using various Python formatting methods:
# Option 1
print("You %s" % weight)
# Option 2 (newer)
print("You {0}".format(weight))
# Option 3, format strings (newest, Python 3.6)
print(f"You {weight}")
Since you are trying to concat a string with an integer it's going to throw an error. You need to either cast the integer back into a string, or print it without concatenating the string
You can either
a) use commas in the print function instead of string concat
print("You",weight)
b) recast into string
print("You "+str(weight))
Edit:
Like some of the other answers pointed out, you can also
c) format it into the string.
print("You {}".format(weight))
Hope this helps! =)
print("You %s" % weight) or print("You " + str(weight))
Another way is to use format strings like print(f"You {weight}")
Python is dynamically typed but it is also strongly typed. This means you can concatenate two strs with the + or you can add two numeric values, but you cannot add a str and an int.
Try this if you'd like to print both values:
print("You", weight)
Rather than concatenating the two variables into a single string, it passes them to the print function as separate parameters.
This question already has answers here:
How can I concatenate str and int objects?
(1 answer)
String formatting: % vs. .format vs. f-string literal
(16 answers)
Closed 7 months ago.
I have to write a program that reads in a whole number and prints out that number divided by two. This is my code:
a= int(input("Number: "))
h= a/2
print("Half number: " + h)
But I keep getting this
Number: 6
Traceback (most recent call last):
File "program.py", line 3, in <module>
print("Half number: " + h)
TypeError: Can't convert 'float' object to str implicitly
I don't see anything wrong with my code and I have no idea what the error is. Any idea what's wrong?
The expression:
"Half number: " + h
is trying to add a string to a float. You can add strings to strings:
"This string" + ", then this string"
and floats to floats:
100.0 + 16.8
but Python isn't willing to let you add strings and floats. (In the error message above, Python has processed the first string and the addition, and it now expects a string -- that's why you get the error that it can't -- or at least won't -- convert a 'float' number to a string.)
You can tell Python this is what you really want it to do in a few ways. One is to use the built-in str() function which converts any object to some reasonable string representation, ready to be added to another string:
h = 100
"You can add a string to this: " + str(h)
a= int(input("Number: "))
h= a/2
print('Half number:', h)
Without the spaces in between though
Here is a very simple way to do it.
Here's a sample solution from Grok Learning:
n = int(input('Number: '))
print('Half number:', n/2)
Here's my explanation below:
As you might've already guessed, n here is a variable. And in this code, we will be assigning some information to n. int(input('Number ')) is the statement that Python will then read, and follow. int() tells Python that the input will be an integer, and input() allows the user to input whatever they would like to input. n/2 is simply another way of saying "n divided by two". print() tells Python to print a statement, and so print('Half number:', n/2) will print out that "Half number" is simply just half of the number entered above.
Here's an example of what the output should look like:
Number: 6
Half number: 3
(In that example, the input was 6.)
So, yes, I know that you may already know this stuff but I am leaving this information for people who may visit this website in the future. The error that you had was that you used a +, when you should've used a ,. Python is pretty strict when it comes to processing what you're saying, so it didn't allow you to put a str and an int together using a +. So next time, remember to use a ,.
I hope this helps you.
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 7 months ago.
My goal is very simple, which makes it all the more irritating that I'm repeatedly failing:
I wish to turn an input integer into a string made up of all numbers within the input range, so if the input is 3, the code would be:
print(*range(1, 3+1), sep="")
which obviously works, however when using an n = input() , no matter where I put the str(), I get the same error:
"Can't convert 'int' object to str implicitly"
I feel sorry to waste your collective time on such an annoyingly trivial task..
My code:
n= input()
print(*range(1, n+1), sep="")
I've also tried list comprehensions (my ultimate goal is to have this all on one line):
[print(*range(1,n+1),sep="") | n = input() ]
I know this is not proper syntax, how on earth am I supposed to word this properly?
This didn't help, ditto this, ditto this, I give up --> ask S.O.
I see no reason why you would use str here, you should use int; the value returned from input is of type str and you need to transform it.
A one-liner could look like this:
print(*range(1, int(input()) + 1), sep=' ')
Where input is wrapped in int to transform the str returned to an int and supply it as an argument to range.
As an addendum, your error here is caused by n + 1 in your range call where n is still an str; Python won't implicitly transform the value held by n to an int and perform the operation; it'll complain:
n = '1'
n + 1
TypeErrorTraceback (most recent call last)
<ipython-input-117-a5b1a168a772> in <module>()
----> 1 n + 1
TypeError: Can't convert 'int' object to str implicitly
That's why you need to be explicit and wrap it in int(). Additionally, take note that the one liner will fail with input that can't be transformed to an int, you need to wrap it in a try-except statement to handle that if needed.
In your code, you should just be able to do:
n = int(input())
print(*range(1,n+1),sep="")
But you would also want to have some error checking to ensure that a number is actually entered into the prompt.
A one-liner that works:
print(*range(1, int(input()) + 1), sep="")
This question already has answers here:
How can I convert a string with dot and comma into a float in Python
(9 answers)
Closed 6 years ago.
I have a list in python and I want to get the average of all items. I tried different functions and even I wrote a small function for that but could not do that. even when I tried to convert the items to a int or float it gave these errors:
TypeError: float() argument must be a string or a number
TypeError: int() argument must be a string or a number, not 'list'
here is a small example of my list in python.
['0,0459016', '0,0426647', '0,0324087', '0,0222222', '0,0263356']
do you guys know how to get the average of items in such list/
thanks
Assuming that '0,0459016' means '0.0459016':
In [6]: l = ['0,0459016', '0,0426647', '0,0324087', '0,0222222', '0,0263356']
In [7]: reduce(lambda x, y: x + y, map(lambda z: float(z.replace(',', '.')), l)) / len(l)
Out[7]: 0.033906559999999995
Please refer to How can I convert a string with dot and comma into a float number in Python
sum([float(v.replace(",", ".")) for v in a]) / len(a)
where a is your original list.
Try this,
In [1]: sum(map(float,[i.replace(',','.') for i in lst]))/len(lst)
Out[1]: 0.033906559999999995
Actulluy there is 2 problem in your list. The elements are string and instead of . it having ,. So we have to convert to normal form. like this.
In [11]: map(float,[i.replace(',','.') for i in lst])
Out[11]: [0.0459016, 0.0426647, 0.0324087, 0.0222222, 0.0263356]
Then perform the average.
This question already has answers here:
How to concatenate two integers in Python?
(17 answers)
Closed 8 years ago.
How would I append a number to the end of another number?
for example:
a = 1
b = 2
a = a + b
print(a)
Output = 3
I want to get my output as 12 but instead I get 3. I understand that when you do number + number you get the addition of that but I would like to do is append b to a and so I would get 12. I have tried appending a number to a number but I get an error. I think that you can only append a list.
My question is:
How do I append a number to a number?
or is there a better way of doing it?
The reason you get 3 is because a and b contain integers. What you want is string concatenation to get 12. In order to use string concatenation you need strings. You can type cast the integers to string using str() and then use int() to type cast the string to an integer.
a = 1
b = 2
a = str(a) + str(b)
a = int(a)
print(a)
The oneliner solution is already provided in the comments.