user1010007
user1010007

Reputation: 11

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

Upvotes: 0

Views: 7095

Answers (3)

JBernardo
JBernardo

Reputation: 33397

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

Upvotes: 5

IanNorton
IanNorton

Reputation: 7282

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

Upvotes: 1

phihag
phihag

Reputation: 287815

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.

Upvotes: 2

Related Questions