[Tutor] Function - Python
DL Neil
PyTutor at danceswithmice.info
Fri Apr 10 07:13:09 EDT 2020
On 10/04/20 9:10 PM, Zulfadli Azhar wrote:
> I just started to learn Python this week. I have some confusion here.
Which course are you attempting, or which book are you following?
> Please see below the code that I created. I supposed to come out with a
> Return #0000ff but it's not.
>
> def color_translator(color):
> if color == "red":
> hex_color = "#ff0000"
> elif color == "green":
> hex_color = "#00ff00"
> elif color == "blue":
> hex_color = "#0000ff"
> else:
> hex_color = "unknown"
> return "blue"
Notice how there is a change in the last two lines?
See below, you are expecting the function to return an RGB-triplet, but
above what is being returned on the last line?
Which gives you a hint for dealing with the other three possibilities.
What should be return-ed?
Is there a statement to do-so?
> print(color_translator("blue")) # Should be #0000ff
> print(color_translator("yellow")) # Should be unknown
> print(color_translator("red")) # Should be #ff0000
> print(color_translator("black")) # Should be unknown
> print(color_translator("green")) # Should be #00ff00
> print(color_translator("")) # Should be unknown
Here's a little extra idea for you:
assert color_translator( "blue" ) == "0000ff"
will smile at you if all is correct, but will raise an error (message)
if not. The computer does the work and saves you from reading and
checking - every time!
> Please do not tell me a direct answer but I need an explanation on how to
> come out with a Return #0000ff.
Good for you, this is the way to learn!
...and there you have written your own answer!
Perhaps you've spent so long looking at the problem, you've confused
yourself. Sometimes it is a good idea to stop what's confusing you, and
go off to do something else. Nine out of ten times: when you return the
answer will be obvious...
> I have 3 more questions to ask as I have spent my whole day today to figure
> get the correct code by referring from other sources.
One at a time helps stay organised!
Please copy-paste the code straight into (simple-test) email. The above
code has lost all indentation which may be 'hiding' other errors!
--
Regards =dn
More information about the Tutor
mailing list