2016-09-24 27 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 
相關問題