Count number of digits using for loop in Python - python

I want to count number of digits of any digits number without converting the number to string and also using for loop. Can someone suggest how to do this.
num = int(input("Enter any number : "))
temp = num
count = 0
for i in str(temp):
temp = temp // 10
count += 1
print(count)

If you stick to using input, you can't get away the fact that this function prompts a String. As for the for loop, simply count the number of characters in the input string:
num = input("Enter any number : ")
print(len(num))

You don't have to create a temp variable as num already contains the input.
If there should only digits being entered, you can first check that with a pattern, then get the length of the string without using any loop.
import re
inp = input("Enter any number : ")
m = re.match(r"\d+$", inp)
if m:
print(len(m.group()))
else:
print("There we not only digits in the input.")

i = int(input('num : '))
j=0
while i:
j+=1
i//=10
print(j)
Repeats dividing the entered number stored in i by 10 and adds 1 to j (result) Checks From i if it finds it equal to 0 it exits the iteration and prints the result j
i = 103
j = 0
#inside repetition :
i//=10 #i=10
j+=1 #j=1
i!=0 #completion
i//=10 #i=1
j+=1 #j=2
i!=0 #completion
i//=10 #i=0
j+=1 #j=3
i==0 #break
print j #result

Related

while loop won't works right in python

I wrote this code for summing up digits of a number which is bigger than 10 until the result only have one digit and when I try to compile it, it won't even give me an error until I stop it. I want to know what's the problem.
number = input()
#sumed_up_digits = result
result = 0
while len(number) != 1:
for i in number:
int_i = int(i)
result = result + int_i
number = str(result)
print(result)
Try the following code:
s=input()
n=len(s)
result=0
for i in range(n-1):
result=result+int(s[i])
print(result)
This for loop runs from 0th to (n-2)th index of the given string, hence the last digit will not be added to the result. Like for 1245, it will add 1,2 and 4 to result, but not 5.
result is cumulative and include previous sums.
try:
number = input()
#sumed_up_digits = sum
sum = 0
while len(number) != 1:
result = 0
for i in number:
int_i = int(i)
result = result + int_i
sum = sum + result
number = str(result)
print(sum)
You can do it like this:
number = input()
if len(number) <= 1:
print(0)
while len(number) > 1:
number = str(sum(int(i) for i in number))
print(int(number))
Of course, you would need to check that the initial input number is made of digits...
the problem is number isn't being shortened so the condition for the loop to stop is never reached.
number = input()
result = 0
while len(number) != 1:
# set digit to last number
digit = int(number) % 10
result += digit
number = number[:-1]
print(result)

Finding unique 9 digit numbers

I'm writing a program that accepts as input a 9 digit number with each number from 1-9 (i.e 459876231) The program takes that number and then finds the next highest number with the same digits. The code I have works, but only when I put the print statement within the for loop.
n = int(input("Please input a 9 digit number"))
n_str = str(n)
n_str1 = str(n+1)
while n < 1000000000:
for char in n_str:
if not char in n_str1:
n += 1
n_str1 = str(n)
print(n)
If I put don't indent the print statement to where it is now, the program will not work. Putting the print statement here also displays every number that the program tries on the way to the correct number, and I only want to display the final answer. Why is this happening? I've tried storing n in a completely new variable and then trying to print outside the loop but get the same thing.
It's because if you do n += 1, n will be 1, then 2, 3.., so you need to print n every time. If you print n outside of the for, it will only print its last value.
Your code is fixed like:
n = int(input("Please input a 9 digit number: "))
n_str = str(n)
n_str1 = str(n+1)
while n < 1000000000:
found = True
for char in n_str:
if not char in n_str1:
n += 1
n_str1 = str(n)
found = False
break
if found:
print(n)
break
There is a bug in your condition
for char in n_str:
if not char in n_str1:
If input number is 333222323, n_str1 is 333222324, digit check char in n_str1 would be all true and 333222323 would be the result.
I find the LeetCode problem 31. Next Permutation is quite similar to your question, and there are already many recommended solutions, most are more efficient than yours.
This example code is based on my LeetCode answer:
nstr = input("Please input a 9 digit number: ")
nums = [int(c) for c in nstr]
l = len(nums) # length should be 9
for i in range(l-2, -1, -1):
swap_idx, swap_n = None, None
for j in range(i+1, l):
if (nums[i] < nums[j]) and (not swap_n or (nums[j] < swap_n)):
swap_idx, swap_n = j, nums[j]
if swap_idx:
tmp = nums[i]
nums[i] = nums[swap_idx]
nums[swap_idx] = tmp
break
nums = nums[:i+1] + sorted(nums[i+1:])
print(''.join([str(i) for i in nums]))
With a test:
Please input a 9 digit number: 459876231
459876312
Please input a 9 digit number: 333222323
333222332

writing a loop that ends with a negative number and prints the sum of the positive numbers

