简体   繁体   English

通过Python中的输入循环

[英]Looping through inputs in Python

I have a python script where we get the input from the USER (in the command window, no need for GUI window at this point). 我有一个python脚本,我们从USER获取输入(在命令窗口中,此时不需要GUI窗口)。 once the user provides the input, the provided input has to be validated and the if the input is in wrong format, the input needs to be asked again & again till the input is correct. 一旦用户提供输入,就必须验证提供的输入,如果输入的格式错误,则需要再次询问输入,直到输入正确为止。 The part of the script where user input is asked & validated is below & working absolutely fine. 询问和验证用户输入的脚本部分低于&工作绝对正常。

SOname = '1'  #something that doesn't validate
while True:
    SOname = input("Please enter the order number: ").upper()
    if not re.match(r"\b[A-Z]{2}[-][0-9]{6}\b", SOname):
        print ("Error! Please enter order in format 'AS-XXXXXX'"
    else:
        break

After this condition is satisfied, the order number is used further to do a lot of activities. 满足此条件后,订单号将进一步用于执行大量活动。 However, completing the rest of the program takes 2 minutes (it involves a lot of file copying, PDF reading etc...) & i do not want the user to keep waiting for the program to end and start again to enter another order number. 但是,完成剩余的程序需要2分钟(它涉及大量的文件复制,PDF阅读等...)我不希望用户继续等待程序结束并再次开始输入另一个订单号。

So, i want to provide the option of entering multiple order numbers separated by space(for ex: they can enter 5 order numbers & work on something else while the python program runs for 10-12mins). 因此,我想提供输入由空格分隔的多个订单号的选项(例如:他们可以输入5个订单号并在python程序运行10-12分钟时处理其他内容)。 And just like for a single order number, each of the entries should be validated for the above mentioned criteria & each of the number should go through the rest of the program. 就像单个订单号一样,每个条目都应该针对上述标准进行验证,并且每个条目都应该通过程序的其余部分。

Here is where i am failing miserably. 这是我悲惨失败的地方。 I wrote a small program to check if all the elements go through the loop and it does not & i cannot figure out why. 我写了一个小程序来检查是否所有元素都通过循环而它没有&我无法弄清楚原因。

user_input = input("Enter Numbers:")
Ui = user_input.split()
for i in range(len(Ui)):
    if i == 2:
        print(i)
    else:
        print ("tada")

If it enter the values "2 4 2 4 2 4", i get the output " tada tada 2 tada tada tada" 如果输入值“2 4 2 4 2 4”,我得到输出“tada tada 2 tada tada tada”

it does not even makes sense to me. 它对我来说甚至都没有意义。 it prints 2 once but there are 3 2's in the input. 它打印2次,但输入中有3个2。 What am i doing wrong? 我究竟做错了什么? how do I make input to go through the validation, then through the rest of the program. 如何进行验证,然后通过程序的其余部分。 And also, in a scenario when the user started the program but does not want to give an input , how to end the script by clicking Esc key?? 而且,在用户启动程序但不想提供输入的情况下 ,如何通过单击Esc键来结束脚本? I looked up in a lot of places but nothing is working for me. 我抬头看了很多地方,但没有什么对我有用。

The condition is over i which is the current index in the loop (because you iterated on range(len(Ui)) ), eg, it takes values from 0, 1, 2, and so on. 条件超过i ,这是循环中的当前索引(因为您在range(len(Ui))上迭代),例如,它从0,1,2等取值。

I guess you expected i to be the current value introduced by the user. 我想你希望i成为用户引入的当前值。 If so, then the loop should be for i in Ui: instead. 如果是这样,那么循环应该是for i in Ui:相反。 Notice however than this value is a string, not an integer (even if the input looks like an integer). 但请注意,此值是一个字符串,而不是整数(即使输入看起来像一个整数)。 So the comparison should be i == "2" (or int(i) == 2 , but this is not error-proof if the user enters something that cannot be converted by int ). 因此,比较应该是i == "2" (或int(i) == 2 ,但如果用户输入无法通过int转换的内容,则这不是防错的)。

The variable i in the loop is not taking on the value of the data but the index into that data. 循环中的变量i不是采用数据的值而是采用该数据的索引。 So the first time through it will have a value of 0, the next time 1, etc. So you will always print out '2' as the second element no matter what your actual input. 因此,第一次通过它将具有值0,下一次1,等等。因此无论您的实际输入是什么,您将始终打印出'2'作为第二个元素。

If you want to iterate across the values of your list try: 如果要迭代列表的值,请尝试:

for i in Ui:
   if int(i) == 2:
       print(i)

The int() is there because the input will be a string from the input, and not an integer. int()是因为输入将是输入的字符串,而不是整数。

A fuller example, using your regex validation would look like: 更完整的示例,使用正则表达式验证将如下所示:

import re

while True:
    user_input = input("Enter Numbers:")
    Ui = user_input.split()
    for order in Ui:
        if not re.match(r"\b[A-Z]{2}[-][0-9]{6}\b", order):
            print ("Error! Please enter order in format 'AS-XXXXXX', not {}".format(order))
            break
    else:
        break

print("Orders are {}".format(", ".join(Ui)))

Firstly, regarding your second splitting code, you probably missed out type conversion. 首先,关于你的第二个拆分代码,你可能错过了类型转换。

In Python, 2 == '2' will return False . 在Python中, 2 == '2'将返回False

So, to make the second part of your code work, this will help: 因此,要使代码的第二部分工作,这将有助于:

user_input = input("Enter Numbers:")
Ui = user_input.split()
for i in range(len(Ui)):
    if int(i) == 2:
        print(i)
    else:
        print ("tada")

Now, furthermore, your order IDs are seemingly in format AS-XXXXXX . 此外,您的订单ID现在看似AS-XXXXXX格式。 In this case, you wouldn't have to do the int type-casting. 在这种情况下,您不必进行int类型转换。 Because your order IDs are anyway going to be String . 因为您的订单ID无论如何都是String

So for entering multiple order IDs, this might help (also, I have taken the liberty to add the ESC key exit which you wanted, even though I would say it's a whole topic in itself): 因此,对于输入多个订单ID,这可能会有所帮助(同样,我已经冒昧地添加了您想要的ESC键退出,即使我说它本身就是一个完整的主题):

import keyboard    
while True:
    if keyboard.is_pressed('ESC'):
        break
    else:
        SOname = input("Please enter the order number:  (If multiple, seperate by spaces)").upper()
        if(SOname == 
        IDArray = SOname.split()
        for ID in IDArray:
            if not re.match(r"\b[A-Z]{2}[-][0-9]{6}\b", ID):
            print ("Error in ", ID, " Please enter order in format 'AS-XXXXXX'")
        else:
            break

For using keyboard , you might want to pip install keyboard in your shell. 对于使用keyboard ,您可能希望在shell中使用pip install keyboard

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM