鱼C论坛

 找回密码
 立即注册
查看: 1825|回复: 1

[已解决]为什么这个执行不出来呢

[复制链接]
发表于 2023-6-12 17:03:24 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
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)
截图未命名.jpg
最佳答案
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)

以上修改过后的代码应该可以正常运行了。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 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)

以上修改过后的代码应该可以正常运行了。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-22 19:36

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表