-5

我希望某人有 7/10 的机会成功完成一项动作,例如爬墙。我无法让一组整数与 random.randint 一起使用,所以我不得不重新输入 10 次,如下所示:

import random

print('You try to climb the wall.')

climbResult = random.randint(1,10)


elif climbResult == (1):
    print('You were successful.')

elif climbResult == (2):
    print('You were successful.')

elif climbResult == (3):
    print('You were successful.')

elif climbResult == (4):
    print('You were successful.')

elif climbResult == (5):
    print('You were successful.')

elif climbResult == (6):
    print('You were successful.')

elif climbResult == (7):
    print('You were successful.')

elif climbResult == (8):
    print('You were unsuccessful.')

elif climbResult == (9):
    print('You were unsuccessful.')

elif climbResult == (10):
    print('You were unsuccessful.')

一遍又一遍地添加数字很痛苦,而这只有 10 个部分。我只想做两个 if 语句,一个有 70% 的机会打印你成功,另一个有 30% 的机会打印你不成功。

很抱歉,这是一个非常简单的问题,我问的方式可能很难理解。我只学了两个星期的 Python,我很难用英语问它,因为它不是我的第一语言。

4

5 回答 5

12
if climbResult <= 7:
     print('You were successful.')
else:
     print('You were unsuccessful.')
于 2013-06-04T20:51:06.540 回答
6

对于一个稍微有趣和不同的看待问题的方式:

random.choice(['You were successful']*7 + ['You were unsuccessful']*3)

如果你不计算进口,它也是一个 1 班轮......这必须考虑到一些东西......

于 2013-06-04T20:54:29.330 回答
3

既然您说您只关心 70% 的案例中的“成功”和其他所有情况的“不成功”,那么您也可以使用随机数。

# import random

def answer():
  if random.uniform(0, 10) < 7:
    return 'successful'
  else:
    return 'unsuccessful'
于 2013-06-04T20:54:58.627 回答
0
if climbResult <= 7: 
    print("Success")
else: 
    print ("Fail")
于 2013-06-04T20:51:38.177 回答
-1
return climbResult in range(1,8)    
于 2013-06-04T21:43:44.753 回答