Complete noob to programming needs help with simplifying


#1

So, i’ve had a pretty slow start to learning python so far. I’m taking an edX class as well as the “learn python” course on here. I’m trying to take the lessons a little further, as I understand the very basic parts of coding now, but i’m having a problem remembering the details, and when to use what. This took me a good 40 minutes, for example.


city_name = “St. Assholeburg”
#current population of the city named St. Potatosburg
city_pop = 340000
#Uncounted Homeless
X = 3787
#Fathers
Y = 18

print(city_name + “-”)
print(“Population:”)
print(city_pop)

city_pop += X + Y
city_pop = str(city_pop)

p = “Population: Including children with leperosy,”
Y = " unemployed fathers,"
X = " and the uncounted ghosts of the homeless"

POC = [p, Y, X]
print(city_name + “-”)
print§ + (Y) + (X) + ‘-’ + (city_pop)


It finally came out how i wanted it to, but i cannot help but think there must be a way to simplify this. Either using dictionaries or something…but still using the variables. Can anyone give me any pointers on that?


#2

Let’s start with something cool like string formatting:

You can replace those separated print statments into one line like this code block:

print(city_name + "-")
print("Population: ")
print(city_pop)

Into this:

print("{} - Population: {}".format(city_name, city_pop))

Notice how for every curly brace pair {}, there is an argument inside .format method.

Also you don’t need to do two lines for the city_pop variable, instead you can do the follow:

city_pop += X + Y
city_pop = str(city_pop)

Is the same as:

city_pop = str(X + Y)

Another thing is that you don’t need another p, X, Y var since you can stay with just one big string. No idea why you split them into p, Y, X an stored into POC. A better approach would be based on string formatting.

print("{} - Population: Including children with leperosy, unemployed fathers, and the uncounted ghosts of the homeless - {}".format(city_name, city_pop))

Hope it helped you :smiley: