I've got a book for python 2. in school and the problem is that we're programming in 3. which makes it difficult from time to time to get it right, cause you cant just copy the text in the book to the shell.

I'm stuck with this ex:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# This is a program to convert celsius to Fahrenheit

def main():
celsius = input('What is the temperature in celsius? ')
fahrenheit = (9.0 / 5.0) * celsius + 32
print('The temperature is', fahrenheit, 'degrees Fahrenheit.')

main()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~

when i run it in shell for 3. i get the following error msg:

"Can't convert 'int' object to str implicitly"


Now i need help to translate this to 3. python.


Best regards
Simon

Recommended Answers

All 7 Replies

try:

print('The temperature is %f degrees Fahrenheit.' % fahenheit)

The function input() in Python3 replaces the old Python2 function raw_input() and returns a string,so you have to use int() to convert the string to an integer value ...

def main():
    celsius = int( input("What is the temperature in celsius? ") )
    fahrenheit = (9.0 / 5.0) * celsius + 32
    print('The temperature is', fahrenheit, 'degrees Fahrenheit.')

main()

Thank you for the quick answers!

The last post made it, from vega~. The thing is that i want it to work with non-int(I think it's non-int, a complete rookie with programming, decimal number) numbers too. then

"celsius = int( input("What is the temperature in celsius? ") )" wont do it.
right? *confused*

So the question is, how do i make it to work with decimail numbers too?

Simply use float() instead of int() now you have numbers covered more generally.

Recommended book ...
"Dive Into Python"
Mark Pilgrim's Free online book, novice to pro, updated constantly.
rewritten for Python3 (check appendix A for the 2to3 differences)
http://diveintopython3.org/

Try:

fahrenheit = (9.0 / 5.0) * int(celsius) + 32

Unfortunatly that was going to be my first suggestion, but i was unsure about input only taking strings... i only use 2.6

Thanks alot. Float is the thing:icon_cheesygrin:

And thank you for the tip vegaseat!

Also with Python3 you don't have to use
fahrenheit = (9.0 / 5.0) * celsius + 32
you can just use
fahrenheit = (9 / 5) * celsius + 32
since '/' is now floating point division and '//' is integer division.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.