笨办法19函数和变量
来源:互联网 发布:mac帧ip类型数据长度 编辑:程序博客网 时间:2024/06/08 13:03
以下为代码
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 = 10amount_of_crackers = 50cheese_and_crackers(amount_of_cheese, amount_of_crackers)print "We can even do math inside too:" #通过math执行cheese_and_crackers(10 + 20, 5 + 6)print "And we can combine the two, variables and math:" #通过变量+math执行cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
输出结果:
获取用户输入:
def cheese_and_crackers(cheese_count, boxes_of_crackers): print "You have %d cheeses!" % cheese_count print "You have %d boxes of crackers!\n" % boxes_of_crackersnum1 = raw_input("cheeses:")num2 = raw_input("crackers:")cheese_and_crackers(num1, num2)
然而执行到用户输入后,报错
查看问题发现,报错由于变量的类型不正确,即%d和raw_input的问题,原因是raw_input() 将所有输入作为字符串看待,返回的是字符串类型。可以有以下解决办法:
1. 将%d换成%r或者%s
2. 将raw_input换成input,input() 返回所输入的数字的类型( int, float )
3. 第8行加入int: cheese_and_crackers(int(num1), int(num2))
以下用方法2
def cheese_and_crackers(cheese_count, boxes_of_crackers): print "You have %d cheeses!" % cheese_count print "You have %d boxes of crackers!\n" % boxes_of_crackersnum = "Please enter the number"num1 = input(num + ", cheeses:")num2 = input(num + ", crackers:")cheese_and_crackers(num1, num2)
顺利输出结果:
阅读全文
0 0
- 笨办法19函数和变量
- 笨办法学python习题19 函数和变量
- 笨办法18命名、变量、代码、函数
- 笨办法学python习题18 命名、变量、代码和函数
- 《笨办法学python》---更多的变量和打印
- 笨办法05更多的变量和打印
- 笨办法学python习题4 变量和命名
- 变量变量和变量函数
- Exercise 19: 函数和变量
- 习题19 函数和变量
- exercise 19 函数和变量
- 笨方法学Python 习题 19: 函数和变量
- 笨方法学习Python-习题19: 函数和变量
- 笨办法学python习题13 参数、解包和变量
- 笨办法学python习题5 更多的变量和打印
- static函数和变量
- static 函数和变量
- 变量和函数
- R --xgboost使用
- SVN分支管理
- (14)cookie细节
- 浅析TCP通信原理
- nginx中ssl模块
- 笨办法19函数和变量
- quartz学习笔记6:多线程
- JavaWeb项目中数据库存入数据中乱码的解决方案
- c++基础之随机函数
- 用ImageLoader查找图片继承Application
- unigui导出EXCEL使用NATIVEEXCEL
- 花式读取Android CPU使用率
- 2017 ACM/ICPC Asia Regional Shenyang Online 1004 array array array
- jzoj P2190 dis