骰子滚动模拟器在Python中

问题描述 投票:-2回答:6

我想写一个掷骰子的程序。现在这就是我所拥有的:

import random
print("You rolled",random.randint(1,6))

而且我也希望能够做到这样的事情:

print("Do you want to roll again? Y/N")

然后,如果我按Y它再次滚动,如果我按N我退出应用程序。提前致谢!

python-3.x simulator dice
6个回答
3
投票

让我们来看看这个过程:您已经知道生成随机数所需的内容。

  1. import random(或者你可以更具体,并说from random import randint,因为我们在这个程序中只需要randint
  2. 正如你已经说过的那样; print("You rolled",random.randint(1,6))“滚动骰子”。但它只做一次,所以你需要一个循环来重复它。一个while loop正在打电话给我们。
  3. 您需要检查用户是否输入Y。你可以简单地用"Y" in input()来做。

代码版本1。

import random
repeat = True
while repeat:
    print("You rolled",random.randint(1,6))
    print("Do you want to roll again? Y/N")
    repeat = "Y" in input()

代码版本1.1(好一点)

from random import randint
repeat = True
while repeat:
    print("You rolled",randint(1,6))
    print("Do you want to roll again?")
    repeat = ("y" or "yes") in input().lower()

在此代码中,用户可以自由使用yEsyyesYES等字符串来继续循环。

现在请记住,在版本1.1中,因为我使用from random import randint而不是import random,我不需要说random.randint(1, 6)而只需要radint(1,6)就可以完成这项工作。


0
投票
import random
def dice_simulate():
    number = random.randint(1,6)
    print(number)
    while(1):
       flag = str(input("Do you want to dice it up again:Enter 1 and if not enter    0"))
       if flag == '1':
         number = random.randint(1,6)
         print(number)
      else:
         print("ending the game")
         return

dice_simulate() 

为了更多的理解,你可以参考:qazxsw poi



-1
投票

我刚刚开始学习Python三天前,但这是我为Python 3提出的,它的工作原理如下:

import random
repeat="Y"
while repeat == "Y":
   print("Rolling the dice")
   print(random.randint(1,6))

repeat =input("Do you wanna roll again Y/N?")
if repeat=="Y":
    continue

-1
投票
import random

question = input('Would you like to roll the dice [y/n]?\n')

while question != 'n':
    if question == 'y':
        die1 = random.randint(1, 6)
        die2 = random.randint(1, 6)
        print(die1, die2)
        question = input('Would you like to roll the dice [y/n]?\n')
    else:
        print('Invalid response. Please type "y" or "n".')
        question = input('Would you like to roll the dice [y/n]?\n')        

print('Good-bye!')

-1
投票
from random import randint
ques = input('Do you want to dice Y/N : ')

while ques.upper() == 'Y':
    print(f'your number is {randint(1,6)}')
    ques = input('Do you want to roll again !!')
else:
    print('Thank you For Playing')
© www.soinside.com 2019 - 2024. All rights reserved.