查找数字中的数字的次数

时间:2011-10-23 22:52:03

标签: python

这就是我现在所处的状态,我仍然坚持如何使用for循环查找数字在数字中的次数。如果有人有任何基本想法,我是python的新手,所以我不太了解这种语言。

#Assignment 6

#Start out with print instructions
print """
This program will take a Number and Digit that you enter.
It will then find the number of times the digit is in your number.
Afterwards, this program will multiply your number by your digit.
"""

#Get the user's number

number = raw_input("Enter a number: ")

#Use a while loop to make sure the number is valid

while (number == ""):
    print "You have entered an invalid number."
    number = raw_input("Enter another number: ")

#Get the digit

digit = raw_input("Enter a digit between 0-9: ")

#Use a while loop to make sure the digit is valid

while (int(digit) > 9):
    print "You have entered an invalid digit."
    digit = raw_input("Enter a digit between 0-9: ")

#Set the count to 0
count = 0

#Show the user their number and digit

print "Your number is:", number, "And your digit is:", digit

#Use the for loop to determine how many times the digit is in the number

for d in number:
    if d == digit
        count +=1
    else
        count +=0
print d, count

3 个答案:

答案 0 :(得分:3)

>>> '123123123123111'.count('3')
4

答案 1 :(得分:2)

您的代码在当前阶段在语法上无效,

if d == digit
    count +=1
else
    count +=0

缺少冒号:

if d == digit:
    count +=1
else:
    count +=0 # or just pass, or better, skip the whole else tree

除此之外,它有效,但你应该抓住第一个(或第二个)输入时发生的错误,比如a

您尚未解决此子作业:

  

之后,该程序会将您的数字乘以您的数字。

Python tutorial对于找出如何乘以数字非常有帮助。

答案 2 :(得分:1)

您可以将用户的输入保存为字符串,并迭代字符串中的字符,如下所示:

number = "12423543534543"
digit = "3"

您可能需要考虑将其中的一部分放在方法中而不是内联中。

count = 0

for d in number:
  if d == digit:
    count += 1

print matched