It is necessary for the code to stop at the first digit of a multi-valued integer number. What should be added?

n = int(input()) while n // 10 != 0: n = n // 10 
  • Now does not stop? Or what? - Enikeyschik
  • на первой цифре многозначного целочисленного числа is 10, for example? Or any number that has more than one digit? - Alex Po
  • Given for example the number 178, it is necessary that the program remembers 1 and discards the rest, but now in this code it goes to the end and leaves only 0 - Vladimir Makarov
  • while n >= 10: ( assert n >= 0 ) - jfs

2 answers 2

We translate the module of the number (in case of negative numbers) into the text and take the first character:

  n = str(abs(chislo))[0] 

If the result needs to be used as a number, then we convert the string again to a number:

 n = int(str(abs(chislo))[0]) 
  • For negative numbers it will be a minus? - andreymal
  • @andreymal aha. But the fix is ​​easy. Corrected. - Enikeyschik
 n = -50178 sign = False if n < 0: n *= -1 sign = True while n > 10: n //= 10 if sign: n *= -1 print(n) # -5 
  • "-5" is not a number, but a number. - Enikeyschik
  • If you want to use an additional variable, then sign = abs(n) == n replaces four lines with one. - Enikeyschik
  • @ Enikeyschik is important for the author of the question to understand what the code is doing, and it can be improved to infinity The goal is to set a working example. Remove the sign is easy. - slippyk