Я просто изучаю python, и я написал это, но я хочу показать все догадки и, может быть, слишком ли они слишком высокие или низкие. Часть "responseList" - это то, где мне нужна помощь. Благодарю!
import random, easygui
secret = random.randint (1, 100)
guess = 0
tries = 0
easygui.msgbox ("""Guess the secret number.
It is from 1 to 99. You have five tries. Get Guessin' !""")
while guess != secret and tries < 5:
user_response = guess = easygui.integerbox ("C'mon...GUESS!!! ")
if not guess: break
if guess <= (secret + 5) and guess > secret:
easygui.msgbox(str(guess) + " is too HIGH... but you're close!")
if guess >= (secret - 5) and guess < secret:
easygui.msgbox(str(guess) + " is too LOW... but you're close!")
if guess < (secret - 5):
easygui.msgbox(str(guess) + " is too LOW... Guess higher")
if guess > (secret + 5):
easygui.msgbox (str(guess) + " is too HIGH...Guess lower")
tries = tries + 1
responseList = [user_response]
easygui.msgbox (responseList)
if guess == secret:
easygui.msgbox ("Darn! You got it!")
else:
easygui.msgbox ("Ha, Ha, Ha! No more guesses! To the firin' squad with ya!")
easygui.msgbox (str(secret) + " was the secret number")
Я предполагаю, что вы хотите, чтобы responseList содержал список всех ответов пользователей. Вы этого не писали. :)
Вам нужно будет установить responseList
для пустого списка в начале и append
к нему новый ответ.
responseList = [user_response]
просто устанавливает его в одноэлементный список каждый раз. Очевидно, вы получите список из одного элемента с последним ответом.
EasyGUI не является частью стандартного дистрибутива Python. Вы можете скачать его из SourceForge здесь http://easygui.sourceforge.net/. Он был установлен в установку Python (x, y) с первой попытки только с установкой setup.py. Чтобы ваш список вел себя так, как вы ожидаете, попробуйте эту версию:
import random, easygui
secret = random.randint (1, 100)
guess = 0
tries = 0
easygui.msgbox ("""Guess the secret number.
It is from 1 to 99. You have five tries. Get Guessin' !""")
responseList = []
while guess != secret and tries < 5:
user_response = guess = easygui.integerbox ("C'mon...GUESS!!! ")
if not guess: break
if guess <= (secret + 5) and guess > secret:
easygui.msgbox(str(guess) + " is too HIGH... but you're close!")
if guess >= (secret - 5) and guess < secret:
easygui.msgbox(str(guess) + " is too LOW... but you're close!")
if guess < (secret - 5):
easygui.msgbox(str(guess) + " is too LOW... Guess higher")
if guess > (secret + 5):
easygui.msgbox (str(guess) + " is too HIGH...Guess lower")
tries = tries + 1
responseList.append(user_response)
easygui.msgbox (",".join(["%d"%x for x in responseList]))
if guess == secret:
easygui.msgbox ("Darn! You got it!")
else:
easygui.msgbox ("Ha, Ha, Ha! No more guesses! To the firin' squad with ya!")
easygui.msgbox (str(secret) + " was the secret number")
инициализируйте responseList как список вне цикла, затем добавьте к нему каждый номер, когда вы идете. Я добавил некоторые запятые, чтобы отделить ваши номера в msgbox за бонус. ;)
Инициализировать список responseList
перед while guess != secret and tries < 5:
loop. В цикле вы можете append
кортежи в responseList
содержащий догадки, и если он был слишком высоким или низким (используйте переменную, скажем, where
, чтобы сохранить значение 'HIGH'
или 'LOW'
). Затем вне цикла while покажите отформатированные результаты с помощью easygui.msgbox
:
responseList = []
while guess...:
user_response = ...
if not...
if guess <=...
where = 'HIGH'
if guess >=...
where = 'LOW'
if guess <...
where = 'LOW'
if guess >...
where = 'HIGH'
tries...
responseList.append((guess, where))
responseString = ', '.join([ '%d (%s)' % (guess, where)
for guess, where in responseList])
easygui.msgbox(responseString)
эта строка с responseString
- это List List, которое вы можете прочитать или спросить здесь.
responseList
содержал, точно?