如何使用 Python 从用户那里获取准确的输入数量?

How to take exact number of inputs from the user using Python?

我对编程比较陌生,尤其是 Python。我被要求创建一个 for 循环,打印用户给定的 10 个数字。我知道如何接受输入以及如何创建 for 循环。令我困扰的是,在我的程序中,我需要用户输入 10 个数字。如何让程序控制插入多少个数字?这是我尝试过的:

x = input('Enter 10 numbers: ')
for i in x:
    print(i)

你需要

  • 问 10 次:做一个大小为 10 的循环
  • 询问用户输入:使用 input 函数
for i in range(10):
    choice = input(f'Please enter the {i+1}th value :')

如果您想在之后保留它们,请使用 list

choices = []
for i in range(10):
    choices.append(input(f'Please enter the {i + 1}th value :'))

# Or with list comprehension
choices = [input(f'Please enter the {i + 1}th value :') for i in range(10)]

如果输入的行包含以空格分隔的单词(数字)怎么办?我建议你检查是否有 10 个单词,并且它们肯定是数字。

import re
def isnumber(text):
   # returns if text is number ()
   return re.match(re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$"), text)

your_text = input() #your input
splitted_text = your_text.split(' ') #text splitted into items

# raising exception if there are not 10 numbers:
if len(splitted_text) != 10:
    raise ValueError('you inputted {0} numbers; 10 is expected'.format(len(splitted_text)))

# raising exception if there are any words that are not numbers
for word in splitted_text:
    if not(isnumber(word)):
        raise ValueError(word + 'is not a number')

# finally, printing all the numbers
for word in splitted_text:
    print(word)

我从this answer

那里借号查号