首页 > 代码库 > 1、Python基础
1、Python基础
简明python教程:http://woodpecker.org.cn/abyteofpython_cn/chinese/
进入python:
[root@likun ~]# python
Python2.6.5(r265:79063,Jul142010,11:36:05)
[GCC 4.4.420100630(RedHat4.4.4-10)] on linux2
Type"help","copyright","credits" or "license"for more information.
>>>
退出python
[ CTRL + d ]
查看版本:
[root@likun ~]# python -V
Python 2.6.5
执行第一个hello程序
[root@likun ~]# cat hello.py
#!/usr/bin/python
print‘hello!‘
[root@likun ~]#
[root@likun ~]# python hello.py
hello!
print加颜色:
>>> print ‘\033[31;1mHello world!\033[0m‘
print重复输出字符:
>>> print (‘a‘*5)
aaaaa
读取用户输入:
>>> A = raw_input(‘pleas input:‘)
pleas input:hello!
>>> print A
hello!
保证输入为数字:
>>> A = int(raw_input(‘pleas input number:‘))
pleas input number:sdf
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ‘sdf‘
转换数字为字符:
>>> str(12)
‘12‘
简单计算:
>>> 2 * 3
6
>>> 32/4
8
>>> b=2+3
>>> print b
5
变量:
>>> name=‘Likun‘ --定义,并给变量赋值,字符类型要加引号
>>> print name
Likun
>>> name1=name --变量之间传递赋值
>>> print name1
Likun
>>> print ‘%s is good‘%name1 --%s 为变量占位符
Likun is good
>>> name1=addr --addr未加引号,会当做变量而不是字符,找不到变量因此报错
Traceback(most recent call last):
File"<stdin>", line 1, in <module>
NameError: name ‘addr‘ is not defined
变量使用单引、双引、三引的区别
正常字符串用单引
本身带单引的字符串用双引
三引可以引住多行字符
[root@likun python_scripts]# cat 1hello.py #!/usr/bin/pythonprint ‘hello!‘print "what‘s your name?"n=‘‘‘good morningeveryone,come on !‘‘‘print n
‘‘‘ ‘‘‘ 可以用来注释多行代码
小练习:兑换人民币
[root@likun python_scripts]# cat 3rate.py #!/usr/bin/pythonprint ‘The rate between HK$ and US$ to RMB\n‘rmb =int(raw_input(‘input how much RMB you want to change:‘)) --int后才能做浮点运算HK=rmb /0.84US=rmb /6.4print ‘HK=‘,HK,‘,US=‘,US --拼接用逗号
[root@likun python_scripts]# python 3rate.py
The rate between HK$ and US$ to RMB
input how much RMB you want to change:10
HK=11.9047619048,US=1.5625
缩进要求:
逻辑上同一层级的,要对齐,不对齐会报错
不同层级的必须有缩进,否则也会报错
缩进可以选择制表符、单空格、双空格,全文一定要保证缩进上下一致
[root@likun python_scripts]# cat 1hello.py #!/usr/bin/pythonprint ‘hello!‘print ‘world‘ for i in range(1,5): print i
python命令自动补全脚本:
vim ~/.pythonstartup
import sysimport readlineimport rlcompleterimport atexitimport osreadline.parse_and_bind(‘tab: complete‘)histfile = os.path.join(os.environ[‘HOME‘], ‘.pythonhistory‘)try: readline.read_history_file(histfile)except IOError: passatexit.register(readline.write_history_file, histfile)del os, histfile, readline, rlcompleter
echo "export PYTHONSTARTUP=~/.pythonstartup" >> ~/.bashrc
1、Python基础
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。