My code is supposed to determine and display the number of binary trees after an input.
I keep getting the can't convert int object to str implicitly error and I have no idea how to fix it. It easily works in versions of Python under 3.0, so please help, as I'm still a beginner in Python and I would like to understand what I'm doing wrong.
import sys
print ("Welcome to Binary Tree Enumeration!")
x = input("Type an integer to output its binary trees: ")
print ("\nYou entered " + str(x))
def distinct(x):
leafnode = '.'
dp = []
newset = set()
newset.add(leafnode)
dp.append(newset)
for i in range(1,x):
newset = set()
for j in range(i):
for leftchild in dp[j]:
for rightchild in dp[i-j-1]:
newset.add(("(") + leftchild + rightchild + (")"))
dp.append(newset)
return dp[-1]
alltrees = distinct(x+1)
for tree in alltrees:
print (tree)
print ("Thank you for trying this out!")
I forgot to add...this is the error I'm getting.
Traceback (most recent call last):
File "main.py", line 29, in
alltrees = distinct(x+1)
TypeError: Can't convert 'int' object to str implicitly
As others have suggested, this comes from your call to input. In Python27:
>>> input() + 1
3 # I entered that
4
But using raw_input() (which has the same behaviour as input in Python3+):
>>> raw_input() + 1
3 # I entered that
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
And indeed, we have:
>>> x = raw_input()
3
>>> type(x)
<type 'str'>
In your code, your user-input x is a string, and the code complains on the line distinct(x+1) when you try to add a string and an int. Convert it first like this:
>>> x = int(input())
...
In order to concatenate strings and string representations of various types, you have to cast the latter to strings explicitly, e. g.
"(" + str(leftchild) + ", " + str(rightchild) + ")"
or, more readably,
"(%i, %i)" % (leftchild, rightchild)
By default when you use input its always a string input
x = input("Type an integer to output its binary trees: ")
print ("\nYou entered " + str(x))
So there's no need to convert it again !
and here use .format()
newset.add("{0} {1} {2} {3}".format(r"(", leftchild, rightchild, r")"))
But the above one will not maintain the datastructure !!
If you would like to preserve the datastructure, use,
newset.add(tuple(leftchild, rightchild))
Related
I am coding a simple program to add all positive integers not greater than a given integer n. My code:
print("Enter an integer:")
n=input()
def add(k):
sum=0
for i in range(k+1):
sum=sum+i
return sum
#print("1+2+3+...+"+str(n)+"="+str(add(n)))
print(add(100))
The function works.
Why does the line in the one line comment not work, if I remove the hash tag? It should - there is a concatenation of four strings. Thank you.
EDIT: the whole output:
Enter an integer:
12
Traceback (most recent call last):
File "<string>", line 10, in <module>
File "<string>", line 6, in add
TypeError: can only concatenate str (not "int") to str
>
input() returns a string. You are passing n=input() which is a string so it is not working as expected.
change it to n=int(input())
Also sum is a reserved keyword and it will be best to change that to a different name
input returns a string, so add(n) will look something like add("1234"). Then, range(k+1) inside the function will be range("1234" + 1), but "1234" + 1 is an error since it's not possible to add a string and a number.
The problem exists in your input, it's current data type is str, and must be converted into int.
Also, it's best if you use .format() when printing strings.
print("Enter an integer:")
n = int(input())
def add(k):
sum=0
for i in range(k+1):
sum=sum+i
return sum
print("1 + 2 + 3 + ... + {} = {}".format(n, add(n)))
This question already has answers here:
How can I concatenate str and int objects?
(1 answer)
How can I read inputs as numbers?
(10 answers)
String concatenate TypeError: can only concatenate str (not "int") to str"
(3 answers)
Closed 2 years ago.
I decided to make some kind of secret code for testing purposes with Unicode.
I've done that by adding numbers to Unicode so it would be kind of secret.
I've been getting this error, but I don't know how to solve it.
Is there any solution?
Original Code
message = input("Enter a message you want to be revealed: ")
secret_string = ""
for char in message:
secret_string += str(chr(char + 7429146))
print("Revealed", secret_string)
q = input("")
Original Error
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-182-49ece294a581> in <module>
2 secret_string = ""
3 for char in message:
----> 4 secret_string += str(chr(char + 7429146))
5 print("Revealed", secret_string)
6 q = input("")
TypeError: can only concatenate str (not "int") to str
Updated code
while True:
try:
message = int(input("Enter a message you want to be decrypt: "))
break
except ValueError:
print("Error, it must be an integer")
secret_string = ""
for char in message:
secret_string += chr(ord(char - str(742146)))
print("Decrypted", secret_string)
q = input("")
Python working a bit differently to JavaScript for example, the value you are concatenating needs to be same type, both int or str...
So for example the code below throw an error:
print( "Alireza" + 1980)
like this:
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
print( "Alireza" + 1980)
TypeError: can only concatenate str (not "int") to str
To solve the issue, just add str to your number or value like:
print( "Alireza" + str(1980))
And the result as:
Alireza1980
Use f-strings to resolve the TypeError
f-Strings: A New and Improved Way to Format Strings in Python
PEP 498 - Literal String Interpolation
# the following line causes a TypeError
# test = 'Here is a test that can be run' + 15 + 'times'
# same intent with a f-string
i = 15
test = f'Here is a test that can be run {i} times'
print(test)
# output
'Here is a test that can be run 15 times'
i = 15
# t = 'test' + i # will cause a TypeError
# should be
t = f'test{i}'
print(t)
# output
'test15'
The issue may be attempting to evaluate an expression where a variable is the string of a numeric.
Convert the string to an int.
This scenario is specific to this question
When iterating, it's important to be aware of the dtype
i = '15'
# t = 15 + i # will cause a TypeError
# convert the string to int
t = 15 + int(i)
print(t)
# output
30
Note
The preceding part of the answer addresses the TypeError shown in the question title, which is why people seem to be coming to this question.
However, this doesn't resolve the issue in relation to the example provided by the OP, which is addressed below.
Original Code Issues
TypeError is caused because message type is a str.
The code iterates each character and attempts to add char, a str type, to an int
That issue can be resolved by converting char to an int
As the code is presented, secret_string needs to be initialized with 0 instead of "".
The code also results in a ValueError: chr() arg not in range(0x110000) because 7429146 is out of range for chr().
Resolved by using a smaller number
The output is not a string, as was intended, which leads to the Updated Code in the question.
message = input("Enter a message you want to be revealed: ")
secret_string = 0
for char in message:
char = int(char)
value = char + 742146
secret_string += ord(chr(value))
print(f'\nRevealed: {secret_string}')
# Output
Enter a message you want to be revealed: 999
Revealed: 2226465
Updated Code Issues
message is now an int type, so for char in message: causes TypeError: 'int' object is not iterable
message is converted to int to make sure the input is an int.
Set the type with str()
Only convert value to Unicode with chr
Don't use ord
while True:
try:
message = str(int(input("Enter a message you want to be decrypt: ")))
break
except ValueError:
print("Error, it must be an integer")
secret_string = ""
for char in message:
value = int(char) + 10000
secret_string += chr(value)
print("Decrypted", secret_string)
# output
Enter a message you want to be decrypt: 999
Decrypted ✙✙✙
Enter a message you want to be decrypt: 100
Decrypted ✑✐✐
instead of using " + " operator
print( "Alireza" + 1980)
Use comma " , " operator
print( "Alireza" , 1980)
Use this:
print("Program for calculating sum")
numbers=[1, 2, 3, 4, 5, 6, 7, 8]
sum=0
for number in numbers:
sum += number
print("Total Sum is: %d" %sum )
Problem is you are doing the following
str(chr(char + 7429146))
where char is a string. You cannot add a int with a string. this will cause that error
maybe if you want to get the ascii code and add it with a constant number. if so , you can just do ord(char) and add it to a number. but again, chr can take values between 0 and 1114112
Change secret_string += str(chr(char + 7429146))
To secret_string += chr(ord(char) + 7429146)
ord() converts the character to its Unicode integer equivalent. chr() then converts this integer into its Unicode character equivalent.
Also, 7429146 is too big of a number, it should be less than 1114111
I have typed
x = input("enter name: ")
Print ("hey") + x
But when compiled am getting
Typeerror: unsupported operand type(s) for +: 'nonetype' and 'str'
I'm using python 3.6.0b1.
You are trying to add to the return value of print (which is None) to a string. Setting parentheses correctly is important.
x = input("enter name: ")
print("hey" + x)
print() is a function call which takes a string, so you need to pass the string inside the brackets to the function call like so;
x = input("enter name: ")
print ("hey " + x)
Further reading on print() is available here: https://docs.python.org/3/tutorial/inputoutput.html
I am creating a program in which compresses text, which includes normal letters and punctuation and etc. However I have come across a mixed operand Type error of some sort and I do not know how to fix this. I have tried reading other posts about the topic but I cannot understand how it works and how to apply this to my code.
print("The compression program has started")
myDict={}
revDict={}
sentList=[]
posList=[]
num = 0
sentence = open("pyCompress.txt","r").read().split()
for word in sentence:
if word not in myDict:
myDict[word] = num
num += 1
print(sentence)
print(myDict)
for k, v in myDict.items():
revDict[v] = k
file = open("Positions.txt","w")
for word in sentence:
file.write((myDict[word]) + " ")
file.close()
There is more code beyond these lines
The error I get is: TypeError: unsupported operand type(s) for +: 'int' and 'str'
Cast the myDict[word] to a str so you can perform the concatenation, as well as move the file.close outside the loop as mentioned by others. Thus, only changing the last loop like this should fix the errors you're getting:
for word in sentence:
file.write((str(myDict[word]) + " "))
file.close()
Python does not allow adding integers to strings:
>>> 1 + "a"
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
1 + "a"
TypeError: unsupported operand type(s) for +: 'int' and 'str'
To put the number into the string you can either explicitly convert it:
>>> str(1) + "a"
'1a'
Or format it in with either the % notation or {} notation:
>>> "the number %d is prime"%874193
'the number 874193 is prime'
>>> "please give me {n} apples".format(n=2)
'please give me 2 apples'
You could also use print to handle the conversion for you:
print(myDict[word], file = file, end=" ")
Next you need to make sure you close a file after writing all the data that needs to be written to it, in your case that would be after the for loop:
for word in sentence:
print(myDict[word], file = file, end=" ")
file.close() #un-indent
Although you may want to use a with statement to ensure the file is properly handled:
with open("Positions.txt","w") as file:
for word in sentence:
print(myDict[word], file = file, end=" ")
assert file.closed #the file is closed at the end of with block
try this, read my comments for the changes I've made
print("The compression program has started")
myDict={}
revDict={}
sentList=[]
posList=[]
num = 0
sentence = open("pyCompress.txt","r").read().split()
for word in sentence:
if word not in myDict:
# needs to convert to str
# also indentation problem here
myDict[word] = str(num)
num += 1
print(sentence)
print(myDict)
for k, v in myDict.items():
revDict[v] = k
file = open("Positions.txt","w")
for word in sentence:
file.write((myDict[word]) + " ")
# indentation problem here
file.close()
In case you want to write both keys and values into the file, try this,
file.write(word + ":" + myDict[word] + " ")
How do you print addition in python?
I tried to define addition and tell it to print:
subtraction = int(number - reverse(number))
print str(subtraction)
But it always says:
Traceback (most recent call last):
File "C:\Python25\Castor's Python Programs\proj02.py", line 16, in <module>
subtraction = int(number - reverse(number))
TypeError: unsupported operand type(s) for -: 'str' and 'str'
This is my full code:
import sys
def reverse(num):
return (num)[::-1]
print "This is a puzzle favored by einstein. You will be asked to enter a three digit number, where the hundred's digit differs from the ones digit by at least two. The procedure will always yield 1089."
number = raw_input("Give me a number:")
print "For the number: "
print number
print " the reverse number is: "
print reverse(number)
print "The difference between "
print number
print" and "
print reverse(number)
print " is "
subtraction = int(number - reverse(number))
print str(subtraction)
print "The reverse difference is: "
print str(reverse(subtraction))
print "The sum of: "
print subtraction
print " and revDiff is: "
finaladdition = int(subtraction - reverse(subtraction))
print str(finaladdition)
Can someone please help?
You are trying to subtract two strings, which can't be done. You want to convert those strings to numbers first before you perform the operations:
subtraction = int(number) - int(reverse(number))
You need to convert number to a int before you subtract it. number here is a string confusingly, because it was set by raw_input which returns a string.
subtraction = int(number) - int(reverse(number))
For print str(reverse(subtraction)) to work subtraction must be converted to a string, because it is an int set by subtracting. Thus:
print str(reverse(str(subtraction)))
But reverse will return a string so the str in front is unneeded.
print reverse(str(subtraction))
Also, finaladdition = int(subtraction - reverse(subtraction)) needs to become:
finaladdition = int(subtraction) - int(reverse(str(subtraction)))
We must convert subtraction to a string before passing it to reverse, because reverse uses it's argument as if it is a string. In the first part, subtraction is already a int so converting it to an int is unneeded.