2016-09-24 62 views
0

我想添加一些东西来计算变量的使用次数(如变量c),并以变量c的次数输出。我可以使用哪些功能?下面的代码:计算一个变量被调用的次数

#! /usr/bin/python 

question = raw_input 
y = "Blah" 
c = "Blahblahb" 


print "Is bacon awesome" 
if question() = "Yes": 
    print y 
else: 
    print c 

print "Blah" 
if question() = "Yes": 
    print y 
else: 
    print c 
+7

你认为什么“用”?当它被分配给?阅读?都?更重要的是,**为什么**?这听起来像是一个X Y的问题,告诉我们你实际上想要达到的目标,而不是你认为的解决方案。 –

+0

为什么不使用保持跟踪的getter和setter?未来更容易修改。 – David

回答

0

如果我正确理解你的问题,你可以试试这个:

question = raw_input 
y = "Blah" 
c = "Blahblahb" 
y_counter = 0 
c_counter = 0 


print "Is bacon awesome" 
if question() = "Yes": 
    print y 
    y_counter = y_counter + 1 
else: 
    print c 
    c_counter = c_counter + 1 

print "Blah" 
if question() = "Yes": 
    print y 
    y_counter = y_counter + 1 
else: 
    print c 
    c_counter = c_counter + 1 

print "y was used " + str(y_counter) + " times!" 
print "c was used " + str(c_counter) + " times!" 
+0

为什么你不使用'+ ='? – idjaw

0

你可以有一个计数器变量。让我们称之为'计数'。每次打印c时,您都会将计数递增1.我粘贴了下面的代码。您可以在最后打印计数变量

question = raw_input 
y = "Blah" 
c = "Blahblahb" 

count=0 

print "Is bacon awesome" 
if question() == "Yes": 
    print y 
else: 
    count+=1 
    print c 

print "Blah" 
if question() == "Yes": 
    print y 
else: 
    count+=1 
    print c 

print c 
0

您可以使用递增变量来完成此操作。

counter = 0 
# Event you want to track 
counter += 1 

你的Python 2.7的代码,用计数器:

question = raw_input 
y = "Blah" 
c = "Blahblahb" 
counter = 0 


print "Is bacon awesome" 
if question() = "Yes": 
    print y 
else: 
    print c 
    counter += 1 

print "Blah" 
if question() = "Yes": 
    print y 
else: 
    print c 
    counter +=1 

print counter 
+0

@ user3543300对不起?从什么时候开始+ =在Python中不起作用? –

0

你将不得不增加一个计数器和一个有许多方法可以做到这一点。一种方法是在class封装和使用property,但使用Python的更先进的功能:

class A(object): 
    def __init__(self): 
     self.y_count = 0 

    @property 
    def y(self): 
     self.y_count += 1 
     return 'Blah' 

a = A() 
print(a.y) 
# Blah 
print(a.y) 
# Blah 
print(a.y) 
# Blah 
print(a.y_count) 
# 3