我希望有一个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,而且我用英语问它,因为它不是我的第一语言。
答案 0 :(得分:12)
if climbResult <= 7:
print('You were successful.')
else:
print('You were unsuccessful.')
答案 1 :(得分:6)
以一种稍微有趣和不同的方式来查看问题:
random.choice(['You were successful']*7 + ['You were unsuccessful']*3)
如果你不计算进口数量,这也是一个单行...这是必须的... ...
答案 2 :(得分:3)
因为你说在70%的情况下你只关心这个说法“成功” 并且“不成功”的其他一切你也可以使用随机数。
# import random
def answer():
if random.uniform(0, 10) < 7:
return 'successful'
else:
return 'unsuccessful'
答案 3 :(得分:0)
if climbResult <= 7:
print("Success")
else:
print ("Fail")
答案 4 :(得分:-1)
return climbResult in range(1,8)