简体   繁体   English

如何使用随机数作为 if 语句的输入?

[英]How to use random numbers as an input for a if statement?

I am making a small text based adventure game, I am trying to use the random feature built into python to generate a number.我正在制作一个基于文本的小型冒险游戏,我正在尝试使用 python 中内置的随机功能来生成一个数字。 Based on the number it will allow you to continue or to die on the adventure.根据数字,它将允许您继续冒险或死亡。

N/A不适用

import random
i = random.randint(1, 2)
if i == '1':
  print("hello")
if i == '2':
  print("Hi")

N/A不适用

Your code works fine.您的代码工作正常。 Just remove the quotes:只需删除引号:

import random
i = random.randint(1, 2)
if i == 1:
  print("hello")
if i == 2:
  print("Hi")

If you have quotes around the 1 and 2, i will be evaluated as a string but you've defined it as an integer.如果您在 1 和 2 周围有引号,则 i 将被评估为字符串,但您已将其定义为 integer。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM