第三章 函数

# def hello():
#     print("Howdy!")
#     print("Hello,world!")
# hello()#定义函数并调用①

# def hello(name):
#     print("hello,"+name)
# hello("sun")
# hello("xu")含参数的函数的定义并调用②

# import random
# def getAnswer(answernumber):
#     if answernumber == 1:
#         return "It's certain"
#     elif answernumber == 2:
#         return "Yes"
# print(getAnswer(random.randint(1,3)))

# spam = print("Hello!")
# print(spam)#print函数的默认返回值为None⑥

# print("dog","cat","fish",sep=",")#sep可以将字符串按需要分隔开来,有双引号中的值来决定⑦
# print("dog",end="")#end可以将print函数不换行打印出来,并且可以在双引号中输入值来决定用什么将他们隔开,可以为空⑧
# print("cat")

# def spam():
#     eggs = 32337
# spam()
# print(eggs) #当程序执行在全局作用域中时,不存在局部作用域,所以不会有任何局部变量⑨

# def spam():
#     eggs = 99
#     bacon()
#     print(eggs)
#
# def bacon():
#     ham = 101
#     eggs = 0
#
# spam()
# #一个函数再被调用结束后他所在的局部作用域就已经被销毁了,他所包含的变量的值也就被销毁了,即一个函数的局部变量完全与其他函数中的局部变量分隔开来⑩

# def spam():
#     print(eggs)
# eggs = 43
# spam()
# print(eggs)#全局变量能够在局部作用域内被读取,局部变量不能在全局作用域内使用

# def spam():
#     eggs = "spam local"
#     print(eggs) #print "spam local"
#
# def bacon():
#     eggs = "bacon local"
#     print(eggs) #print "bacon local"
#     spam()
#     print(eggs) #print "bacon local"
#
# eggs = "global"
# bacon()
# print(eggs) #print "global"
#打印结果的原因就是,
#一个函数再被调用结束后他所在的局部作用域就已经被销毁了,他所包含的变量的值也就被销毁了,即一个函数的局部变量完全与其他函数中的局部变量分隔开来
# 全局变量能够在局部作用域内被读取,局部变量不能在全局作用域内使用
#虽然这样的代码不存在语法错误,但是当出现问题时,追踪变量就显得十分的麻烦

# def spam():
#     global eggs #使用global语句可以在一个函数中修改局部变量
#     eggs = "spam"
#
# eggs = "global"
# print(eggs)
# spam()
# print(eggs)

# def spam():
#     global eggs
#     eggs = "spam"#这是一个全局变量
#
# def bacon():
#     eggs = "bacon"#这是一个局部变量
#
# def ham():
#     print(eggs)#这是一个全局变量
# ham()#此处调用会出错,因为全局变量此时并没有被定义
# eggs = 43#这是一个全局变量
# ham()#此时打印结果为43
# spam()
# print(eggs)
# ham()此时打印结果为spam,因为调用了函数spam,使得对全局变量eggs重新赋值了

#This is a guess the number game.
# import random
# secretsNumber = 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 < secretsNumber:
#         print("Your guess is too low.")
#     elif guess > secretsNumber:
#         print("Your guess is too high.")
#     else:
#         break #This condition is the correct guess!
# if guess == secretsNumber:
#     print("Good job! You guessed my number in "+str(guessesTaken)+"guesses!")
# else:
#     print("Nope.The number I was thinking of was"+str(secretsNumber))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值