help帮助系统,一个好的方法是直接看自带的帮助,尽量不用baidu

help()是进入交互式帮助界面
quit是退出交互式帮助界面 [root@kvm1 python]# python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> help
Type help() for interactive help, or help(object) for help about object.
>>> help() Welcome to Python 2.7! This is the online help utility. If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/2.7/tutorial/. Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit". To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics". Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam". help> help> quit You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)". Executing "help('string')"
has the same effect as typing a particular string at the help> prompt. 下面是模块,关键字,主题的列表
help> modules Please wait a moment while I gather a list of all available modules... ANSI base64 io sched
BaseHTTPServer bdb itertools screen
Bastion binascii javapackages select
CDROM binhex json selinux
CGIHTTPServer bisect jsonschema semanage
Enter any module name to get more help. Or, type "modules spam" to search
for modules whose descriptions contain the word "spam". help> keywords Here is a list of the Python keywords. Enter any keyword to get more help. and elif if print
as else import raise
assert except in return
help> topics Here is a list of available topics. Enter any topic name to get more help. ASSERTION DEBUGGING LITERALS SEQUENCEMETHODS2
ASSIGNMENT DELETION LOOPING SEQUENCES
ATTRIBUTEMETHODS DICTIONARIES MAPPINGMETHODS SHIFTING
ATTRIBUTES DICTIONARYLITERALS MAPPINGS SLICINGS
导入一个自定义模块
[root@250-shiyan ~]# mkdir python
[root@250-shiyan ~]# cd python/
[root@250-shiyan python]# cat >hello.py
#! /usr/bin/env python
print "hello world"
[root@250-shiyan python]# python hello.py
hello world
[root@250-shiyan python]# ll
total 4
-rw-r--r-- 1 root root 43 Jul 16 12:50 hello.py
[root@250-shiyan python]# chmod 755 hello.py
[root@250-shiyan python]# ./hello.py
hello world
[root@250-shiyan python]# python
Python 2.6.6 (r266:84292, Jan 22 2014, 09:42:36)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import hello
hello world
>>> quit()
[root@250-shiyan python]# ll
total 8
-rwxr-xr-x 1 root root 43 Jul 16 12:50 hello.py
-rw-r--r-- 1 root root 116 Jul 16 12:51 hello.pyc

需求逐渐增加

1.去掉用户名前后的空格  strip()

2.判断用户名不为空

  不输入或输入空格都是空  用len()

3.判断用户名是否输错  !=

4.超过3次就退出

  需要一个计数器来判断次数

程序是一步步做出来的,这次加一点,下次加一点。

1.第一次只是基本的格式化输出  print "your name is %s" %name

2.第二次加入 strip()方法去掉前后的空格,保证程序的健壮性,来防止用户输入错误。

3.第三次加入while循环,使得用户只能输入正确的aa,才能返回正常,否则不输入或输入错误都不行

[root@kvm1 python]# cat input2.py
#! /usr/bin/env python #name= raw_input("please enter your name: ").strip()
while True:
        name= raw_input("please enter your name: ").strip()
        if len(name)==0:
                print "Empty name,try again:"
                continue
     elif name != "aa"
         print "Error name,try again: %s " %name
                continue
        break
age=int(raw_input("please enter your age: "))
sex= raw_input("your sex is: ")
dep= raw_input("which department: ")
#message = '''Information of the company staff:
# Name:%s
# Age:%d
# Sex:%s
# Dep:%s
# ''' % (name,age,sex,dep)
#print message if name != "aa":
print "you are not in user list"
else:
print "welcome you are login"

制作tab补全

