[英]How to use the Random Function in a if statement, in Python 3?
Here is my code for a simple coin toss program, I am new to python. 这是我的一个简单的抛硬币程序的代码,我是python的新手。
I am not getting any Errors, but the program will not print my "if" statements, it skips straight from input too input. 我没有收到任何错误,但是程序不会打印我的“ if”语句,它会直接从输入中跳过输入。
I am sure there is more intuitve ways to generate a coin toss program, this was just the idea I had. 我确信还有更多直观的方法来产生抛硬币程序,这只是我的想法。
Any thoughts? 有什么想法吗?
import random
print('--HEADS or TAILS--')
print('Welcome Players!')
print('[H=_Heads][T=_Tails]')
print('Please ENTER {H_or_T}')
input("Heads or Tails:")
rand = (random.randint(1,2))
if rand=='1':
print("Heads Wins!")
elif rand=='2':
print("Tails Wins!")
input("Press ENTER to Exit")
random.randint(1,2)
returns the value of integer type. random.randint(1,2)
返回整数类型的值。 random.randint(a,b)
document clearly says that it: random.randint(a,b)
文件明确指出:
Returns a random integer N such that a <= N <= b.
返回一个随机整数N ,使得a <= N <= b。
But in your if
you are comparing it against the value of string type, and hence your conditional statements are failing. 但是,
if
您将它与字符串类型的值进行比较,则条件语句将失败。
You need to modify your conditional statements as: 您需要将条件语句修改为:
# v no quotes here
if rand == 1:
print("Heads Wins!")
# v no quotes here
elif rand == 2 : # Better to simply use `else`
print("Tails Wins!")
Like the name randint
already suggests, random.randint(1,2)
returns an integer between 1 and 2 (both inclusive). 就像
randint
已经暗示的那样, random.randint(1,2)
返回一个介于1和2之间(包括两端) 的整数 。
If you perform 1 == '1'
you compare an int
with a str
, which is always False
. 如果执行
1 == '1'
则将一个int
与一个str
比较 ,这始终为False
。 You should compare with 1
instead of '1
'. 您应该用
1
而不是'1
'进行比较。
You can also drop the elif
, and use else
, since we know that it will be 2
if it is not 1
, so: 您也可以删除
elif
,并使用else
,因为我们知道这将是2
如果不是1
,那么:
input("Heads or Tails:")
rand = random.randint(1,2) # no brackets necessary
if rand ==
1: # use an integer, instead of a string:
print("Heads Wins!")
else: # else instead of elif
print("Tails Wins!")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.