You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In programming, there is always more than one way to solve a problem. However, you will find that some solutions are usually better than others. Whenever you write code, there is usually a way that code can be improved either for improved readability, better performance, or best practices. Two rules of thumb to remember when refactoring your code are: Keep it Simple and Don't Repeat Yourself.
Refactoring (aka. cleaning up) our code
Let's tidy up our code so that it is shorter and cleaner. We can take our original list and actually change the function to return a lower case version of a true input when it runs, which eliminates having to list out specific upper/lower cases. Like so:
answer=input("Do you want to hear a joke? ")
affirmative_responses= ["yes", "y"]
negative_responses= ["no", "n"]
ifanswer.lower() inaffirmative_responses:
print("I'm against picketing, but I don't know how to show it.")
# Mitch Hedburg (RIP)elifanswer.lower() innegative_responses:
print("Fine.")
else:
print("I don't understand.")
And we can use .lower to eliminate the need for a list entirely:
answer=input("Do you want to hear a joke? ")
ifanswer.lower() inaffirmative_responses:
print("I'm against picketing, but I don't know how to show it.")
# Mitch Hedburg (RIP)elifanswer.lower() innegative_responses:
print("Fine.")
else:
print("I don't understand.")
There are some hiccups that may result from refactoring (depending on what your input is) but in general, this is a great way to improve your code.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
In programming, there is always more than one way to solve a problem. However, you will find that some solutions are usually better than others. Whenever you write code, there is usually a way that code can be improved either for improved readability, better performance, or best practices. Two rules of thumb to remember when refactoring your code are: Keep it Simple and Don't Repeat Yourself.
Refactoring (aka. cleaning up) our code
Let's tidy up our code so that it is shorter and cleaner. We can take our original list and actually change the function to return a lower case version of a true input when it runs, which eliminates having to list out specific upper/lower cases. Like so:
.lower
to eliminate the need for a list entirely:There are some hiccups that may result from refactoring (depending on what your input is) but in general, this is a great way to improve your code.
Beta Was this translation helpful? Give feedback.
All reactions