代码Python入门(八、函数)(转p3)

这篇博客介绍了Python中的函数定义与使用,包括带有默认参数的函数、读取和修改全局变量的方法,以及如何通过函数重载显示游戏说明。
摘要由CSDN通过智能技术生成
#!/usr/bin/env python
# -*- coding: UTF-8 -*-


def instructions():  # 定义函数
    """Display game instructions."""
    print(
        """
        Welcome to the greatest intellectual challenge of all tome : Tic-Tac-Toe.
         This will be a showdown between your human brain and my silicon processor.
         You will make your move known by entering a number, 0 - 8. The number will 
         correspond to the board position as illustrated:
                      0 | 1 | 2
                      ---------
                      3 | 4 | 5
                      ---------
                      6 | 7 | 8
         Prepare yourself, human. The ultimate battle is about to begin. \n 
        """
    )


def instructions(spp):     # 可重载
    print(spp)


def birthday(name, age = 0, sex = "man"):  # 某个参数设置了默认值时,其后所有参数都需要设置默认值
    print(name, age, sex)


def read_global():
    print("From inside the local scope of read_global(), value is:", value)     # 函数内部读取全局变量


def shadow_global():
    value = -10         # 函数内部屏蔽全局变量
    print("From inside the local scope of shadow_global(), value is:", value)


def change_global():
    global value      # 获取全局变量value的完全访问权
    value = -10       # 函数内部修改全局变量
    print("From inside the local scope of change_global(), value is:", value)


# 主程序
print("Here are the instructions to the Tic-Tac-Toe game:")
instructions()
print("Here they are again:")
instructions()
print("You probably understand the game by now.")

input("\n\nPress the enter key to exit.")

# 关键字实参可以不关心形参的顺序
birthday(age = 15, name = "Tom")

value = 10   # 全局变量
print("In the global scope, value has been set to :", value, "\n")

read_global()
print("Back in the global scope, value is still :", value, "\n")

shadow_global()
print("Back in the global scope, value is still:", value, "\n")

change_global()
print("Back in the global scope, vlaue is still:", value, "\n")


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值