cs61A discussion 1: control,Environment
#!/usr/bin/env python
# -*- coding: utf-8 -*-#
#-------------------------------------------------------------------------------
# Name: disu01
# Description:
# Author: handa
# Date: 2022/4/18
#-------------------------------------------------------------------------------
def special_case():
x = 10
if x > 0:
x += 2
elif x < 13:
x += 3
elif x % 2 == 1:
x += 4
return x
r = special_case()
print(r)
def just_in_case():
x = 10
if x > 0:
x += 2
if x < 13:
x += 3
if x % 2 == 1:
x += 4
return x
r = just_in_case()
print(r)
def wears_jacket_with_if(temp, raining):
"""
>>> wears_jacket_with_if(90, False)
False
>>> wears_jacket_with_if(40, False)
True
>>> wears_jacket_with_if(100, True)
True
"""
if temp < 60 or raining:
return True
else:
return False
r = wears_jacket_with_if(100,True)
print(r)
def if_function(condition, true_result, false_result):
"""Return true_result if condition is a true value, and
false_result otherwise.
>>> if_function(True, 2, 3)
2
>>> if_function(False, 2, 3)
3
>>> if_function(3==2, 'equal', 'not equal')
'not equal'
>>> if_function(3>2, 'bigger', 'smaller')
'bigger'
"""
if condition:
return true_result
else:
return false_result
def with_if_statement():
"""
>>> result = with_if_statement()
61A
>>> print(result)
None
"""
if cond():
return true_func()
else:
return false_func()
'''
这个运行正常
'''
def with_if_function():
"""
>>> result = with_if_function()
Welcome to
61A
>>> print(result)
None
"""
return if_function(cond(), true_func(), false_func())
def cond():
print("enter cond")
return True
def true_func():
print("Welcome to")
def false_func():
print("61A")
with_if_function()
'''
要求定义cond,true_func,false_func三个函数,当调用with_if_function函数时输出welcome to
61A
这题主要是因为 表达式if_function(cond(), true_func(), false_func())在调用if_function时,先计算机出三个函数,所以会先输出所有结果,并不受if条件限制。
'''
函数帧
- 由于懒得截图,参考别人的答案
https://blog.csdn.net/Denny5608/article/details/120484514