你如何创建一个随机范围,但排除一个特定的数字? [英] How do you create a random range, but exclude a specific number?

查看:14
本文介绍了你如何创建一个随机范围,但排除一个特定的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

while True:
    if var_p1 != "0":
        break
    else:
        import random
        var_p1 = random.randint(-5,5)

我希望循环重复直到 var_p1 不等于零.但是,我总是得到零.我做错了什么?

I want the loop to repeat until var_p1 equals anything but zero. However, I get zero all the time. What am I doing wrong?

推荐答案

回答标题中的问题,而不是真正的问题(由 Daniel Roseman 回答):

Answering the question in the title, not the real problem (which was answered by Daniel Roseman):

如何创建随机范围,但排除特定数字?

使用random.choice:

import random
allowed_values = list(range(-5, 5+1))
allowed_values.remove(0)

# can be anything in {-5, ..., 5}  {0}:
random_value = random.choice(allowed_values)  

这篇关于你如何创建一个随机范围,但排除一个特定的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