Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何向投币式Python代码中添加命令?_Python_Python 3.x_List - Fatal编程技术网

如何向投币式Python代码中添加命令?

如何向投币式Python代码中添加命令?,python,python-3.x,list,Python,Python 3.x,List,我是编程新手,遇到了一个问题。 以下是我编写的简单抛硬币模拟器代码: import random import time chosen_side = input("Type Heads or Tails: ") options = ['Heads', 'Tails'] q = (random.choice(options)) if chosen_side == q: for x in range (0,5): b = "Flipping" + "." * x

我是编程新手,遇到了一个问题。 以下是我编写的简单抛硬币模拟器代码:

import random
import time

chosen_side = input("Type Heads or Tails: ")
options = ['Heads', 'Tails']
q = (random.choice(options))

if chosen_side == q:
    for x in range (0,5):
        b = "Flipping" + "." * x
        print (b, end="\r")
        time.sleep(0.3)
    time.sleep(0)
    print("-------------")
    print("You have Won!")
    print("--------------")

if chosen_side != q:
    for x in range (0,5):
        b = "Flipping" + "." * x
        print (b, end="\r")
        time.sleep(0.3)
    time .sleep(0)
    print("--------------")
    print("You have Lost!")
    print("--------------")

代码本身是有效的,但我有一个名为“选项”的列表,其中包含“正面”和“反面”(在第5行)。所以我想说,如果你不在“选项”列表中输入一个单词,硬币就不会翻转,它会告诉你“无效输入”。所以基本上我想让投币只在你输入“正面”或“反面”时有效

您可以在获得所选的\u端后添加验证

chosen_side = input("Type Heads or Tails: ")
options = ['Heads', 'Tails']
if chosen_side.strip().title() not in options:
    raise ValueError('Invalid Input')
    # you can also just print('invalid input') and return if you dont want an error

我们使用的是
.strip
。title
因此
heads
tails
等仍然可以接受。但是你也可以只检查
,如果选择的站点不在选项中

,你可以在获得所选站点后添加验证

chosen_side = input("Type Heads or Tails: ")
options = ['Heads', 'Tails']
if chosen_side.strip().title() not in options:
    raise ValueError('Invalid Input')
    # you can also just print('invalid input') and return if you dont want an error

我们使用的是
.strip
。title
因此
heads
tails
等仍然可以接受。但是你也可以只检查
如果选择了\u site not in options

modesit的答案很好,但是可以通过添加while循环来改进,如果用户输入无效,可以重新输入选项,类似这样:

while chosen_side.lower() != 'heads' or chosen_side.lower() != 'tails':
    chosen_side = input('You have entered an invalid input! Please try again\nHeads or 
    tails?\n> ')

modesitt的答案很好,但可以通过添加while循环来改进,在该循环中,如果用户因无效输入而失败,则可以重新输入选项,如下所示:

while chosen_side.lower() != 'heads' or chosen_side.lower() != 'tails':
    chosen_side = input('You have entered an invalid input! Please try again\nHeads or 
    tails?\n> ')

您应该阅读
elif
else
if语句的部分。您应该阅读
elif
else
if语句的部分。