Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - simplify repeated if statements

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.

like image 833
user3619552 Avatar asked May 09 '14 08:05

user3619552


People also ask

What is ifelse in Python?

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.


1 Answers

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)
like image 168
perreal Avatar answered Sep 30 '22 10:09

perreal