Try\except ; help

why this option…
why it is not “3” ???
why even there is the “cel = 0”??
please check if my trying to solve it is right…

tempt = “5 degrees”
fahr = float(tempt)
fahr = 41.0
cel = (fahr - 32.0) * 5.0 / 9.0

if you run it without try/except do you have any error?

yeah, i will have an error in the second line

have you actually try running it? because the second line does not give an error

isnt it right that we can not turn a string to float?

float works for strings or integers

you mean that i can convert a string to float?

yes, if the string is made a certain way

you can use this to run the code and see what happens

1 Like

Because if line3 is skipped, “fahr” is undefined and line4 cannot be executed. So both lines need to be in the try-block.
cel=0 is there so line5 can work, even if line3 and line4 are skipped.

1 Like

Bear in mind that data in its value form cannot be connected to a unit. A number is scalar. We need to devise a system of assigning units.

>>> float('5 degrees')
Traceback (most recent call last):
  File "<pyshell#119>", line 1, in <module>
    float('5 degrees')
ValueError: could not convert string to float: '5 degrees'

Easiest system is variable names.

>>> degrees_F = '5'
>>> degrees_F = float(degrees_F)
>>> degrees_F
1 Like

and the certain way is to make the string itself as a number right?
like this;

and the output will be 123.0 right ?

so how can i rewrite the code ??

and isnt it right that we can not skip line 3 because it will just produce an error ?

Sorry can you try rephrasing that question, because I don’t understand it.
Everything that can throw an error has to be put into the try-block → in the opening example that’s line3 and line4.
The except-block is executed IF the try-block runs into an error and only then.

If you post code please use the “</>” symbol above the text-field so it get’s properly formatted as code. Otherwise the forum removes spacing and indentation which makes Python code hard to read.

1 Like

can you rewrite the code in proper way?
and thanks for help

You mean this?
With that indentation it works.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.