需要用def语句编写代码吗? &安培;不能使用全局变量

时间:2013-02-21 19:37:13

标签: python function

我遇到了def语句的问题。我似乎无法理解他们。我必须为类似赌场老虎机的类制作代码。我有一个代码可以做到,但不是我需要的def语句。我也不能使用全局变量。有人能指出我正确的方向吗?

import random

money=''

b1=''

def greeting():

        print("Project 2")

def myMoney(money=0): 

    money=int(input("Let's play the slots!\nHow much money do you want to start with?\nEnter the starting number of dollars."))
    return money
    while True:
        if money>0:
            break
        if money==0:
            break


def getBet(bet=''):

        b1=int(input("How much do you want to bet?"))
        while True:
            if bet==0:
                break
            while True:
                if bet>money:
                    print("ERROR: You don't have that much left.")
                    print()
                    b1=int(input("How much do you want to bet?"))
                if bet<money:
                    input("Press enter to pull the slot machine handle!")
                    break
        return money
        return bet

    num1=random.randint(1, 5)
    num2=random.randint(1, 5)
    num3=random.randint(1, 5)
    print("/---+---+---\ ")
    print("|-"+str(num1)+"-|-"+str(num2)+"-|-"+str(num3)+"-|")
    print("\---+---+---/")

greeting()

myMoney()

getBet()

1 个答案:

答案 0 :(得分:0)

在“def语句”(函数)中,您可以根据需要定义变量。它们不会是全球性的

def A_function():
    money = 0
    #do all sorts of things

基本上相当于:

money=''
def Another_function(money=0):
    #do all sorts of things

这就是你拥有的。看看我在函数中定义变量'money'的第一个函数怎么样?在第二个中,您将变量重新定义为您需要的变量。最终效果是相同的,但是,首选是首选,因为它有助于跟踪所有变量,并且不会全局定义变量。在你的代码中,在顶部定义'b1'和'money'是不必要的,因为你已经从位于每个函数中的输入语句中获得了一个值。