骰子滚动模拟器在Python中

时间:2017-05-16 17:58:51

标签: python-3.x simulator dice

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

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

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

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

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

6 个答案:

答案 0 :(得分:3)

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

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

    代码版本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)即可完成工作。

答案 1 :(得分: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() 

要了解更多,您可以参考以下内容:https://community.progress.com/code_share_group/f/169/t/35797

答案 2 :(得分:-1)

import random
min = 1
max = 6

roll_again = "yes"
 roll_again = raw_input

while roll_again == "yes" or roll_again == "y":
    print ("Rolling the dices...")
    print ("The values are....")
    print (random.randint(min, max))
    print (random.randint(min, max))

    roll_again = raw_input("Roll the dices again?")

答案 3 :(得分:-1)

这是for 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

答案 4 :(得分:-1)

I just started learning Python three days ago, but this is what I came up with for Python 3, and it works:

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!')

答案 5 :(得分:-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')