I am very new to python and looking for a way to simplify the following:
if atotal == ainitial:
print: "The population of A has not changed"
if btotal == binitial:
print: "The population of B has not changed"
if ctotal == cinitial:
print: "The population of C has not changed"
if dtotal == dinitial:
print: "The population of D has not changed"
Obviously _total and _initial are predefined. Thanks in advance for any help.
The if-else statement is used to execute both the true part and the false part of a given condition. If the condition is true, the if block code is executed and if the condition is false, the else block code is executed.
You can use two dictionaries:
totals = {'A' : 0, 'B' : 0, 'C' : 0, 'D' : 0}
initials = {'A' : 0, 'B' : 0, 'C' : 0, 'D' : 0}
for k in initials:
if initials[k] == totals[k]:
print "The population of {} has not changed".format(k)
A similar way is first determining not changed populations:
not_changed = [ k for k in initials if initials[k] == totals[k] ]
for k in not_changed:
print "The population of {} has not changed".format(k)
Or, you can have a single structure:
info = {'A' : [0, 0], 'B' : [0, 0], 'C' : [0, 0], 'D' : [0, 0]}
for k, (total, initial) in info.items():
if total == initial:
print "The population of {} has not changed".format(k)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With