在python中使用全局变量处理默认值

时间:2014-10-02 21:13:29

标签: python

我正在尝试以下代码:

import simplegui
import random
import math
def new_game():
   global secret_number
   global low
   global high
   global n
   print "New game. Range is from" ,low ,"-",high
   secret_number=random.randrange(low,high)
   n=math.ceil(math.log((high-low+1),2))
   print "no of guesses",n
   print " "

def new_game1():
   global secret_number
   print "New game. Range is from 0-100"
   print " "
   secret_number=random.randrange(0,100)    


# define event handlers for control panel
def range100():
    global low,high
    low=0
    high=100
    new_game()

def range1000():
    global low
    global high
    low=0
    high=1000
    new_game()


def input_guess(guess):
    global secret_number
    global n
    g=int(guess)
    print "Guess was",g
    --n
    print "no of guesses left",n
    if(g>secret_number):
        print "Lower"
    elif(g<secret_number):
        print "Higher"
    else:
        print "Equal"


frame = simplegui.create_frame('Testing', 200, 200)
button1 = frame.add_button('Range is(0,100)', range100,200)
button2 = frame.add_button('Range is(0,1000)', range1000,200)
inp = frame.add_input('Enter a guess', input_guess,200)
frame.start()
new_game1() 

我上面代码的问题是我想使用一个newgame()fn,默认值为0,高为100。现在我把这个函数分成了newgame1(),它正在对默认值进行计算

如何纠正这个问题?请帮忙

1 个答案:

答案 0 :(得分:1)

您可以将它们作为函数参数发送,而不是将限制作为全局变量。您可以将默认值设置为某些值,并根据需要覆盖它们。 new_game()可能会变成:

def new_game( low = 0, high = 100 ):
    global secret_number, n    # Maybe these can be function arguments as well?
    print "New game. Range is from" ,low ,"-",high
    secret_number=random.randrange(low,high)
    n=math.ceil(math.log((high-low+1),2))
    print "no of guesses",n
    print " "

您的range函数将变为:

def range100():
    new_game() # high & low take default values of 0,100

def range1000():
    new_game(high = 1000) # high is now 1000

# My own function
def rangeMinus1000():
    new_game(low = -100, high = 1000) # low is -100 & high is 1000