Python编程快速上手-让繁琐工作自动化 — 读书与代码笔记

chapter3

# -*- coding:utf-8 -*-
# @FileName     :chapter3_Function.py
# @Time         :2020/8/13 15:12
# @Author       :Wu Hongyi
# @Copyright    :Wu Hongyi
# Function description:
'''
本文件为Python编程快速上手-让繁琐工作自动化一书的第三章示例练习代码
'''
# @version      :Version1.0
# Modification description:
'''

'''

# 设计函数可以减少重复工作,增加程序可移植性
# helloFunc.py
def hello():
    print('Howdy!')
    print('Howdy!!!')
    print('Hello there.')

hello()
hello()
hello()

# helloFunc2.py
def hello2(name):
    print('Hello ' + name)

hello2('Alice')
hello2('Bob')

# 关于函数的返回值和return语句
# magic8Ball.py
import random

def getAnswer(answerNumber):
    if answerNumber == 1:
        return 'It is certain'
    elif answerNumber == 2:
        return 'It is decidedly so'
    elif answerNumber == 3:
        return 'Yes'
    elif answerNumber == 4:
        return 'Reply hazy try again'
    elif answerNumber == 5:
        return 'Ask again later'
    elif answerNumber == 6:
        return 'Concentrate and ask again'
    elif answerNumber == 7:
        return 'My reply is no'
    elif answerNumber == 8:
        return 'Outlook not so good'
    elif answerNumber == 9:
        return 'Very doubtful'

r = random.randint(1, 9)    # 生成随机数范围包括9
# print(r)
fortune = getAnswer(r)
print(fortune)
# 以上几行代码可缩写为一句:
# print(getAnswer(random.randint(1,9)))

# None 值:表示没有值,首字母必须大写,类似于其他编程语言中的null、nil或undefined
# 如果希望变量中存储的东西不会与一个真正的值混淆,这个没有值的值就可能有用
# 如print()的返回值就是None,其在屏幕上显示文本,但不需要返回任何值,因此设计其返回值为None
spam = print('Hello!')
None == spam
# 在幕后,对于所有没有return语句的函数定义,Python都会在末尾加上return None
# return语句不带值时也返回None

# 关键字参数和print()函数
# print()函数有可选变元end和sep,分别指定在参数末尾打印什么和在参数之间打印什么来隔开它们
print('Hello')
print("World")              # 不指定end参数时默认为换行

print('Hello', end = '')    # 指定end参数为空字符串(非空格)
print('World')

# 向print()传入多个字符串值,该函数自动以一个空格分隔他们
print('cats', 'dogs', 'mice')

# 传入sep关键字参数,替换默认的分隔字符串
print('Cats', 'Dogs', 'Mice', sep = ',')

# 在Python中让局部变量和全局变量同名是完全合法的
def spam():
    eggs = 'spam local'
    print(eggs)     # print 'spam local'

def bacon():
    eggs = 'bacon local'
    print(eggs)     # prints 'bacon local'
    spam()
    print(eggs)     # prints 'bacon local'

eggs = 'global'
bacon()
print(eggs)         # prints 'global'

# global语句
# 需要在一个函数内修改全局变量,就使用global语句
def spam():
    global eggs
    eggs = 'spam'

eggs = 'global'
spam()
print(eggs)
# 有4条法则,来区分一个变量是处于局部作用域还是全局作用域:
# 1.如果变量在全局作用域中使用(即在所有函数之外),它就总是全局变量。
# 2.如果在一个函数中,有针对该变量的global语句,它就是全局变量。
# 3.否则,如果该变量用于函数中的赋值语句,它就是局部变量。
# 4.但是,如果该变量没有用在赋值语句中,它就是全局变量。

# 理解上述法则的例子
def spam():
    global eggs
    eggs = 'spam'       # this is the global

def bacon():
    eggs = 'bacon'      # this is a local

def ham():
    print(eggs)         # this is the global 此处的eggs用的是全局变量

eggs = 42               # this is the global
spam()
ham()
print(eggs)

# 如果想在一个函数中修改全局变量中储存的值,就必须对该变量使用global语句
# 在一个函数中,如果试图在局部变量赋值之前就使用全局变量,像如下程序一下,会报错
# sameName4.py
def spam():
    print(eggs)     # Error!
    eggs = 'spam local'
eggs = 'global'
spam()
# 报错原因:Python看到spam()函数中有针对eggs的赋值语句,因此认为eggs是局部变量
# 但是因为print(eggs)的执行在eggs赋值之前,局部变量eggs并不存在,Python不会退回到使用全局eggs变量

# 异常处理   在程序检测到错误后,仍能处理他们,然后继续运行
# ZeroDivide.py
def spam(divideBy):
    return 42 / divideBy

print(spam(2))
print(spam(12))
print(spam(0))      # 会产生除0错误
print(spam(1))

# 处理该错误
def spam(divideBy):
    try:
        return 42 / divideBy
    except ZeroDivisionError:
        print('Error: Invalid arguments.')

print(spam(2))
print(spam(12))
print(spam(0))      # 能检测到除0错误
print(spam(1))

# 在函数调用中的try语句块中,发生的所有错误都会被捕捉:
def spam(divideBy):
    return 42 / divideBy

try:
    print(spam(2))
    print(spam(12))
    print(spam(0))
    print(spam(1))
except ZeroDivisionError:
    print('Error: Invalid arguments.')
# 该程序中print(spam(1))从未被执行是因为,一旦执行到跳转except子句的代码
# 就不会回到try子句,它会继续照常向下执行



## 一个小程序:猜数字
# guessTheNumber.py
# This is a guess the number game.
import random
secretNumber = random.randint(1, 20)
print('I am thinking of a number between 1 and 20.')

# Ask the player to guess 6 times.
for guessesTaken in range(1,7):
    print("Take a guess.")
    guess = int(input())

    if guess < secretNumber:
        print("Your guess is too low.")
    elif guess > secretNumber:
        print("Your guess is too high.")
    else:
        break           # This condition is the correct guess!
if guess == secretNumber:
    print("Good job! You guessed my number in " + str(guessesTaken) + ' guess!')
else:
    print("Nope. The number I was thinking of was " + str(secretNumber))

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值