Итак, я новичок в программировании в целом, и я пытаюсь создать систему угадывания чисел, чтобы она давала вам 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)
После определения вашей функции добавьте цикл while. "пока количество < 7". Сделайте отступ для остальных четырех пробелов, добавьте count = count + 1 к c<>z, и все заработает.
Вам нужно сделать count и z глобальными переменными, чтобы их можно было использовать в this(). Затем сделайте (If c < z) и (If c > z) увеличение счетчика на 1. Отсчет должен начинаться с 0.
Затем, когда число угадано, вам нужно напечатать количество попыток, напечатав конкатенацию ('У вас ушло' + count (количество попыток) + 'пытается угадать число!'). Вам нужно объединить строковое значение count, потому что count — это целое число, а целые числа не могут быть объединены со строками.
Код:
global count #MAKE count GLOBAL
count = 0
global z #MAKE z GLOBAL
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')
count += 1 #INCREASE count BY 1
this()
if c < z:
print('Higher')
print('Tries ' + str(count) + '/7')
count += 1 #INCREASE count BY 1
this()
if c == z:
print('Success! You guessed the number')
print('It took you ' + str(count) + ' tries to guess the number!')
#print 'It took you X tries to guess the number!' where X is the number of tries it took them to guess the number
quit(0)
this()
if count == 7:
print('You lose!')
quit(1)
ИМО, вы должны вызывать функцию в цикле. Это был бы лучший стиль здесь. Вам просто нужно обработать случай для входов> 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)
Если вы не хотите делать это, снова вызывая одно и то же имя метода и буквально просто нуждаетесь в том, чтобы цикл выполнялся определенное количество раз, вы можете сделать что-то вроде этого:
count = 0
guesses_allowed = 7
number_to_guess = 5
while (count < 7):
guess = input("Guess a number:")
if guess >= 101:
print('Number too high only 1-100')
elif guess <= 0:
print('Number too low only 1-100')
elif guess > number_to_guess:
print('Lower')
count += 1
print('Tries ' + str(count) + '/7')
elif guess < number_to_guess:
print('Higher')
count += 1
print('Tries ' + str(count) + '/7')
if count >= guesses_allowed:
print('You guessed too many times')
quit(0)
if guess == number_to_guess:
print('Success! You guessed the number')
quit(0)
А затем при необходимости измените переменную number_to_guess
или guesses_allowed
. Я еще не запускал этот код локально, так как я только что набрал его, но он должен помочь вам в этом.
во втором коде нет цикла.