[英]Finding how many times a digit is in a number
目前,这是我要解决的问题,我坚持使用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
>>> '123123123123111'.count('3')
4
您的代码在当前阶段在语法上是无效的,
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教程对找出如何将数字相乘会非常有帮助。
您可以将用户的输入保留为字符串,并像这样遍历字符串的字符:
number = "12423543534543"
digit = "3"
您可能要考虑将其中的一些放在方法中而不是内联。
count = 0
for d in number:
if d == digit:
count += 1
print matched
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.