Python随机数游戏

xxb16uws  于 2022-12-20  发布在  Python
关注(0)|答案(5)|浏览(254)

我正试着写一个程序,它能产生一个1到100之间的随机数,然后让用户猜一猜,如果猜对了,它就会告诉用户,如果猜错了,它就会告诉用户。
我目前掌握的情况是:

import random

def playGame2():
    number = random.randint(1,100)
    guess = input("I'm thinking of a number between 1 and 100. Guess what it is: ")
    if str(number) == guess:
        print("That is correct!")
    else:
        print("Nope, I was thinking of" +str(number))

当我运行程序时,它只给我<function playGame2 at 0x0000000002D3D2F0>。它为什么要这样做?

0dxa2lsx

0dxa2lsx1#

你必须执行这个函数,你的输出暗示你做了类似于

print(playGame2)

代替

playGame2()
bnlyeluc

bnlyeluc2#

def playGame2():
    number = random.randrange(1,100)
    guess = input("I'm thinking of a number between 1 and 100. Guess what it is: ")
    if str(number) == guess:
        print("That is correct!")
    else:
        print("Nope, I was thinking of %s" % number)

试试看。我刚刚运行的很好。要在空闲状态下或者你可以访问它的地方使用playGame2()。

dfty9e19

dfty9e193#

你需要告诉python这有一个main函数,尝试在代码的末尾包含这个:

if __name__ == "__main__":
    playGame2()

把这个放在开头

# -*- coding: UTF-8 -*-

位于代码顶部,有关指定所使用Python文件编码的方法,请参见http://www.python.org/dev/peps/pep-0263/
希望它能帮助你。

yk9xbfzb

yk9xbfzb4#

import random

guess=99 

count=0  

no = random.randint(1,100)  

print("Welcome to the guessing game!")


while guess != no :  
    guess = int(input("Guess a number: ")) 

    if guess < no : 
        print("Higher") 
        count+=1  

    if guess > no :
        print("Lower") 
        count+=1  

    if (guess==no):
        print("You win, the number was indeed:",no)
        print("It took you a total of:",count,"tries")
50few1ms

50few1ms5#

import random #import modules
import time

x = random.randint(1,100)#This is the random number

while True:
    try:
        while True: #Make a loop
            y = input('Enter a number: ')
            if int(y) == x:
                print('You won!')
                time.sleep(5)
                exit()
            if int(y) > x:
                print('The input is too high')
                continue #restart the loop
            if int(y) < x:
                print('The input is too low')
                continue
    except:
        print('Only numbers')
        continue

相关问题