ini*_*ick 4 python if-statement xrange
新的编程,即时学习,这对你来说可能是一个非常简单的问题.
import random
def run_stair_yes():
print "\nRunning in stairs is very dangerous!"
print "Statistique shows that you have 70% chance of falling"
print "\nroll the dice!"
for i in xrange(1):
print random.randint(1, 100)
if i <= 70 :
print "\nWell, gravity is a bitch. You fell and die."
elif i >= 71 :
athlethic()
else:
print "im boned!"
exit(0)
Run Code Online (Sandbox Code Playgroud)
我的问题是,无论生成什么数字,它总是给我相同的"重力是一个婊子.你堕落而死".
我哪里出错了?
你从来没有真正把我设置为 random.randint()
你说
for i in xrange(1):
Run Code Online (Sandbox Code Playgroud)
我在0你迭代的时候取值,xrange(1)然后你只打印出结果random.randint(1, 100),而不是把它分配给我.
试试这个
i = random.randint(1, 100)
Run Code Online (Sandbox Code Playgroud)
除了jamylak的建议,还有一些改进代码的一般指示:
print语句可以更好地编写多行提示.这样你只需要写print一次,而你不需要所有那些额外的换行符(\n)例:
print """
Running on the stairs is dangerous!
You have a 70% chance to fall.
Run on the stairs anyway?
"""
Run Code Online (Sandbox Code Playgroud)
您的概率计算使用[1-100]范围内的随机整数,但使用浮点数可能更自然.(无论哪种方式都有效.)
您无需检查号码是否正确<= 70,然后检查是否是>= 71.根据定义(对于整数!),只有其中一个条件成立,因此您实际上不需要检查它们.
例:
random_value = random.random() # random number in range [0.0,1.0)
if random_value < 0.7:
pass #something happens 70% of the time
else:
pass #something happens the other 30% of the time
Run Code Online (Sandbox Code Playgroud)
或者更紧凑:
if (random.random() < 0.7):
pass #something happens 70% of the time
else:
pass #something happens 30% of the time
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7140 次 |
| 最近记录: |