简体   繁体   English

查找数字中有多少次

[英]Finding how many times a digit is in a number

This is currently what I'm at, I'm stuck with how to find how many times the digit was in the number, using the for loop. 目前,这是我要解决的问题,我坚持使用for循环查找数字中数字的次数。 If anyone has any basic ideas, I'm new to python, so I'm not too knowledgeable about this language. 如果有人有任何基本想法,我是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
>>> '123123123123111'.count('3')
4

Your code is syntactically invalid in its current stage, 您的代码在当前阶段在语法上是无效的,

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

is missing colons: 缺少冒号:

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

Apart from that, it works, although you should catch the errors that occur when the first (or second) input is, say, a . 除此之外,它还可以工作,尽管您应该捕获第一个(或第二个)输入为a时发生的错误。

You haven't yet solved this sub-assignment: 您尚未解决此子分配:

Afterwards, this program will multiply your number by your digit. 然后,该程序将您的数字乘以您的数字。

The Python tutorial will be very helpful in finding out how to multiply numbers. Python教程对找出如何将数字相乘会非常有帮助。

You can keep your user's inputs as strings and iterate through the characters of the string like so: 您可以将用户的输入保留为字符串,并像这样遍历字符串的字符:

number = "12423543534543"
digit = "3"

You might want to consider putting some of this in a method instead of inline. 您可能要考虑将其中的一些放在方法中而不是内联。

count = 0

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

print matched

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

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