i have to write a program with a loop that asks the user to enter a series of positive numbers. the user should enter a negative number to signal the end of the series, and after all positive numbers have been entered, the program should display their sum.
i don't know what to do after this, or whether this is even right (probably isn't):
x = input("numbers: ")
lst = []
for i in x:
if i > 0:
i.insert(lst)
if i < 0:
break
you should use input in the loop to enter the intergers.
lst = []
while True:
x = int(input('numbers:'))
if x > 0:
lst.append(x)
if x < 0:
print(sum(lst))
break
def series():
sum1 = 0
while True:
number = int(input("Choose a number, -1 to quit:"))
if number>=0:
sum1+=number
else:
return sum1
series()
while True means that the algorithm has to keep entering the loop until something breaks it or a value is returned which ends the algorithm.
Therefore, while True keep asking for an integer input , if the given integer is positive or equal to zero, add them to a sum1 , else return this accumulated sum1
You can use a while loop and check this condition constantly.
i, total = 0, 0
while i>=0:
total+=i
i = int(input('enter number:'))
print(total)
Also, don't use:
for loop for tasks you don't know exactly how many times it is going to loop
while loop as while True unless absolutely necessary. It's more prone to errors.
variable names that have the same name as some built-in functions or are reserved in some other ways. The most common ones I see are id, sum & list.
do you want that type of code
sum_=0
while True:
x=int(input())
if x<0:
break
sum_+=x
print(sum_)
Output:
2
0
3
4
5
-1
14
if you want a negative number as a break of input loop
convert string to list; input().split()
convert type from string to int or folat; map(int, input().split())
if you want only sum, it is simple to calculate only sum
x = map(int, input("numbers: ").split())
ans = 0
for i in x:
if i >= 0:
ans += i
if i < 0:
break
print(ans)

how can I compare the value of an element with the next element

how can I compare an element in a list with the next element to see whether they're the same? Let's say I have a list and I want to use for loop to iterate through the list and print out how many times the number is there before different number comes.
str_n = "5223888"
count = 1
#print(len(str_n))
number = [int(x) for x in str_n]
#print(number)
for i in number:
while number[i] == number[i+1]:
count+=1
i+=1
print(count, " ", i)
expected output:
15221338
It took me some time to understand what you where asking for . In your situation its best to go with a while loop
str_n = "5223888"
#print(len(str_n))
number = [int(x) for x in str_n]
#print(number)
i=0;
while(i<len(number)):
storei=i
count = 1
while i+1<len(number) and number[i] == number[i+1] :
count+=1
i+=1
i+=1
print("number is "+str(number[storei])+" count is "+str(count)))
OUTPUT
number is 5 count is 1
number is 2 count is 2
number is 3 count is 1
number is 8 count is 3
EDIT
in python3 to print the output you require you need to specify
str_n = "522388"
#print(len(str_n))
number = [int(x) for x in str_n]
#print(number)
i=0;
while(i<len(number)):
storei=i
count = 1
while i+1<len(number) and number[i] == number[i+1] :
count+=1
i+=1
i+=1
#print("number is "+str(number[storei])+" count is "+str(count))
print(str(count)+str(number[storei]),end="")
And in python 2 to get the exact output you need to specify like
str_n = "522388"
import sys
#print(len(str_n))
number = [int(x) for x in str_n]
#print(number)
i=0;
while(i<len(number)):
storei=i
count = 1
while i+1<len(number) and number[i] == number[i+1] :
count+=1
i+=1
i+=1
#print("number is "+str(number[storei])+" count is "+str(count))
sys.stdout.write(str(count)+str(number[storei]))
Mistakes
When you do for i in number, you iterate over "2" two times and "8" three times which gives wrong output.
You did not initialize count to zero at each iteration.
for i in number iterates over the values in number, not the index
Correct code
You can use the following code:
str_n = "5223888"
number = [int(x) for x in str_n]
for i in set(number):
print("Element " + str(i) + " occurs " + str(number.count(i)) + " times")
When you wrote for i in number you probably meant for i in range(len(number)) which would make i be the indices of the number list.
That being said, you don't really need the indices; when you say for num in number, num is the actual number in the list. You can accomplish what you want without indices with something like this:
count = 0
current = number[0]
for num in number:
if num == current:
count += 1
else:
print(count, current)
current = num
count = 1
print(count, current) # print the last count
This gives us:
1 5
2 2
1 3
3 8

While loop python resulting in infinite loop

def generate_n_chars(n,s="."):
res=""
count=0
while count < n:
count=count+1
res=res+s
return res
print generate_n_chars(raw_input("Enter the integer value : "),raw_input("Enter the character : "))
I am beginner in python and I don't know why this loop going to infinity. Please someone correct my program
The reason is because the input will be evaluated and set to a string. Therefore, you're comparing two variables of different types. You need to cast your input to an integer.
def generate_n_chars(n,s="."):
res=""
count=0
while count < n:
count=count+1
res=res+s
generate_n_chars(int(raw_input("Enter the integer value : ")),raw_input("Enter the character : "))
def generate_n_chars(n, s = "."):
res = ""
count = 0
while count < n:
count = count + 1
res = res + s
return res
print generate_n_chars(input("Enter the integer value : "), raw_input("Enter the character : "))
Here input("Enter the integer value : ") input instead of raw_input
raw_input() => https://docs.python.org/2/library/functions.html#raw_input
input() => https://docs.python.org/2/library/functions.html#input

Categories