Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (Retired) Slices sillyCase

Małgorzata Staniszewska
Małgorzata Staniszewska
2,431 Points

general question about number of variables

I attach two different versions of the same program. My question is: how many variables should I create? I realized that I tend to built a kind of "shorcuts" like in the first example. But on videos you show rather the second approach. Can you give advice?

silly.py
# The first half of the string, rounded with round(), should be lowercased.
# The second half should be uppercased.
# E.g. "Treehouse" should come back as "treeHOUSE"
def sillycase(string):
    half = round(len(string)/2)
    return(string[:half].lower() + string [half:].upper())

def sillycase(string):
    half = round(len(string)/2)
    string_1 = string[:half].lower()
    string_2 = string[half:].upper()
    new_string = string_1 + string_2
    return(new_string)

1 Answer

Hi Małgorzata Staniszewska

The general rule is to solve a problem with the least amount of code. So both your examples are correct although the second example uses 5 lines of code, making the first example much better. If you need to use a variable to store the string you could reduce the amount of code like so.

def sillycase(string):
    half = round(len(string)/2)
    new_string = string[:half].lower() + string[half:].upper()
    return(new_string)

The amount of variables you use will depend on code and problem you are trying to achieve. One thing to remember is not to repeat code i.e follow the principal of DRY or don't repeat yourself.