Python Forum
"return" value indentation
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
"return" value indentation
#1
Hi,

Regarding the code below

phone_letters = ["' '","","ABC","DEF","GHI","JKL","MNO","PQRS","TUV","WXYZ"]
def let_to_num():
    letter = input("Enter letter: ")
    key = 0
    while key < 10:
        if letter.upper() in phone_letters[key]:
            return key
        else:
            key = key + 1
    return "Not found"
        
print(let_to_num())
    
What is the significance of placing the return "Not found" at the same indentation as "while key < 10:"?

as compared to

phone_letters = ["' '","","ABC","DEF","GHI","JKL","MNO","PQRS","TUV","WXYZ"]
def let_to_num():
    letter = input("Enter letter: ")
    key = 0
    while key < 10:
        if letter.upper() in phone_letters[key]:
            return key
        else:
            key = key + 1
            return "Not found"
        
print(let_to_num())
    
By doing it as per the second code, the whole code will crumble and wont work? I can't get my head around this
Reply
#2
Isn't it clear - the difference is what will happen if letter is not in the first element of phone_letter.
You can use http://www.pythontutor.com/visualize.html to visualize the execution of the code and get better understanding of what's going on.

As a side note - it's easier to use dict, not list
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
great aid. thanks
Reply
#4
Hi,

In the first code, the return doesn't depend of the "if then else" does it ?
Python indentation marks blocks as begin/end in others programming languages.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020