Code cleanliness and readabilty

Hello! So I’m following the lesson about string splitting and I have a question about code cleanliness and readability…

The example provided in the lesson is as follow

favorite_song = 'SmOoTH'
favorite_song_lowercase = favorite_song.lower()
print(favorite_song_lowercase)

But if you write this following code the result is the same, with 1 line less

favorite_song = 'SmOoTH'
print(favorite_song.lower())

In the following lesson the code example provided is this:

man_its_a_hot_one = "Like seven inches from the midday sun"
print(man_its_a_hot_one.split())

Why, in this case didnt follow the same logic, so to assign the method to another variable? like this?

man_its_a_hot_one = "Like seven inches from the midday sun"
man_its_a_hot_one_splitted = man_its_a_hot_one.split()
print(man_its_a_hot_one_splitted)

Ignoring completely the fact that variable may be useful if the program gets bigger, can someone explain me the logic behind deciding between printing a method or printing a variable that contains a method?

Of course this doesnt extend only to this lesson but as a logic in general, final example:

Why this:

print("Hello World")

is better, or worst, than this?

hello_world = ("Hello World")
print(hello_world)

Thanks!

Hello,

I don’t think variable names have as much of an effect on scalability as much as loose functionality does. Both of the methods you mention are builtins for the str object they act on, so I’m not sure you should be so concerned with whether you should store the result in a variable or not. It’s pretty easy to split a string or call lower at another point in your program if need be.

If you are going through a series of steps on a string, I.E calling split, lower, join, then performing search and transforming the result, then you should store that functionality inside of a function definition in case you need to reuse it. That’s going to have a greater impact on the scalability and reuse of your application logic than the addition or subtraction of a single variable name when calling a single builtin like lower.

Also, in regards to your last example, if you plan on using the string "Hello, World!" in more than one place, then you should absolutely store that value in a variable. In general, you can use this rule to decide whether to use a variable. If that value is used in more than one spot within the same scope, then you should probably use a variable.

Just my personal opinion

1 Like