Python第四堂课:用户输入

咱们学完了输出,那就得想到肯定会有用户要求输入。

用户输入了东西,需要调用,肯定需要先赋值给一个变量,才能使用。

输入命令: raw_input([prompt])

其中提示是可选的,如果不填也是可以的,提示的话,可以参考前面说的字符串那一章节。很简单的吧~

对用户输入进行赋值,

>>> abc = raw_input("input something:\t")

input something: kairong 18

>>> print abc,

kairong 18

简单吧~来做练习吧~

age = raw_input("How old are you? ")
height = raw_input("How tall are you? ")
weight = raw_input("How much do you weigh? ")
print "So, you're %r old, %r tall and %r heavy." % (
age, height, weight)

How old are you? 35
How tall are you? 6'2"
How much do you weight? 180lbs
So, you're '35' old, '6\'2"' tall and '180lbs' heavy.

用户输入,在脚本中互动是一种方法,还有一种方法是,使用用户在脚本后面添加相关的参数进行导入。

在这里需要使用一个命令:import,这个命令很强大,可以把你的原来写的东西,直接拿来使用,也可以使用网上的现成代码。

使用方法有三种方法:

1、import time  #(time是关于时间的的一个基本库,后面也许会降到,先埋坑)

2、import time as time_alias #(有时候网上提供的库名不便于识别,需要重命名为我认识的,针对我这种英语白痴的话,很实用哦)

3、from time import sleep #(导入time库里的单个功能,可以这么使用)

4、from time import sleep #(导入time库里的单个功能并重命名)

好了怎么读取变量呢?

下面就是测试代码。

exp1.py
from
sys import argv print argv

argv本身获取的是一个元组。

python exp1.py abc def

这样执行这个命令的话,获得输出是:

['f:\\lianxi\\python\\exp1.py', 'abc', 'def']

我们看出,argv[0],是这个脚本本身的名称,后续依次+1。关于元组的话,可以后续看看元组的使用方法。

现在咱们做个练习:

我想让脚本输出我脚本后面的字符串(我搞了两个字符串,请看官自己追加更多)

exp2.py
from sys import argv
print "first string is %s" % argv[1]
print "second string is %s" % argv[0]
print "you input %d strings" % ( len(argv) -1) #减一是因为需要抛去脚本的那一位。
按照 python exp2.py "hello world" "kairong"
first string is hello world second string is kairong you input 2 strings

好了,今天比较少。。。漠然发现我把《笨办法学python》的14章融合成了4章。。。

原文地址:https://www.cnblogs.com/sageskr/p/3047837.html