This question already has answers here:
What does "Type Error: Can't convert 'int' to str implicitly" mean?
(2 answers)
Closed 6 years ago.
I am having a problem with a program I am currently working on. It is a GTIN-8 Code generator. When I try to start the program, I get the error:
Type Error: Can't convert 'int' to str implicitly.
My code is as follows:
sevenNum = ""
gtinNum = ""
checkDigit = ""
total = ""
a = ""
b = ""
c = ""
d = ""
e = ""
f = ""
g = ""
def GTINCalc():
a = int(sevenNum[0])*3
b = int(sevenNum[1])*1
c = int(sevenNum[0])*3
d = int(sevenNum[1])*1
e = int(sevenNum[0])*3
f = int(sevenNum[1])*1
g = int(sevenNum[0])*3
total = (a+b+c+d+e+f+g)
checkDigit = (total + 9) // 10 * 10 - total
print("GTIN-8 Code:" + a+b+c+d+e+f+g+checkDigit)
def sevenNumAsk():
sevenNum = input("Enter a 7 digit number to be converted into a GTIN-8 Number")
if sevenNum.isdigit() == True and len(sevenNum) == 7:
print("Valid Number - Calculating GTIN-8...")
GTINCalc()
else:
print("The number is not valid - please re-enter ")
sevenNumAsk()
sevenNumAsk()
I am having problems with this part:
total = (a+b+c+d+e+f+g)
checkDigit = (total + 9) // 10 * 10 - total
Many thanks.
You cannot concatenate string and ints together:
print("GTIN-8 Code:" + a+b+c+d+e+f+g+checkDigit)
It is more correct to use string formatting anyway, for example:
print("GTIN-8 Code: {0}{1}{2}{3}{4}{5}{6}{7}".format(a, b, c, d, e, f, g, checkDigit))
a, b....g are defined as string:
a = ""
b = ""
c = ""
d = ""
e = ""
f = ""
g = ""
and, when you sum them up total = (a+b+c+d+e+f+g), total is a string as well.
I would think your indentation is off in the code. If it is just a copy/paste error while posting the question only, then You can refer to #Selcuk's answer.
Related
I'm practicing my python and trying to format the print statement of the below code for match_string so it will print in this format:
There are 5 numbers, 4 letters and 2 other characters.
I've tried to do:
print("There are:", + x.nums, + "numbers", +x.letters,+"letter", + x.other, +"other characters")
and I get the error:
AttributeError: 'tuple' object has no attribute 'nums'
I also think I have an issue with the getDupes part as well but i can't figure out what, it just prints the same as.
Here's my code:
def match_string(words):
nums = 0
letter = 0
other = 0
for i in words :
if i.isalpha():
letter+=1
elif i.isdigit():
nums+=1
else:
other+=1
return nums,letter,other
def getDupes(x):
d = {}
for i in x:
if i in d:
if d[i]:
yield i
d[i] = False
else:
d[i] = True
x = match_string(input("enter a sentence"))
c = getDupes(x)
print(x)
#print("There are:", + str(x.nums), + "numbers", +x.letters,+"letter", + x.other, +"other characters")
print("PRINT",x)
funtion match_string returns a tuple hence cannot be accessed by using x.nums
instead try the below code
nums,letter,other = match_string(input("enter a sentence"))
print("There are:", + nums, + "numbers", + letters,+"letter", + other, +"other characters")
I started learning my first real language and can't find a solution for my problem:
how can I convert the user input, if someone is typing minus 10 for example instead of -10?
I just want to convert minus to -
I also added my code.
def get_temperatur():
minus = "-"
plus = "+"
while True:
C = input("Input temperature in Celsius: ")
try:
C = float(C)
return C
except ValueError:
print("That is not a valid input")
def convert_to_Kelvin(C):
K = C +273.15
return K
if __name__ == "__main__":
C = get_temperatur()
print("That is " + str(convert_to_Kelvin(C)) + " Kelvin")
def convert_to_Fahrenheit(C):
L = C * 1.8
F = L +32
return F
if __name__ == "__main__":
F = get_temperatur()
print("That is " + str(convert_to_Fahrenheit(F)) + " Fahrenheit")
I expect user input minus to be converted to -
Adding - sign will not make it a negative number, It is still going to be a string and you will get ValueError.
Instead do something like,
if 'minus' in c:
c = 0 - float(c.split('minus')[1].strip())
Note: I am assuming that your string will not contains any other word after number.
i.e. It will be like 'minus 10' and not 'minus 10 xyz'.
def get_temperatur():
minus = "-"
plus = "+"
while True:
C = input("Input temperature in Celsius: ")
try:
if 'minus ' in C:
C = C.replace('minus ', '-')
C = float(C)
return C
except ValueError:
print("That is not a valid input")
The C.replace() function takes in 2 values - the string to be replaced, and what it is to be replaced with. The if statement checks if 'minus '(note the space) is in the string, and if it is, replaces it with '-'
def get_temperatur():
while True:
C = input("Input temperature in Celsius: ")
C.replace("minus ", "-")
try:
C = float(C)
return C
except ValueError:
print("That is not a valid input")
I'm working on a cryptopals problem. Specifically, the first one. I have a, what I feel, decent solution for it, in that it works for given inputs, and for the example they give, but I've been looking at further testing to see if it holds up, and it doesn't seem to. Here's my code:
hex="0123456789abcdef"
base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
def hexNumeralToBinary(hexNumeral):
index = hex.index(hexNumeral)
binaryNumber = []
while index > 0:
if (index % 2) == 0:
binaryNumber = ["0"] + binaryNumber
index = index / 2
else:
binaryNumber = ["1"] + binaryNumber
index = (index-1)/2
while len(binaryNumber) < 4:
binaryNumber = ["0"] + binaryNumber
return ''.join(binaryNumber)
def hexToBinary(hexNumber):
length = len(hexNumber) + 1
binaryNumber = []
for i in range(1, length):
hexNumeral = hexNumber[-1*i]
binaryNumeral = hexNumeralToBinary(hexNumeral)
binaryNumber = [binaryNumeral] + binaryNumber
return ''.join(binaryNumber)
def splitString(binaryNumber):
while (len(binaryNumber) % 6) != 0:
binaryNumber = "0" + binaryNumber
binaryNumberSplit = []
while binaryNumber != "":
binaryNumberSplit.append(binaryNumber[0:6])
binaryNumber = binaryNumber[6:]
return binaryNumberSplit
def hexToBase64(hexNumber):
base64Number = []
binaryNumber = hexToBinary(hexNumber)
binaryNumberSplit = splitString(binaryNumber)
for sixBitNum in binaryNumberSplit:
#Convert 6 bit binary number into the base64 index
index = 0
for i in range(1, 7):
index += int(sixBitNum[-1*i]) * (2**(i-1))
base64Digit = base64[index]
base64Number = base64Number + [base64Digit]
return ''.join(base64Number)
hexNumber = input("Please enter a hexadecimal number to convert to base64: ")
print(hexToBase64(hexNumber))
It seems like the hexadecimal number needs to have a number of digits divisible by 3, or it just gets stuck while running. I don't know where, and I'm really stumped. I'm a total beginner to programming, and this is easily the most complex thing I've done, just trying to work it out as I go, and this isn't coming to me.
I want to make a program that returns a group of True variables that i found in my program. Like this:
1 = True
2 = True
3 = False
4 = False
5 = True
What I want is to return as a print
The true numbers are: 1, 2 and 5
Edit 1:
The code is a letter counter!
eacha letter in a group has a value.
Like
a=1
b = 2
...
If a number repeats more than 4 times, that number is a true
The group would be a name. like John in an imput.
The program reads it and gives a number for each letter.
what I am using right now is this (Preatty ugly I know, but I started programing this month...), where "a" is the amount of letter a in the name, b is the amount of b in the name....
if (a + j + s) >=4:
exe1 = 1
else:
exe1 = ""
if (b + k + t) >=4:
exe2 = 2
else:
exe2 = ""
if (c + l + u) >=4:
exe3 = 3
else:
exe3 = ""
if (d + m + v) >=4:
exe4 = 4
else:
exe4 = ""
if (e + n + w) >=4:
exe5 = 5
else:
exe5 = ""
if (f + o + x) >=4:
exe6 = 6
else:
exe6 = ""
if (g + p + y) >=4:
exe7 = 7
else:
exe7 = ""
if (h + q + z) >=4:
exe8 = 8
else:
exe8 = ""
if (i + r) >=4:
exe9 = 9
else:
exe9 = ""
print("Excesses:", exe1, exe2, exe3, exe4, exe5, exe6, exe7, exe8, exe9)
Why don't you use a dictionary? Take a look in this code as an example.
dict1 = {1:'True', 2:'True', 3:'False', 4:'False', 5:'True'}
list = []
for k, v in dict1.items():
if v == 'True':
#print(k, sep=' ', end=',')
list.append(k)
print(list)
Now you the list - although inside brackets and I don't know how to remove them since they are part of the list... Maybe iteration over it again should solve the problem, although I am not a truly expert in Python.
Hello I'm asking about the conversion issue with strings and integers.
I have a piece code that requires the conversion between strings and integers but I just can't get it to work, I wonder if anyone could help me. I receive String index out of range error.
Here is the code
def ISBN(bc):
total = 0
up = 0
down = 11
for x in range(10):
sbc = str(bc)
ibc = int(sbc[up])
total += (ibc * down)
#total += (int(sbc[up])*down)
up += 1
down -+ 1
mod = (total % 12)
if mod == 10:
total = "x"
print ("The ISBN book code is: " + bc + total)
w = 0
while w == 0:
a = int(input("Please input the 10 digit book number:\n"))
b = str(a)
if len(b) == 9:
ISBN(a)
else:
print ("Sorry book code not 10 digits long")
restart = input("Would you like to use the book code changer again?\n")
restart = restart.lower
if restart == "yes" or restart == "y":
print ("--------------------------------------------------\n")
elif restart == "no" or restart == "n":
print ("Thank you for using the ISBN book code changer\n")
w = 1
if len(b) == 9:
This should be 10.
mod = (total % 12)
This should be 11.