在python脚本中循环两次询问input()条目时

2024-09-27 09:33:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用python3.7.1(默认值,2018年12月14日,19:28:38)。你知道吗

首先,第二次在input()中输入正确的条目时,我的脚本运行正常,但我更希望它只询问一次。 在我的代码中,我写了print()行,以便实时查看正在发生的事情,而这正是我无法获取执行过程中发生的事情的地方。你知道吗

让我们看看剧本:

import subprocess
from scrapy import cmdline
import sys

champ_choix = ""
while champ_choix != "1" and champ_choix != "2":
    champ_choix=input("Pour cat_course tapez 1\nPour hippodrome tapez 2\n")
    print("L'input est : {}".format(champ_choix)) #the input is:
    print("le type de l'input est: {}".format(type(champ_choix))) #the type of input is:
    if champ_choix == "1": #Traite le champ hippodrome
        print("on a le champ_choix 1") #we have got choice 1
        #do instructions
        sys.exit() #to stop the script and stop asking once again an entry after it is done
    if champ_choix == "2":
        print("le champ_choix est 2") #we have got choice 2
        cmdline.execute(['scrapy','crawl','test_shell','-a','nom_prix=True'])
        sys.exit()

我在候机楼看到的是:

Pour cat_course tapez 1
Pour hippodrome tapez 2
2 # here a good entry
L'input est : 2 # it says it is a good entry
le type de l'input est: <class 'str'> # it even says that's the good type
le champ_choix est 2 # it even says it is in the second `if` condition
Pour cat_course tapez 1 # but it asks once again, without executing instructions
Pour hippodrome tapez 2
2 # a good entry once more
L'input est : 2
le type de l'input est: <class 'str'>
le champ_choix est 2 # in the second `if` condition and now gonna finally execute instructions
#Running the spider as expected, that is alright
#Stop and exit, it is alright too

怎么了?你知道吗


Tags: andtheleinputifistypeit
1条回答
网友
1楼 · 发布于 2024-09-27 09:33:51

措辞恰当的问题(给出标准输出的道具),但要确保你的间距合适(即在操作符之前和之后应该有一个空格,比如a == b)。你知道吗

1)不要使用sys.exit()只要使用break。你知道吗

2)你需要启动你的循环。换言之,在输入之前先进行一次输入
输入循环,然后在循环结束时继续输入:

import subprocess
from scrapy import cmdline
import sys

while True: 
    champ_choix = input("Pour cat_course tapez 1\nPour hippodrome tapez 2\n")

    # This first if isn't needed because the if at the bottom catches this case
    # if champ_choix == "1": #Traite le champ hippodrome
    #     break
    if champ_choix == "2":
        cmdline.execute(['scrapy','crawl','test_shell','-a','nom_prix=True'])
    if champ_choix in ["1", "2"]:
        break

相关问题 更多 >

    热门问题