简体   繁体   English

python for循环计数器返回0

[英]python for loop counter returns 0

Please excuse my noobishness. 请原谅我的无礼。 I've been hitting the python books and websites for the past 6 months because I really, really want to learn it, but occasionally I'll hit a road block where I just don't get why the simplest code won't work. 在过去的6个月中,我一直在访问python书和网站,因为我真的非常想学习它,但是偶尔我会遇到一个障碍,我只是不明白为什么最简单的代码行不通。

I've looked at quite a few stack overflow answers on this, to no avail. 我已经看了很多关于堆栈溢出的答案,但都没有用。

I'm working on some exercises that explicitly require the use of a python for loop counter system (I know there is such a thing called itertools and enumerate). 我正在做一些明确要求使用python for loop counter系统的练习(我知道有一个叫做itertools和enumerate的东西)。 Please see below: 请看下面:

>>> 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

output: 输出:

0
1
0
0
1
0
1

How do I just get it to return the sum of 3 that - that is, the number of 8's in variable a? 我怎样才能让它返回3的和-即变量a中8的数目?

You are setting your counter to zero in every loop cycle. 您将在每个循环周期中将计数器设置为零。 You have to define it outside the loop. 您必须在循环之外定义它。 Try: 尝试:

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

If you only want to print the number of times 8 is in the variable, you also have to keep the print statement outside the loop, so it would print only after the loop has been exhausted: 如果只想打印变量中8的次数,则还必须将print语句保留在循环之外,因此仅在循环用完后才打印:

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

Python string objects have a count() method which does what you need: Python字符串对象具有一个count()方法,该方法可以满足您的需求:

print(a.count('8'))

or 要么

print(a.count(b))

Should do it. 应该做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM