Python入门书《笨办法学Python》笔记——第二篇

Python入门书《笨办法学Python》笔记


第二篇、习题11至习题20


习题11、关于raw_input()引入

代码段:

print "How old are you?",
age = raw_input()
print "How tall you are?",
height = raw_input()
print "How much do you weight?",
weight = raw_input()

print "So you're %r old, %r tall and %r heavy."%(age, height, weight)
"

结果:
不同输入下的输出:

How old are you? 24
How tall you are? 180
How much do you weight? 75
So you’re ‘24’ old, ‘180’ tall and ‘75’ heavy.

How old are you? 24years
How tall you are? 180cm
How much do you weight? 70kg
So you’re ‘24years’ old, ‘180cm’ tall and ‘70kg’ heavy.

注意:

1、raw_input()输入为字符串,其内部包含了打印功能,上面可以改为age = raw_input(“How old are you?”)同样效果
2、可强制类型转换,将字符串转换为int 即:age = int(raw_input(“How old are you?”))



习题12、raw_input()提示

代码段:

age = raw_input("How old are you ?")
height = raw_input("How tall you are?")
weight = raw_input("How weight you are?")

print "So you're %r old, %r tall and %r heavy."%(age, height, weight)

结果:
与习题11完全一致

注意:

1、raw_input()可以让它显示一个提示,从而告别别人应该输入什么东西,可以在()之间放入一个你想要作为提示的字符串

补充内容:

1、Terminal终端输入:pydoc raw_input
输出:
Help on built-in function raw_input in module builtin:
raw_input(…)
raw_input([prompt]) -> string

Read a string from standard input. The trailing newline is stripped.
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
On Unix, GNU readline is used if enabled. The prompt string, if given,
is printed without a trailing newline before reading.

关于pydoc:是Python的文档工具



习题13、参数、解包和变量

代码段:

from sys import argv             #sys是模块

#argv是“参数变量”(argument variable),这个变量保存着运行Python脚本时传递给Python脚本的参数
#这一行将argv“解包”(unpack),将argv中的东西解包
#将所有参数依次赋值给左边的变量,script、first、second和Third.
script, first, second, third = argv    

print "The script is called: ", script
print "Your first variable is:", first
print "Your second variable is:", second
print "your third variable is: ", third

结果:

不同输入下的输出:

root@db1:~/share/python/Hardway# python second.py 1 2 3 4
Traceback (most recent call last):
File “second.py”, line 64, in
script, first, second, third = argv
ValueError: too many values to unpack
当给予三个以上的参数,提示在解包时值过多,运行脚本时参数的个数不匹配

root@db1:~/share/python/Hardway# python second.py a b
Traceback (most recent call last):
File “second.py”, line 64, in
script, first, second, third = ar

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值