四角投掷猜谜游戏Python

2024-05-17 00:05:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我想让这个工作,但由于某些原因,我不能让尾部工作,它一直显示1。另外请注意,我在python还是新手。在

我还想做个循环。假设他们没有得到他们猜测的数字。所以,如果他们说不(游戏又开始了)或是(这会让他们感谢玩游戏)

这就是我目前所拥有的。在

import random

print 'Welcome to Heads or Tails Guessing Game'
print ''
print 'Lets say I toss a Quater up in the air. What are the chances it will come up heads or even tails every time split even? 5 times or even 5000 times. Choose an ejucated guess.'
raw_input ('What would your number be? ')
tossQuater, itsHeads, itsTails = 1,1,1
while tossQuater < 5000:
    if random.randint(1,500) == 1:
        itsHeads = itsHeads + 1
        itstails = itsTails + 1
    tossQuater = tossQuater + 1

    if tossQuater == 1300:
        print 'First 1,500 tosses. Heads will come up ' + str(itsHeads) + ' times.' ' But for Tails it came up ' + str(itsTails)+ ' times.'
    if tossQuater == 1900:
        print 'Second 2,000 tosses. Heads will come up ' + str(itsHeads) + ' times damm!.' ' But for Tails it came up ' + str(itsTails)+ ' times.'
    if tossQuater == 3050:
        print 'Third and final 1,500 tosses. Heads will come up ' + str(itsHeads) + ' times...' ' But for Tails it came up ' + str(itsTails)+ ' times...'

print ''
print 'Out of 5 times or even 5000 times. Well the number of heads showed out to be.' + str(itsHeads) + ' times! ' ' But from Tails it showed ' + str(itsTails) + ' times..'
raw_input ('\n\nDid the number you choose was the right one?')

Tags: ortheitwillevenprintupheads
3条回答

我重新编写了一些您的代码,因为我不确定您在中间部分要做什么。下面的内容将持续循环,直到用户声明他们不想继续播放。在

我已经做了一个函数来玩游戏和掷硬币,随时可以问你是否有任何关于函数或其他的问题

 import random


def toss(flips):
    heads=0;tails=0
    for i in range(0,flips):
        if random.random()>0.5:
            heads+=1
    return heads

def guessing_game():
    print 'Welcome to Heads or Tails Guessing Game'
    print ''
    print '''Lets say I toss a Quater up in the air 5000 imes.
            How many times will it come up heads?
            5 times or even 5000 times. Choose an educated guess.'''
    guess = raw_input ('What would your number be? ')

    ## compare the guess and the answer
    heads=toss(5000)
    print 'You guessed '+str(guess)+' heads and the actual answer was '+str(heads)
    if heads==guess:
        print 'Well Done'
    else:
        print 'Better luck next time'

    return  raw_input ('\n\n Do you want to play again (y/n)?')


play='y'
while play<>'n':
    play= guessing_game()

您正在递增itstails变量并打印出itstails变量。因此,当打印出itsTails变量时,它显示1(因为它没有递增)。你的代码应该像

itsTails = itsTails+1

除此之外,你的逻辑似乎也有缺陷。我更喜欢以下代码:

^{pr2}$

我设定了一个条件,如果我得到1,那就是正面,如果我得到2,那就是反面。这是一个公平的假设,但不是一个完全现实的假设,因为即使是randint方法也会根据一些内置函数生成一个数字。在

对于你的一般性问题,你需要在逻辑上下功夫。为什么要同时给“它的头”和“它的尾”加1?在

另外,你需要看看“randint”是如何工作的。现在,你扔一个500面硬币,只检查它是否落在其中一个面上。在

还有更多的逻辑错误。你好像用了很多具体的数字。这有什么原因吗?请编辑其中的一些以使问题更清楚。在

相关问题 更多 >