Reputation: 25
I want the first if ... else
statement to check both a
and b
simultaneously. And I want an efficient way of counting no_of_good and no_of_poor in order to minimize the number of lines of code. Is it possible?
How can I print both a
and b
as good in if statement? And also how to calculate good and poor count?
a = 1
b = 3
good_count=0
poor_count=0
if a in range(0,6) and b in range(0,6):
//print and count
elif a in range(6,10) and b in range(6,10):
//pprint and count
This is a long method of doing the work:
a = 1
b = 3
good_count=0
poor_count=0
if a in range(0,6):
print("a = GOOD")
good_count+=1`
elif a in range(6,10):
print("a = POOR")
poor_count+=1
if b in range(0,6):
print("b = GOOD")
good_count+=1
elif b in range(6,10):
print("b = POOR ")
poor_count+=1
print("no_of_good=",good_count," ","no_of_poor=",poor_count)
Actual output:
a = GOOD
b = GOOD
no_of_good= 2 no_of_poor= 0
Expected output should also be same but by using any different method
Upvotes: 0
Views: 807
Reputation: 20490
If you don't care about the variables, a,b,c,d
etc, you can just use a list, and use the index of the lis t to print GOOD
or POOR
li = [1,3,5,6]
good_count = 0
poor_count = 0
#Iterate through the list
for idx, item in enumerate(li):
#Check the condition on the item and print accordingly
if 0 <= item <= 5:
good_count+=1
print('index {} = GOOD'.format(idx))
elif 6<= item <= 10:
poor_count+=1
print('index {} = POOR'.format(idx))
#Print final good and poor count
print('no_of_good = {}'.format(good_count))
print('no_of_poor = {}'.format(poor_count))
The output will be as below:
index 0 = GOOD
index 1 = GOOD
index 2 = GOOD
index 3 = POOR
no_of_good = 3
no_of_poor = 1
Upvotes: 0
Reputation: 16505
If you don't want to repeat your if statements then you could look into having a datatstructure to hold your values and iterate over all the values.
I also changed the condition to use integer comparisson instead of a range; it seames cleaner in my opinion.
Here is an example using a dict
to hold the data:
data = {
'a': 1,
'b': 3,
'c': 5,
'd': 6,
}
good_count = 0
poor_count = 0
for k, v in data.items():
if 0 <= v <= 5:
good_count += 1
result = 'GOOD'
else:
poor_count += 1
result = 'POOR'
print('{} = {}'.format(k, result))
print('no_of_good = {}'.format(good_count))
print('no_of_poor = {}'.format(poor_count))
And this is the output:
a = GOOD
b = GOOD
c = GOOD
d = POOR
no_of_good = 3
no_of_poor = 1
Does that help you?
Upvotes: 1