2012-12-20 118 views
-1

請原諒我的noobishness。我在過去6個月中一直在使用Python書籍和網站,因爲我真的很想學習它,但偶爾我會遇到一個障礙,我只是不明白爲什麼最簡單的代碼無法工作。python for循環計數器返回0

我已經看過不少堆棧溢出的答案,對此無濟於事。我正在做一些明確要求使用python for循環計數器系統的練習(我知道有這樣一個叫itertools和枚舉的東西)。請看下面:

>>> a = raw_input('Please enter a 7-digit number: ')  
Please enter a 7-digit number: 7893848  
>>> b = raw_input('Please enter a single digit number: ')  
Please enter a single digit number: 8  
    for i in a:    
     count = 0    
     if i == b:     
      count += 1    
     print count 

輸出:

0 
1 
0 
0 
1 
0 
1 

如何我只是得到它返回的3總和即 - 即8點的的變量是多少?

回答

2

您在每個循環週期中將計數器設置爲零。你必須在循環之外定義它。嘗試:

c=0 
for i in range(10): 
    print c  
    c+=1 

如果你只想打印次數8是可變的,你也必須保持print語句外循環,所以它的循環已經耗盡之後纔打印:

a='7893848' 
b='8' 
count=0 
for i in a: 
    if i==b: 
     count+=1 
print count 
+0

gotcha,謝謝你的根! – user1917854

2

Python字符串對象都有一個count()方法,做你所需要的:

print(a.count('8')) 

print(a.count(b)) 

應該這樣做。