[英]How to print numbers on a new line in python without seperating parameters by commas?
I am trying to create a function in which python must print each individual digit of the number in a different line.我正在尝试创建一个 function ,其中 python 必须在不同的行中打印数字的每个单独的数字。 I have to deal with numbers and digits mathematically instead of strings.
我必须以数学方式处理数字和数字而不是字符串。 However as I initially approached it I approached it using the string method to have some grasp on where to begin.
然而,当我最初接近它时,我使用 string 方法接近它以了解从哪里开始。 However the code I did works as I need it to only if the user inputs a group numbers that are separated by commas.
但是,仅当用户输入以逗号分隔的组号时,我所做的代码才可以正常工作。 I want for the user to input for example;
例如,我希望用户输入; (my_numbers(4523)):
(我的号码(4523)):
4 4
5 5
2 2
3 3
Here is the code i've been working on:这是我一直在处理的代码:
def my_numbers():
item = input('enter num:')
result='\n'.join(item.split(','))
print(result)
my_numbers()
Non string approach:非字符串方法:
import math
def my_numbers():
item = int(input('enter num: '))
digits = [(item//(10**i))%10 for i in range(math.ceil(math.log(item, 10)), -1, -1)][bool(math.log(item,10)%1):]
for d in digits:
print(d)
See: Turn a single number into single digits Python参见: 将单个数字变成单个数字 Python
You should also take into consideration negative numbers and 0. math.log
unfortunately doesn't work on these kind of input.您还应该考虑负数和 0。遗憾的是,
math.log
不适用于此类输入。 An alternative would be to use a while loop.另一种方法是使用 while 循环。
def my_numbers():
item = int(input('enter num:'))
result = []
if item == 0:
print(item)
elif item < 0:
item = -item
print('-')
while item > 0:
# Extract last digit
digit = item % 10
result.insert(0, digit)
# Remove last digit
item = item // 10
for digit in result:
print(digit)
my_numbers()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.