我只是学习脚本python以我的方式通过MIT comp。科学开放课程,我有一个问题。我已经读过,将函数设置为全局函数内部是根本,至少是一些邪恶。虽然我确信我的问题有一个明显的答案,但我无法找到一种解决方法,即不在我的函数中设置全局变量' rand_guess'因为我需要来自主体的func中的值while while循环来执行进一步处理。我希望有人可能会形容一种更可接受的(pythonic,我认为是这个术语)我可以这样做的方式。这是我的剧本:
# Instruct the user to pick an arbitrary number from 1 to 100 and proceed to
# guess it correctly within 10 attempts. After each guess, the user must tell
# whether their number is higher than, lower than, or equal to your guess.
def rand_guess(l, h):
# print "l: " + str(l)
# print "h: " + str(h)
# global rand_num
rand_num = random.randint(l, h)
print(str(cntr) + '_2: ' + str(rand_num)) # debug
if rand_num != user_num:
if cntr < attempts:
print '\nMy guess of ' + str(rand_num) + ' is wrong.'
# global hi_lo
hi_lo = raw_input('So should my next guess be [H]igher or [L]ower? ')
print(str(cntr) + '_2: ' + hi_lo) # debug
else:
print '\nMy guess of ' + str(rand_num) + \
' is wrong, and I am out of guesses.\n'
exit()
else:
print '\nWoW! I can hardly believe it! My guess is correct: ' + \
str(user_num) + '\n'
exit()
return rand_num
return hi_lo
import random
attempts = 5
rand_num = 1
hi_lo = ''
lo = 1
hi = 100
user_num = int(raw_input('\nEnter a number between 1 to 100: '))
cntr = 1
while cntr < (attempts+1):
# first guess will be a random num between 1 to 100 so first lo_num must be
print(str(cntr) + '_1: ' + hi_lo) # debug
print(str(cntr) + '_1: ' + str(rand_num)) # debug
# 1
if cntr == 1:
rand_guess(lo, hi)
else:
# if user indicated to guess Higher with next guess
print(str(cntr) + '_3: ' + hi_lo) # debug
if hi_lo == 'H':
# then last number guessed +1 should be the lowest number guessed
# for all future guesses
print(str(cntr) + '_3: ' + str(rand_num)) # debug
if rand_num > lo:
lo = rand_num + 1
# user indicated to guess Lower with next guess
else:
# then last number guessed -1 should be the highest number guessed
# for all future guesses
if rand_num < hi:
hi = rand_num - 1
# func call with new lo-hi guess brackets
rand_guess(lo, hi)
cntr += 1
此外,我很感激阅读任何其他有关我可能正在制作的明显python格式化的建设性建议,因为我意识到python中的格式是最重要的。
修改
好的,所以我用global
语句替换return
语句,就像我最初尝试过的那样,但我希望返回的值似乎也会给我带来问题。我添加了一些额外的print
语句,试图帮助确定给定var在代码中不同点的值。以下是此脚本的输出,包括python调试详细信息:
Enter a number between 1 to 100: 50
1_1:
1_1: 1
1_2: 61
My guess of 61 is wrong.
So should my next guess be [H]igher or [L]ower? L
1_2: L
2_1:
2_1: 1
2_3:
Traceback (most recent call last):
File "ex_loops2.py", line 67, in <module>
rand_guess(lo, hi)
File "ex_loops2.py", line 10, in rand_guess
rand_num = random.randint(l, h)
File "/usr/lib/python2.7/random.py", line 241, in randint
return self.randrange(a, b+1)
File "/usr/lib/python2.7/random.py", line 217, in randrange
raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)
ValueError: empty range for randrange() (1,1, 0)
02:53 exercises $
print
&#39; 2_1的第一个空值:&#39;应该是&#39; H&#39; (在这种情况下)和值&#39; 1&#39;对于第二个`print&#39; &#39; 2_1:1&#39;在蟒蛇投掷错误之前,我预计会出现&#39; 2_1:61&#39; (再次针对此特定情况,返回了&#39; rand_num&#39;)。
再次,如果我只是global
这些变量,脚本按预期工作。我相信有人可以在这里指出我明显的疏忽或遗漏或错误的假设和使用python的return
陈述,因为我很难过。
虽然我可以看到下面贾斯汀的修改示例是如何更好地修改我想要在这里完成的事情,但我真的只需要知道它是什么我在做错{}试图{{1}这些特定的var值因此它们在分配它们的func之外可用(因为脚本基本上不起作用)。我认为,在我遇到问题的情况下,将会对python的这个基本方面产生最大的好处。
答案 0 :(得分:2)
这并不是你想要的,但它应该给出一些指示。
import sys
import random
def random_guess(low=1, high=100, attempts=10, hints=True):
"""Try to guess the random number.
Args:
low (int): Lowest number the value can be.
high (int): Highest number the value can be.
attempts (int): How many tries you get.
hints (bool): Change range boundaries.
"""
# Command line args come in as strings.
low = int(low)
high = int(high)
attempts = int(attempts)
hints = hints in [True, 1, "True", 'true', '1', 't', 'y', 'yes']
mynum = None
rand_num = random.randint(low, high)
for _ in range(attempts): # _ means the last command ... i isn't used. Skips the pylint warning
# Check input
if hints and mynum is not None:
if mynum < rand_num:
low = mynum + 1
print("Incorrect answer! Guess higher next time")
elif mynum > rand_num:
high = mynum - 1
print("Incorrect answer! Guess lower next time")
elif mynum is not None:
print("Incorrect answer!", end=" ")
# Ask the user for input (raw_input for python 2.x)
try:
mynum = int(input('Enter a number between '+str(low)+' to '+str(high)+': '))
if mynum == rand_num:
print("Congratulations, you win!")
return # skip the print you lose and exit the function
except ValueError:
print("That wasn't a number.")
# end for
print("Sorry you lose!")
# end main
# Use name to check if it is the main. This prevents the below code from executing on import.
# So another application and import the random_guess method and use it without actually running it.
if __name__ == "__main__":
commandline_args = sys.argv[1:] # First argument is usually the filename
random_guess(*commandline_args) # run the main method