So I finished day one and had a few questions about general good coding principles
1. She brought up the idea of nesting code, is this a good principle to adopt professionally?
For example:
Taking a non-nested program like this one, which tells you the number of characters in your name.
Ex: Bill = 4
-name = input (“What is your name?”)
-print(len(name))
VERSUS NESTING IT LIKE THIS (which she provides as an example)
print(len((input(“What is your name?))))
In terms of practicality and functionality, especially for future projects which is the better practice moving forward? Keeping the code elementary or trying to nest it?
2. This is a follow up that ties into the nesting question, but I am asking this to clear up some confusion.
So the function of this line of code is to create a new line for the input. Meaning that when the user has the option to input, it is on a new line, not the same one as the instructions.
Which is the better line of code (professionally)?
A:
- input(“What is your name? \n”)
OR
B:
- Print (“What is your name?”)
- input()
Readability is extremely important. While having
Code:
print(len((input(“What is your name?))))
Is valid, there's a lot going on in there too decipher. What if I gave you
Code:
print(len((input(“What is your name?)))))
Or
Code:
print(len((input(“What is your name?)))
How easy is it to spot the mistakes I introduced? I know you probably typed that on the fly, but you had a mistake anyway, no closing quote on the string literal. So even though it comes out to more lines of code, this is easier to parse visually when you're bug fixing and trying to look over your code again in 6-12 months.
Code:
name = input (“What is your name?”)
print(len(name))
In your second question, A is probably the better option because it's accepted that a call to input will print out the string you give it. Going with option B has you making an unnecessary call. If performance was a limitation, cutting down on method calls will give you a quicker execution time.
There's the computer science background on method calls.