[英]How do i make use if?
我對編程很陌生,一直在玩石頭,紙,剪刀的游戲。 除了最后一部分( if
部分),其他所有功能均有效。
x = ("rock")
y = ("paper")
z = ("scissors")
print(x)
print(y)
print(z)
choices1 = (x, y, z)
choices2 = (x, y, z)
import random
print("player 1 chose...")
print(random.choice(choices1))
print("player 2 chose...")
print(random.choice(choices2))
if random.choice(choices1) = rock and random.choice(choices2) = scissors:
print("player 1 wins")
每當我嘗試執行腳本時,它都會說:
File "<string>", line 14
if random.choice(choices1) = rock and random.choice(choices2) = scissors:
^
SyntaxError: invalid syntax
您需要==
否=
:
if random.choice(choices1) == "rock" and random.choice(choices2) == "scissors":
print("player 1 wins")
其次,由於尚未聲明任何名為rock
和scissors
變量,因此必須在它們周圍使用引號使它們成為字符串,否則會出現NameError
。
或使用指向字符串“ rock”和“ scissors”的變量x
, z
:
if random.choice(choices1) == x and random.choice(choices2) == z:
print("player 1 wins")
==
用於檢查相等性,而=
用於分配。
>>> "foo" == "bar"
False
>>> "foo" == "foo"
True
由於在python的if
語句中不允許賦值,因此您得到了SyntaxError
。
相等的比較運算符為==
not =
。
=
用於將項目分配給對象,例如var = 5
。 因此, SyntaxError
。
標准比較運算符的編寫方式與C相同: <
(小於), >
(大於), ==
(等於), <=
(小於或等於), >=
(大於或等於)和!=
(不等於)。
此外,未定義rock
,因此您還將獲得NameError
。 我假設它應該是一個字符串,所以使其成為"rock"
。
比較運算符必須是==而不是=。 查看以下詳細信息: http : //www.tutorialspoint.com/python/python_basic_operators.htm
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.