0

我遇到了 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()
4

1 回答 1

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”,因为您已经从位于每个函数中的输入语句中获得了一个值。

于 2013-02-21T20:36:31.897 回答