2016-09-24 2 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 씩 증가합니다. 아래 코드를 붙여 넣었습니다. 마지막에 count 변수를 인쇄 할 수 있습니다.

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 

파이썬 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를 사용하는 것입니다, 그러나 이것은 파이썬의 고급 기능 사용

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 
관련 문제