首页 > 解决方案 > 如何在Python中循环时将数字添加到int

问题描述

所以我一般是编程新手,我正在尝试制作一个数字猜测系统,所以它会给你 7 次尝试,以及当数字被猜到时你最后尝试了多少次

已经尝试过这样做

    if c < z:
        print('Higher')
        print('Tries ' + str(count) + '/7')
        count += 1
        this()

但它没有用。一些建议将不胜感激。

代码:

count = 1
z = random.randint(1, 100)


def this():


    inpt = input('Enter a Number: ')
    c = int(inpt)

    if c >= 101:
        print('Number too high only 1-100')
        this()

    if c <= 0:
        print('Number too low only 1-100')
        this()

    if c > z:
        print('Lower')
        print('Tries ' + str(count) + '/7')
        this()

    if c < z:
        print('Higher')
        print('Tries ' + str(count) + '/7')
        this()

    if c == z:
        print('Success! You guessed the number')
        quit(0)


this()

if count == 7:
    print('You lose!')
    quit(1)

标签: python

解决方案


IMO,您应该循环调用该函数。这将是更好的风格。您只需要处理输入 > 100 和 < 1 的情况

import random 

count = 1
z = random.randint(1, 100)


def this():

    inpt = input('Enter a Number: ')
    c = int(inpt)

    if c >= 101:
        print('Number too high only 1-100')

    if c <= 0:
        print('Number too low only 1-100')

    if c > z:
        print('Lower')
        print('Tries ' + str(count) + '/7')

    if c < z:
        print('Higher')
        print('Tries ' + str(count) + '/7')

    if c == z:
        print('Success! You guessed the number')
        quit(0)



while count <= 7:
    this()
    count = count+1

print('You lose!')
quit(1)

推荐阅读