[英]Why is the else statement not executed?
import random
words = ["Rock", "Paper", "Scissors"]
wins, loss = 0, 0
while True:
word = random.choice(words)
ur_word = input("Rock, Paper, Scissors..: ")
print("\nComputer: {0}\nYou: {1}\n".format(word, ur_word))
if word == ur_word:
print("Tie!")
continue
elif ur_word == 'q':
break
elif word == 'Rock':
if ur_word == 'Paper':
print("You won!")
wins += 1
elif ur_word == 'Scissors':
print("You lost!")
loss += 1
elif word == 'Paper':
if ur_word == 'Rock':
print("You lost")
loss += 1
elif ur_word == 'Scissors':
print("You won!")
wins += 1
elif word == 'Scissors':
if ur_word == 'Rock':
print("You won!")
wins += 1
elif ur_word == 'Paper':
print("You lost!")
loss += 1
else: <<<<---------///----------HERE------------///----
print("Please enter a valid input.")
if wins == 3:
print("\n\tYou won the entire game of three rounds!")
break
elif loss == 3:
print("\n\tYou lost the entire game of three rounds!")
break
**现在,我的问题是:为什么当我输入像“74n9wndwekf”这样的任意值时,选择的 else 语句不执行?
一个人告诉我,你不能在else
语句之后执行if
和elif
语句,而且你不能在break
语句之后执行你的代码。 我不明白他的意思,我不知道这些信息对你是否有任何价值。**
else
永远不会发生,因为您的elif
之一将始终为真。 word
将始终是Rock
、 Paper
或Scissors
之一,因此您永远不会碰到else
的。
一个简单的解决方法是重组if...elif
链以首先检查ur_word
。
go 的另一种方法是在执行任何其他操作之前验证输入,例如:
ur_word = input("Rock, Paper, Scissors..: ")
if ur_word not in {'Rock', 'Paper', 'Scissors', 'q'}:
print("Please enter a valid input.")
continue
在您的 if 语句中,您正在检查以下内容:
这里的问题是计算机的随机选择将始终是“Rock”、“Paper”或“Scissors”,因此前三个 if/elif 条件之一将满足,因此永远不会到达 else 块。
尝试设计您的 if 语句以首先检查用户输入而不是计算机的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.