Reputation: 45
How would I change this in order to count the number of sevens in a positive integer.
num = int(input("Enter a positive integer: "))
while num >= 1:
digit = num % 10
num = num//10
print(digit)
Upvotes: 0
Views: 271
Reputation: 236004
Using your code as a basis, just declare a variable to count the sevens, and increment it when the current digit is a seven:
sevens = 0
while num >= 1:
digit = num % 10
if digit == 7:
sevens += 1
num = num // 10
print(sevens)
Of course, there are more pythonic ways to do this:
num = input('Enter a positive integer: ')
print(num.count('7'))
Upvotes: 2
Reputation: 2328
You could convert it to a string, then use the count function.
num = int(input("Enter a positive integer: "))
print(str(num).count('7'))
Upvotes: 0