简体   繁体   中英

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. If anyone has any basic ideas, I'm new to python, so I'm not too knowledgeable about this language.

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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