簡體   English   中英

查找數字中有多少次

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM