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

如何使用Python从用户处获取准确数量的输入?,python,for-loop,input,while-loop,controls,Python,For Loop,Input,While Loop,Controls,我对编程比较陌生,尤其是Python。我被要求创建一个for循环,打印用户给出的10个数字。我知道如何获取输入以及如何创建for循环。困扰我的是,我的程序依赖于用户插入10个数字。如何使程序控制插入的数字数量?以下是我尝试过的: x = input('Enter 10 numbers: ') for i in x: print(i) 你需要 问10次:做一个10号的循环 询问用户输入:使用input功能 如果要在之后保存它们,请使用列表 choices = [] for i in

我对编程比较陌生,尤其是Python。我被要求创建一个for循环,打印用户给出的10个数字。我知道如何获取输入以及如何创建for循环。困扰我的是,我的程序依赖于用户插入10个数字。如何使程序控制插入的数字数量?以下是我尝试过的:

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

  • 问10次:做一个10号的循环
  • 询问用户输入:使用
    input
    功能
如果要在之后保存它们,请使用
列表

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)

我借用了

中的数字检查功能,有很多不同的方法可以做到这一点:我首选的方法是使用for循环。制作一个for循环,循环10次(
for uuuuuuuuu9):
),每次都将您的输入记录在一个列表中。我不确定我们的作业的参数是什么,但是如果你需要对输入进行验证,请看。这不是重复的,谢谢你的快速回复。f到底是做什么的?我假设它类似于一个计数器,对吗?@hristogorgiev它表示一个f-string,这是Python中字符串格式化的一种新方法。@hristogorgiev f-strings是
“{}{}{}”的一种较短方式。format(obja,objb)
直接将值插入quotes@HristoGeorgiev你现在可以考虑接受答案/投票支持;)@阿兹罗你什么意思?我对你的解决方案投了赞成票。我昨天注册了这个网站哈。
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)