PYTHON:简单的随机生成驱动if/els

2024-05-23 21:42:01 发布

您现在位置:Python中文网/ 问答频道 /正文

新的程序,我学习和这里可能是一个非常简单的问题,你们家伙。

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)

我的问题是,不管生成多少,它总是给我同样的“重力是个婊子”。你摔了一跤就死了”。

我哪里做错了?


Tags: runinimport程序isdefrandomyes
3条回答

你从未真正地将i设置为random.randint()

你说

for i in xrange(1):

在这里,当你遍历xrange(1)时,我取0的值,然后你只打印random.randint(1, 100)的结果,而不将其分配给i

试试这个

i = random.randint(1, 100)

除了jamylak的建议之外,还有一些改进代码的通用指针:

  • 多行提示最好使用三重引号字符串语法而不是多个print语句编写。这样你只需要写一次print,而不需要所有额外的换行符(\n

示例:

print """
Running on the stairs is dangerous!

You have a 70% chance to fall.

Run on the stairs anyway?
"""
  • 概率计算使用[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

或者更紧凑:

if (random.random() < 0.7):
    pass #something happens 70% of the time
else:
    pass #something happens 30% of the time

如果你真的给i分配了一些东西。。。

i = random.randint(1, 100)

还有一件事:永远不会执行else部分。每个整数都是<;=70或>;=71,因此永远不会到达else

相关问题 更多 >