LPTHW,EX19 额外学分 3

0 投票
6 回答
1766 浏览
提问于 2025-04-17 12:55

我正在学习Zed Shaw的《用艰难的方式学Python》这本书,但在额外的第三个作业上卡住了,找不到相关的问题,所以我决定注册一个账号。

额外作业: 写一个你自己设计的函数,并用10种不同的方式来运行它。

代码:

def cheese_and_crackers(cheese_count, boxes_of_crackers):
    print "You have %d cheeses!" % cheese_count
    print "You have %d boxes of crackers!" % boxes_of_crackers
    print "Man that's enough for a party!"
    print "Get a blanket.\n"


print "We can just give the function numbers directly:"
cheese_and_crackers(20, 30)


print "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50

cheese_and_crackers(amount_of_cheese, amount_of_crackers)


print "We can even do math inside too:"
cheese_and_crackers(10 + 20, 5 + 6)


print "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)

那么,在你的脚本中,还有哪些其他方法可以运行一个函数呢?能不能请你用简单易懂的方式帮我解释一下,最好能提供一些实际的代码,这样我可以尝试理解一下?

6 个回答

0

在编程中,有时候我们需要处理一些数据,比如从一个地方获取数据,然后在程序中使用这些数据。这个过程就像是从冰箱里拿东西出来,然后用这些食材做饭。

有些时候,我们会遇到一些问题,比如数据格式不对,或者数据缺失。这就像是你打开冰箱,发现缺少了某种食材,或者食材过期了,这样就没法做出你想要的菜。

为了避免这些问题,程序员通常会在代码中加入一些检查,确保数据是正确的。这就像是在做饭之前,先检查一下冰箱里的食材是否新鲜,是否足够。

总之,处理数据就像做饭一样,需要仔细检查,确保一切都准备好,才能做出美味的菜肴。

from sys import argv

a, u = argv

def get_length(arg):
    return len(arg)

# 1
print get_length(u)
# 2
print get_length(u+'leaf')
# 3
print get_length(u+'5'*4)
# 4
print get_length('length\n')
# 5
print get_length('length'+'python')
# 6
print get_length('length'*6)
# 7
temp = 'length'
print get_length(temp)
# 8
print get_length(temp+'python')
# 9
print get_length(temp*6)
# 10
print get_length(open(raw_input('filenanme: ')).read())
# 11
print get_length(raw_input('a string:'))
1

我可以再加几种方法:

#the sum function
def displaySum(a,b):
  sum = a + b
  print "The sum is: %d" % sum

print "#1:"
displaySum(5,10)                #1


print "#2:"
x=3
k=7                             #2
displaySum(x,k)

print "#3:"
displaySum(5+5, 10+10)          #3

print "#4:"
displaySum(x+5,k+10)            #4

print "#5:"
var1 = int(raw_input("p1: "))   #5
var2 = int(raw_input("p2: "))
displaySum(var1,var2)


def passValue():                #6
  x1 = 100 
  x2 = 200
  displaySum(x1,x2)

print "#6:" 
passValue()
2

我把评论整理成一个答案放在这里。

print 'We can assign the function to a variable and simply call it by its new name'
foo = cheese_and_crackers
foo(20,30)

print 'We can call the function in a loop, calling it 10 times'
for i in range(10):
    cheese_and_crackers(20,30)

print 'We can pass a function as arguments.'
print 'We can now ask the user for the number of cheese and crackers'
cheese_and_crackers(int(raw_input('how many cheese?')), int(raw_input('how many crackers?')))

撰写回答