I am writing a temperature converter for fun and everything seems to be working except I am getting a 'TypeError: Can't convert 'float' object to str implicitly' message. From what I can tell I am converting it to a string after the fact, can anyone tell me what I am doing wrong?
I looked this this question previously "Can't convert 'float' object to str implicitly"
def tempconverter(startType,Temp):
#conversion types: c -> f c-> K , f -> c, f -> k, k -> c, k -> f
# maybe have them select only their beginning type then show
# all temp types by that temperature
if startType[0].lower() == 'c':
return ('Your temperature ' + Temp +'\n'
+ 'Farenheight: ' + ((int(Temp)*9)/5)+32 + '\n'
+ 'Kelvin: ' + str((Temp+ 273.15)) ## I get the error here ##
)
elif startType[0].lower() == 'f':
#commented out until first is fixed
#return ((int(Temp)-32)*5)/9
return Temp
elif startType[0].lower() == 'k':
return Temp
print('Welcome to our temperature converter program.')
print('''Please enter your temperature type:
C = Celsius
F = Farenheight
K = Kelvin''')
sType = input('> ')
print('Please enter the temperature you wish to convert.')
sTemp = input('> ')
print(tempconverter(sType,sTemp))
In the line of code:
+ 'Kelvin: ' + str((Temp+ 273.15)) ## I get the error here ##
The error is caused by this part of it:
Temp+ 273.15
Temp is a string. You can't add a string and a number together.
In this calculation:
((int(Temp)*9)/5)+32
You are not converting your result to str.
Also, you have spelled "Fahrenheit" incorrectly.
Related
temp = float(input("What is the temperature : "))
def C2F():
"Celsius to Fahrenheit"
f = (temp * 9/5) + 32
return (f)
def C2K():
"Celsius to Kelvin"
k = temp + 273.15
return (k)
def C2R():
"Celsius to Rankine"
r = (temp + 273.15) * 9 / 5
return (r)
print ("F = %.2f" % C2F())
print ("K = %.2f" % C2K())
print ("R = %.2f" % C2R())
How can i add multiple inputs to this code. I have to add input unit , output unit and user_response for correct,incorrect and invalid outputs
You could do it like this - but it is quite a rewrite.
You would need to add more conversion math for the missing cases (F to C, F to K etc.) to calculate the missing ones as well:
def convert(frm, to, value):
# you may want to make more smaller methods that do the calculation
# like def C2F(v): return (v * 9/5) + 32
# and call them inside your if statements
if frm == to:
print("Nothing to convert - same units.")
return value
if frm == "C" and to == "F":
print("Celsius to Fahrenheit")
return (value * 9/5) + 32
if frm == "C" and to == "K":
print("Celsius to Kelvin")
return value + 273.15
if frm == "C" and to == "R":
print("Celsius to Rankine")
return (value + 273.15) * 9 / 5
print(frm, to,"not supported.")
return "n/a"
def tryParseFloat(v):
"""Try parsing v as float, returns tuple of (bool, float).
If not a float, returns (False, None)"""
try:
return (True, float(v))
except:
return (False, None)
Main code:
allowed = {"K", "F", "C", "R"}
print(("Input two units (Celsius,Kelvin,Fahrenheit,Rankine) to convert from/to\n"
"and a value to convert (separated by spaces).\nEnter nothing to leave.\n"
"Example: K F 249 or Kelvin Rank 249\n\n"))
while True:
whatToDo = input("Your input: ").strip().upper()
if not whatToDo:
print("Bye.")
break
# exactly enough inputs?
wtd = whatToDo.split()
if len(wtd) != 3:
print("Wrong input.")
continue
# only care about the 1st letter of wtd[0] and [1]
if wtd[0][0] in allowed and wtd[1][0] in allowed:
frm = wtd[0][0]
to = wtd[1][0]
# only care about the value if it is a float
isFloat, value = tryParseFloat(wtd[2])
if isFloat:
print(value, frm, "is", convert(frm, to, value), to)
else:
print(wtd[2], " is invalid.") # not a number
else:
print("Invalid units - try again.") # not a known unit
Sample run & output:
Input two units (Celsius,Kelvin,Fahrenheit,Rankine) to convert from/to
and a value to convert (separated by spaces).
Enter nothing to leave.
Example: K F 249 or Kelvin Rank 249
Your input: f k 24
F K not supported.
24.0 F is n/a K
Your input: c f 100
Celsius to Fahrenheit
100.0 C is 212.0 F
Your input: c k 100
Celsius to Kelvin
100.0 C is 373.15 K
Your input: caesium kryptonite 100
Celsius to Kelvin
100.0 C is 373.15 K
Your input:
Bye.
To reduce the amount of code you might want to implement:
C2F, C2K, C2R, R2C, K2C, F2C
and for missing ones combine them (if you are ok with Is floating point math broken?) , f.e.:
def K2R(value):
return C2R(K2C(value)) # convert K to C and C to R for K2R
This question already has answers here:
Changing one character in a string
(15 answers)
Closed 1 year ago.
this is my code
this question submission is also giving me errors
import numpy as np
row=6
col=7
gamelist=[" "*col]*row
def gamefield():
print("1,2,3,4,5,6,7")
for i in range(row):
for j in range (col):
if j!=6:
print(gamelist[i][j],end="| ")
continue
else:
print(" ")
print("---------------------")
gamefield()
def move(r):
i=0
while(gamelist[i+1][r]==" "):
gamelist[i+1][r],gamelist[i][r]=gamelist[i][r],gamelist[i+1][r]
i=+1
return i
poi=1
poi=1
def main ():
poi=1
if poi==1:
r=int(input("Player 1 turn Enter column:"))-1
if gamelist[0][r]==" ":
hash="#"
gamelist[0][r]=gamelist[0][r].replace(" ",hash)
gamefield()
row=move(r)
check(row,r)
else:
print("Place occupied")
poi=2
else:
r=int(input("Player 2 turn Enter column:"))-1
if gamelist[0][r]==" ":
at="#"
gamelist[0][r]=at
gamefield()
row=move(r)
check(row,r)
else:
print("Place occupied")
poi=1
def check(r,c):
while r+3<6:
while c+3<7:
if gamelist[r][c]==gamelist[r+1][c] and gamelist[r][c]==gamelist[r+2][c] and gamelist[r][c]==gamelist[r+3][c] :
print("Player",poi,"Wins!!!")
break
elif gamelist[r][c]==gamelist[r][c+1] and gamelist[r][c]==gamelist[r][c+2] and gamelist[r][c]==gamelist[r][c+3] :
print("Player",poi,"Wins!!!")
break
elif gamelist[r][c]==gamelist[r][c-1] and gamelist[r][c]==gamelist[r][c-2] and gamelist[r][c]==gamelist[r][c-3] :
print("Player",poi,"Wins!!!")
break
elif gamelist[r][c]==gamelist[r+1][c+1] and gamelist[r][c]==gamelist[r+2][c+2] and gamelist[r][c]==gamelist[r+3][c+3] :
print("Player",poi,"Wins!!!")
break
elif gamelist[r][c]==gamelist[r-1][c-1] and gamelist[r][c]==gamelist[r-2][c-2] and gamelist[r][c]==gamelist[r-3][c-3] :
print("Player",poi,"Wins!!!")
break
elif gamelist[r][c]==gamelist[r-1][c+1] and gamelist[r][c]==gamelist[r-2][c+2] and gamelist[r][c]==gamelist[r-3][c+3] :
print("Player",poi,"Wins!!!")
break
elif gamelist[r][c]==gamelist[r+1][c-1] and gamelist[r][c]==gamelist[r+2][c-2] and gamelist[r][c]==gamelist[r+3][c-3] :
print("Player",poi,"Wins!!!")
break
else:
print("player",poi," turn over")
break
break
print("Connect 4")
if True :
main()
this is a connect 4 game in python and i have tried it many times to execute but i am getting the same error please help me to resolve it
i need to complete it asap
please resendto me where i have gone wrong
also how to edit strings in python?
gamelist is a list of strings:
>>> row=6
>>> col=7
>>> gamelist=[" "*col]*row
>>> print(gamelist)
[' ', ' ', ' ', ' ', ' ', ' ']
You try to assign a value to one of the characters in a string - You cannot to that.
>>> gamelist[0][2] = '5'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
However, you can use parts of the old string to make a new one.
As pointed out, you solved your problem but didn't implement it. Here is one way to do it.
>>> r=2
>>> gamelist[0] = gamelist[0][:r] + 'a' + gamelist[0][r+1:]
>>> gamelist
[' a ', ' ', ' ', ' ', ' ', ' ']
>>>
The gamelist matrix itself is not created properly. You need to create the matrix in the following way in order to modify its values-
gamelist=[[" "]*col for _ in range(row)]
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 know that this question has been asked numerous times but I am still unable to find the issue in my code. My program is a grade calculator. After inputting the grades I receive this error:
Traceback (most recent call last):
File "/Users/Jeremy/Documents/Python Projects/Mosier_Jeremy_HW4.py", line 59, in <module>
main ()
File "/Users/Jeremy/Documents/Python Projects/Mosier_Jeremy_HW4.py", line 53, in main
total = calcTotal (entry_exam1, entry_exam2, entry_exam3, entry_hw, entry_lqr, entry_fp)
File "/Users/Jeremy/Documents/Python Projects/Mosier_Jeremy_HW4.py", line 29, in calcTotal
total = float ((exam1 * EXAM1_WEIGHT) + (exam2 * EXAM2_WEIGHT) + (exam3 * EXAM3_WEIGHT) + (hw * HW_WEIGHT) + (lqr * LQR_WEIGHT) + (fp * FP_WEIGHT))
TypeError: can't multiply sequence by non-int of type 'float'
Here is my code:
EXAM1_WEIGHT = .2
EXAM2_WEIGHT = .2
EXAM3_WEIGHT = .2
HW_WEIGHT = .2
LQR_WEIGHT = .1
FP_WEIGHT = .1
def entry_validation (assignment) :
entry = -1
while entry == -1:
entry = input ('What was your final score for ' + assignment + '? ')
if entry == '':
entry = -1
print ('ERROR: You cannot leave this field blank. Please try again.')
else:
entry = float (entry)
if entry < 0 or entry > 100:
entry = -1
print ('ERROR: You score must be between 0 and 100. Please try again.')
return assignment
def calcTotal (exam1, exam2, exam3, hw, lqr, fp) :
total = float ((exam1 * EXAM1_WEIGHT) + (exam2 * EXAM2_WEIGHT) + (exam3 * EXAM3_WEIGHT) + (hw * HW_WEIGHT) + (lqr * LQR_WEIGHT) + (fp * FP_WEIGHT))
return total
def calcLetter (total) :
if total < 89.5:
return 'A'
elif total < 79.5:
return 'B'
elif total < 69.5:
return 'C'
elif total < 59.5:
return 'D'
else:
return 'F'
def main () :
entry_exam1 = entry_validation ('Exam 1')
entry_exam2 = entry_validation ('Exam 2')
entry_exam3 = entry_validation ('Exam 3')
entry_hw = entry_validation ('Homework')
entry_lqr = entry_validation ('Language Quick Reference')
entry_fp = entry_validation ('Final Project')
total = calcTotal (entry_exam1, entry_exam2, entry_exam3, entry_hw, entry_lqr, entry_fp)
letter = calcLetter (total)
print ('Your total score is a(n): ', format (total, ',.2%'))
print ('Your final letter grade is a(n): ', letter)
main ()
From your code I assume that you want entry_validation to return a float, but it is actually returning the string you provide when calling it.
For example, in:
entry_exam1 = entry_validation ('Exam 1')
entry_validation ('Exam 1') will return the string Exam 1. If you try to multiply a string by any float, you get the TypeError you reported.
You will have to modify you entry_validation function, so that it returns a float:
def entry_validation (assignment) :
entry = -1
while entry == -1:
entry = input ('What was your final score for ' + assignment + '? ')
if entry == '':
entry = -1
print ('ERROR: You cannot leave this field blank. Please try again.')
else:
# Let's handle possible exceptions when the input cannot be converted
try:
entry = float (entry)
if entry < 0 or entry > 100:
entry = -1
print ('ERROR: You score must be between 0 and 100. Please try again.')
else:
return entry
except ValueError:
entry = -1
print("ERROR: Must be a float")
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.