《笨方法学Python》第六期:参数、变量

Python系列之笨方法学Python是我学习《笨方法学Python》—Zed A. Show著
的学习思路和理解,如有不如之处,望指出!!!

文章主要分为三个部分:

  1. 原文—摘录至《笨方法学Python》第三版
  2. 学习中遇到的问题
  3. 问题的解决方法
  4. 附加练习

原文—摘录至《笨方法学Python》第三版

ex13.py & ex14.py
# ex13.py

from sys import argv
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


# ex14.py

from sys import argv
script, user_name =argv
prompt='> '

print "Hi %s, I'm the %s script."%(user_name,script)
print "I'd like to ask you a few questions."
print "Do you like me %s?"%user_name
likes=raw_input(prompt)

print "Where do you live %s?"%user_name
lives=raw_input('> ')

print "What kind of computer do you have?"
computer=raw_input(prompt)

print"""
Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice!
""" %(likes,lives,computer)

应该看到的结果


原文作者不建议使用python的IDLE运行程序,推荐使用windows下的Powershell(命令行)

不清楚为什么不建议使用IDLE


ex13.py
> python ex13.py 1st 2nd 3rd
The script is called:ex13.py
Your first variable is:1st
Your second variable is:2nd
Your third variable is:3rd
ex14.py
> python ex14.py darer
Hi darer, I'm the ex14.py script.
I'd like to ask you a few questions.
Do you like me darer?
> yes

Where do you live darer?
> china

What kind of computer do you have?
> lenovo

Alright, so you said 'yes' about liking me.
You live in 'china'. Not sure where that is.
And you have a 'lenovo' computer. Nice!

需要注意的几个地方

  1. 怎么在当前文件夹运行Powershell

    • 利用命令行指令 cd
    • 在当前文件夹 shift+鼠标右键 选择“打开powershell"
  2. 注意ex14.py中,raw_input()的用法

  3. 为什么ex14.py 中,键入的字符没有单引号,但是输出的结果中却有单引号(' ')呢?

    因为%r是调试专用,它输出的是“原始表示”出来的字符

    %s是为了给用户显示

附加练习

以下摘录自原文

  1. 是否可以用双引号定义prompt变量的值?

  2. argvraw_input()有什么不同?

    如果参数是在用户执行命令时就要输入的,那就是argv

    如果是在脚本运行过程中需要用户输入,那就使用raw_input()

  3. argv就是所谓的”参数变量“(argument variable),这个变量保存着你运行Python脚本时传递给Python脚本的参数。

  4. 脚本中出现import语句,非常重要,它用于导入模块(module)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值