why is the dcount and tcount 0 and 0 in the output

0 votes

Why are the dcount and tcount 0 and 0 in the output?

a = [1, 2, 3, 4]
dcount = 0
tcount = 0
def doubles():
  dcount = 0
  for i in a:
    for j in a:
      if (i+j)%3 == 0:
        dcount += 1
        print(i,j)

def triplets():
  tcount = 0
  for i in a:
    for j in a:
      for k in a:
        
        if (i+j+k)%3 == 0:
          tcount += 1
          print(i,j,k)

doubles()
triplets()
print(dcount)
print(tcount)
4 1 4
4 2 3
4 3 2
4 4 1
4 4 4
0
0
[Finished in 0.1s]
Nov 6, 2020 in Python by Roshni
• 10,440 points
44 views

1 answer to this question.

0 votes

Because the dcount and tcount variables you use inside the functions aren't the same as the one on outside.

There's two ways:
1) you can just return the values and store it inside dcount instead of declaring it.

def doubles():
     //blah blah
     return dcount

dcount = doubles()

2) use global variables (not recommended) 

def triplets():
    global tcount 
    // blah blah

If the same names confuses you, you can use another name:

def doubles():
     doubles_count = 0
     //blah blah
     return doubles_count

dcount = doubles()
answered Nov 6, 2020 by Gitika
• 65,870 points

Related Questions In Python

0 votes
1 answer

What is the output of and explanation?

It will print concatenated lists. Output would ...READ MORE

answered Jul 20, 2018 in Python by Priyaj
• 58,120 points
101 views
+1 vote
2 answers

What is the difference between classes and labels in machine learning?

Classes and Labels both are almost same things ...READ MORE

answered Apr 3, 2019 in Python by SA
• 1,050 points
1,484 views
+1 vote
1 answer

What is the difference between range and xrange functions in Python 2.X?

xrange only stores the range params and ...READ MORE

answered Aug 22, 2018 in Python by Priyaj
• 58,120 points
1,103 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 2,033 views
0 votes
0 answers
+4 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,810 points
1,557 views
0 votes
5 answers
+1 vote
1 answer

What is the difference between .py and .pyc files in Python?

Hi, @Roshni, You can follow a few steps ...READ MORE

answered Jun 23, 2020 in Python by Gitika
• 65,870 points
2,720 views