pionrrt 发表于 2023-6-12 17:03:24

为什么这个执行不出来呢

def cheese_and_crackers(cheese_count,boxes_of_crackers):
    print("You have %r cheeses!")%cheese_count
    print("You have %r 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)

isdkz 发表于 2023-6-12 17:07:31

代码执行错误是因为你的字符串格式化操作(%操作符)在打印语句外部进行。你应该将%操作符以及后续的变量放在括号内,这样就可以将字符串中的%r替换为变量的值。正确的代码应该如下:

def cheese_and_crackers(cheese_count, boxes_of_crackers):
    print("You have %r cheeses!" % cheese_count)
    print("You have %r 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)


另外,注意到在你的代码中,"We can just give the function numbers directly:"这句话应该在函数调用前打印,而不是在函数内部打印。如下所示:

def cheese_and_crackers(cheese_count, boxes_of_crackers):
    print("You have %r cheeses!" % cheese_count)
    print("You have %r 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)


以上修改过后的代码应该可以正常运行了。
页: [1]
查看完整版本: 为什么这个执行不出来呢