centos7是下面这个目录,ubuntu可能不一样
[root@kvm1 site-packages]# pwd
/usr/lib/python2.7/site-packages
[root@kvm1 site-packages]# vi tab.py
#!/usr/bin/env python
# python startup file
import sys
import readline
import rlcompleter
import atexit
import os
# tab completion
readline.parse_and_bind('tab: complete')
# history file
histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
try:
readline.read_history_file(histfile)
except IOError:
pass
atexit.register(readline.write_history_file, histfile)
del os, histfile, readline, rlcompleter [root@kvm1 site-packages]# python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> import tab
>>> sys.
sys.__class__(              sys.__subclasshook__(       sys.exitfunc(               sys.path_importer_cache
[root@kvm1 site-packages]# ll tab.py
tab.py   tab.pyc
进入python,import tab一下,就有了tab.pyc这个模块了
>>> import os shutil
>>> os.getcwd()
'/root/code/python'
>>> os.listdir("/home")
['zf', 'img', 'iso', 'docker']
>>> os.path.isfile("/tmp")
False
>>> os.path.isfile("input.py")
True
>>> os.path.isabs("input.py")
False
>>> os.path.isabs("/root/code/python/input.py")
True
>>> os.path.split("/root/code")
('/root', 'code')
>>> os.system("free")
              total        used        free      shared  buff/cache   available
Mem:       32657352    16457992     6302376      229644     9896984    15655708
Swap:      14352380           0    14352380
0
>>> os.linesep
'\n'
>>> os.name
'posix' >>> import tab
>>> from os import system
>>> system("df -h")

python 将用户输入录入到sqlite3数据库中,不过这个脚本有点问题,自动创建库,因为首次要建表,第二次录入时会报错,所以应该加一个判断表是否存在的语句块,然后再插入数据,查询数据时,有几行查几行,也可以一次查完(根据代码适度调整吧)

[root@kvm1 python]# cat input3.py
#! /usr/bin/env python import sqlite3 name= raw_input("please enter your name: ")
age=int(raw_input("please enter your age: "))
sex= raw_input("your sex is: ")
dep= raw_input("which department: ") # test.db is a file in the working directory.
conn = sqlite3.connect("test.db")
c = conn.cursor()
# create tables
c.execute('''CREATE TABLE staff
(name string,
age int,
sex string,
dep string)''')
# save the changes
conn.commit() #staffs = [("a",10,"male","caiwu"),
# ("b",15,"female","hr"),
# ("c",20,"male","it")] # execute "INSERT"
#c.execute("INSERT INTO staff VALUES (,age,sex,dep)")
# using the placeholder
c.execute("INSERT INTO staff VALUES (?, ?, ?, ?)", (name,age,sex,dep)) #c.execute('UPDATE staff SET price=? WHERE id=?',(1000, 1))
#c.execute('DELETE FROM staff WHERE id=2')
#c.execute('DROP TABLE staff')
# execute multiple commands
#c.executemany('INSERT INTO staff VALUES (?, ?, ?, ?)', staffs)
conn.commit()

#SQL语句中的参数,使用"?"作为替代符号,并在后面的参数中给出具体值。这里不能用Python的格式化字符串,如"%s",因为这一用法容易受到SQL注入攻击。 c.execute('SELECT * FROM staff')
print(c.fetchone())
print(c.fetchone()) # retrieve all records as a list
#c.execute('SELECT * FROM staff')
#print(c.fetchall()) # iterate through the records
#for row in c.execute('SELECT name, price FROM book ORDER BY sort'):
# print(row) # close the connection with the database
conn.close()

全局替换,注意print aa,这个逗号,不加的话,最后修改后的list.txt格式不正确

[root@kvm1 python]# python rep.py
[root@kvm1 python]# cat list.txt
1 zhou aa-1 15897638976
2 wu feaa 18946578291
3 zheng aa-1 02134578129
4 wang feaa 01098452345
5 feng feaa 02987654890
6 cheng feaa 15771543637
7 chu aa-1 18691234578
8 wei aa-1 18097643789
9 li aa-1 17654893092 [root@kvm1 python]# cat rep.py
#! /usr/bin/env python import fileinput
for line in fileinput.input("list.txt",inplace=1):
aa=line.replace("male","aa")
print aa,
将字符串转成列表
>>> name
['alex', 'fog', 4, 'wo', 'wo']
>>> name.count('wo')
2
>>> 'fog' in name
True
>>> 'fog1' in name
False 将字符串转成列表,默认是以空格为分隔符的,也可以以某个符号为分隔符例如=
>>> a='wowiewoewie'
>>> a.split()
['wowiewoewie']
>>> a='w o w i ew o ew ie'
>>> a.split()
['w', 'o', 'w', 'i', 'ew', 'o', 'ew', 'ie']
>>> a='w o = w i ew = o ew ie'
>>> a.split('=')
['w o ', ' w i ew ', ' o ew ie']
>>> b=a.split('=')
>>> b
['w o ', ' w i ew ', ' o ew ie']

一个购物车程序,用到了列表

[root@kvm1 python]# cat shop.py
#! /usr/bin/env python import sys
products=['car','phone','food','colths','bicyle']
prices=[5000,2010,202,120,549]
shop=[]
while True:
try:
salary=int(raw_input("please input your money "))
break
except ValueError:
print "please input a number,not string."
while True:
print "the have to the shop,please choose one to buy"
for p in products:
print "%s,%s" %(p,prices[products.index(p)])
choice=raw_input("please input one item to buy: ")
F_choice=choice.strip()
if F_choice =='quit':
print "you have bought these things: %s" % shop
sys.exit()
if F_choice in products:
product_price_index=products.index(F_choice)
product_price=prices[product_price_index]
print "%s $%s" %(F_choice,product_price)
if salary > product_price:
shop.append(F_choice)
print "added %s into your shop list" %F_choice
salary =salary - product_price
print "salary is left: $",salary
else:
if salary < min(prices):
print "rest of money cant buy anything"
print "you have these things: %s" % shop
sys.exit()
else:
print "sorry,you cant affor this thing"

从文件中读入数据,并将其转为列表

将文本文件转成列表
[root@kvm1 python]# cat aa.txt
car 1000
phone 500
colth 231
coffe 59
bicyle 400
[root@kvm1 python]# cat b.py
#! /usr/bin/env python products = []
prices = [] f = file("aa.txt")
for line in f.readlines():
p = line.split()[0]
pri = int(line.split()[1])
products.append(p)
prices.append(pri)
print products
print prices [root@kvm1 python]# python b.py
['car', 'phone', 'colth', 'coffe', 'bicyle']
[1000, 500, 231, 59, 400]

将列表导出到一个文件中

[root@kvm1 python]# cat pat.py
import sys
f=open('pat.txt','w') for i in sys.path:
f.write(i+'\n') f.close()
[root@kvm1 python]# python pat.py
[root@kvm1 python]# cat pat.txt
/root/code/python
/usr/lib/python2.7/site-packages/mechanize-0.2.5-py2.7.egg
/usr/lib64/python27.zip
/usr/lib64/python2.7
/usr/lib64/python2.7/plat-linux2
/usr/lib64/python2.7/lib-tk
/usr/lib64/python2.7/lib-old
/usr/lib64/python2.7/lib-dynload
/usr/lib64/python2.7/site-packages
/usr/lib64/python2.7/site-packages/gtk-2.0
/usr/lib/python2.7/site-packages sys.path这个是模块的搜索路径,如果都没有,就报错。
所以可以将自己的.py文件放入以下任何一个目录中,就可随便导入了,并生成pyc文件

python编码-1的更多相关文章

  1. (转载) 浅谈python编码处理

    最近业务中需要用 Python 写一些脚本.尽管脚本的交互只是命令行 + 日志输出,但是为了让界面友好些,我还是决定用中文输出日志信息. 很快,我就遇到了异常: UnicodeEncodeError: ...

  2. Python 编码简单说

    先说说什么是编码. 编码(encoding)就是把一个字符映射到计算机底层使用的二进制码.编码方案(encoding scheme)规定了字符串是如何编码的. python编码,其实就是对python ...

  3. Python之路3【知识点】白话Python编码和文件操作

    Python文件头部模板 先说个小知识点:如何在创建文件的时候自动添加文件的头部信息! 通过:file--settings 每次都通过file--setings打开设置页面太麻烦了!可以通过:View ...

  4. python编码规范

    python编码规范 文件及目录规范 文件保存为 utf-8 格式. 程序首行必须为编码声明:# -*- coding:utf-8 -*- 文件名全部小写. 代码风格 空格 设置用空格符替换TAB符. ...

  5. 【转】python编码的问题

    摘要: 为了在源代码中支持非ASCII字符,必须在源文件的第一行或者第二行显示地指定编码格式: # coding=utf-8 或者是: #!/usr/bin/python # -*- coding: ...

  6. 【转】python编码规范

    http://blog.csdn.net/willhuo/article/details/49300441 决定开始Python之路了,利用业余时间,争取更深入学习Python.编程语言不是艺术,而是 ...

  7. python 编码 UnicodeDecodeError

    将一个py脚本从Centos转到win运行,出错如下: UnicodeDecodeError: 'gbk' codec can't decode byte 0xff in position 0: il ...

  8. Python编码/文件读取/多线程

    Python编码/文件读取/多线程 个人笔记~~记录才有成长   编码/文件读取/多线程 编码 常用的一般是gbk.utf-8,而在python中字符串一般是用Unicode来操作,这样才能按照单个字 ...

  9. 关于Python编码,超诡异的,我也是醉了

    Python的编码问题,真是让人醉了.最近碰到的问题还真不少.比如中文文件名.csv .python对外呈现不一致啊,感觉好不公平. 没图说个JB,下面立马上图.   我早些时候的其他脚本,csv都是 ...

  10. 规范的python编码

    规范的 python 编码令人赏心悦目,令代码的表达逻辑更清晰,使得工程代码更容易被维护和交流: 编码规范包括对于代码书写格式的约束,不良语法的禁用和推荐的编码手法,下面做些简要的描述: 1. 代码规 ...

随机推荐

  1. linux共享库

    linux共享库 linux中共享库一般以.so.x.y.z 命名,其中x,y,z分别为主版本号.次版本号.发布版本号.同一个库,主版本号不同则相互不兼容:主版本相同,次版本号高的库比次版本号低的库有 ...

  2. CentOS6.8下部署Zabbix3.0

    Centos6.8下部署安装zabbix3.0: 环境要求 PHP >= 5.4  (CentOS6默认为5.3.3,需要更新) curl >= 7.20 (如需支持SMTP认证,需更新) ...

  3. Caché数据库学习笔记(4)

    目录 DeepSee的使用 数据.方法等的导入与导出 ======================================================== ================ ...

  4. SPSS数据分析—相关分析

    相关系数是衡量变量之间相关程度的度量,也是很多分析的中的当中环节,SPSS做相关分析比较简单,主要是区别如何使用这些相关系数,如果不想定量的分析相关性的话,直接观察散点图也可以. 相关系数有一些需要注 ...

  5. python新技能get——看!源!码!

    上节课一起看了一下ThreadingTCPserver和tornado的源码,真是心力交瘁...后来仔细的想了一下,看懂源码其实并不难,只是需要明确一些以前我们学习过但是却容易被忽视的概念! 再看继承 ...

  6. POJ----(3974 )Palindrome [最长回文串]

    Time Limit: 15000MS   Memory Limit: 65536K Total Submissions: 5121   Accepted: 1834 Description Andy ...

  7. php WIN下编译注意问题

    下载VC2012,安装打开CMD 须运行 vcvars32.bat (初始化VC编译环境) 下载PHP WIN编译包:http://windows.php.net/downloads/php-sdk/ ...

  8. 转<%%>、<%=%>、<%$%>、<%@%>的区别

    1. 未定义的命名空间前缀“xsd” 上周在项目开发中遇到这样的一个问题,在一个页面用到了自定义的Picker控件,在IE6.7.8.9以及IE10兼容模式下都没有任何问题,但是一换到IE10时已选择 ...

  9. 如何编写android ANE

    1.编写AndroidAne.jar: a.编写SkyContext.java: import java.util.HashMap;import java.util.Map;import com.ad ...

  10. eclipse 本地项目提交到远程库以及从远程库中添加项目 ---git

    本地项目提交到远程库 1.右击项目->team->share project 2.选择本地库 从远处库中的项目拉到本地 1.右击项目->import项目