#!user/bin/env python
#-*- coding:utf-8 -*- # code001
print('hello world') (only one quotation mark, but not two on the upper) # code002
print('''
this is a multi-line string
and this is the first line.
"what's your name?," I asked
He said "Bond, James Bond."
''') # code003 formatting method
age = 25
name = 'Yuyukun'
print('{0} was {1} years old when he read this book'.format(name,age))
print('why is {0} playing with this python, he loves it?'.format(name)) # code004 concatenate strings, which are derived from code003
age = 25
name = 'Yuyukun'
string1 = name + ' is ' + str(age) + ' years old '
print(string1) # code005 there is nothing in the brace, i can get a same result with code003
age = 25
name = 'Yuyukun'
print('{} was {} years old when he read this book'.format(name,age))
print('{} playing with this python, he loves it.'.format(name)) # code006 formatting methon(in details)
print('{0:.3f}'.format(1.0/3)) #keep 3 decimal places
print('{0:_^11}'.format('hello')) #11bits and some bits are replaced by letters
print('{name} wrote {book}'.format(name='Lebron', book='shooting star')) # code007
# 'end' is to avoid line breakprint('a', end='')print('b', end='') # code008 add a blank in single quotes
print('a', end=' ')
print('b', end=' ')
print('c', end=' ') # code009 joint mark and line break
# print('this is the first line\nthis is the second line') #'\n':restart a new line
print("this is the first sentence. \
this is the second sentence.") #'\' help people continue inputting data rather than restart a new line
print('r"Newlines are indicated by \n"') # code010 using varialbe value and invariable value
i = 5
print(i)
i+=1
print(i)
s = '''this is a multi-line string.\
this isthe second line''' #when '\' is located at the end, it represents not line break, but go on.
v = '''this is a multi-line string.\this is the second line''' #when '\' is located at the middle, it is same with a 'Tab'
print(s) #there is a line break in default for the function of 'print()'
print(v) # code011 normally, there is no semicolon in a sentence in python, cos it has been omitted
i = 5
print(i)
i = 5; print(i);
i = 5; print(i);
i = 5;print(i)
#a same value is output by these methods/ #code012 control flow(if-elif-(elif如果有)-else)
num = 23
guess = int(input('Enter an integer : ')) if guess == num:
print('Congratulations, you guessed it.')
print('(but you do not win any prizes!)')
elif guess > num:
print('No, it is a little lower than that')
else:
print('No, it is a little higher than that') print('Done') # code013 control flow(while-else)
# num = 23
# running = True while running:
guess = int(input('Enter an integer : '))
if guess == num:
print('Congratulations, you guessed it.')
running = False
elif guess < num:
print('No, it is a little higher than that.')
else:
print('No, it is a little lower than that.')
else:
print('The while loop is over.')
print('Done') # code014 control flow(for-else)
for i in range(1, 5):
print(i)
else:
print('The for loop is over') # code015 control flow(break)
while True:
s = input('Enter something >>>')
if s == 'quit':
break
print('Length of the string is', len(s))
print('Done') # code016 control flow(continue)
while True:
s = input('Enter something : ')
if s =='quit':
break
if len(s)<3:
print('the length is too small')
continue
print('Input is of sufficient length') # code017 Functions(invoking function)
def say_hello():
print('hello world')
say_hello()
say_hello() # code018 Functions(parameters and arguments)
def print_max(a,b):
if a > b:
print(a, 'is maximum')
elif a == b:
print(a, 'is equal to b')
else:
print(b, 'is maximum')
print_max(3,4)
x=5
y=7
print_max(x,y) # code019 Functions(parameters and arguments)
x = 50
def func(x):
print('x is', x)
x = 2
print('changed local x to', x) func(x)
print('x is still', x) # code020 global parameters
x = 50
def func():
global x
print('x is', x)
x = 2
print('changed global x to', x) func()
print('value of x to', x) #code021 function default
def say(message, times=1):
print(message * times) say('hello')
say('hello', 5) # code022 function keywords
def func(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is', c) func(3, 7)
func(25, c=24)
func(c=50, a=100) # code023 function varargs, tuple
def total(a=5, *numbers, **phonebook):
print('a',a)
for single_item in numbers:
print('single_item',single_item) #tuple
for first_part, second_part in phonebook.items():
print(first_part,second_part) #dic
print(total(10,1,2,3,Jack=1123,John=2231,Inge=1560)) # code024 function of return
def maximum(x, y):
if x > y:
return x
if x==y:
return 'the numbers are equal'
else:
return y
print(maximum(3, 3)) # code025 docstrings
# 该文档字符串所约定的是一串多行字符串,其中第一行以某一大写字母开始,以句号结束。
# 第二行为空行,后跟的第三行开始是任何详细的解释说明
#编写的所有重要的函数配以文档字符串
def print_max(x, y):
'''打印这两个数的最大数。
这两个数都应该是整数。'''
x = int(x)
y = int(y)
if x > y:
print(x, 'is maximum')
else:
print(y, 'is miximum')
print_max(3, 5)
print(print_max.__doc__)
result:
# 5 is miximum
# 打印这两个数的最大数。
# 这两个数都应该是整数。 # code026 docstrings
def print_max(x, y):
help(print_max)
'''打印这两个数的最大数。
这两个数都应该是整数。'''
x = int(x)
y = int(y)
if x > y:
print(x, 'is maximum')
else:
print(y, 'is miximum')
print_max(3, 5)
print(print_max.__doc__) # code027 modules and import operation
import sys
print('The command line arguments are:')
for i in sys.argv: #sys.argv[0], sys.argv[1]... if there are some other arguments
print(i) #print these arguments
print('\n\nThe PYTHONPATH is', sys.path, '\n') #list all directories in which sys.path is located. # code028 obtain the path of the current precedure
import os;
print(os.getcwd()) # code029 from...import...
from math import sqrt
print("Square root of 16 is", sqrt(16))
if __name__ == '__main__':
print('This program is being run by itself')
else:
print('I am being imported from another module') # code030 import
import mymodule
mymodule.say_hi()
print('Version', mymodule.__version__)
# lower sentences are stored in the mymodule.py(C:/Users/Administrator.PC-20160817HMOW/PycharmProjects/a byte of python/a byte of python.py)
def say_hi():
print('Hi, this is mymodule speaking')
__version__ = '' import mymodule
mymodule.say_hi()
print('My version is ', mymodule.myversion)
# function, module is to call different procedures.
# packages are to organize the structure of procedures
# code031 ds_using_list
shoplist = ['apple', 'mango', 'carrot', 'banana']
print('I have', len(shoplist), 'items to purchase.')
print('these items are:', end=' ')
for item in shoplist:
print(item, end=' ') print('\nI also have to buy rice.')
shoplist.append('rice')
print('my shopping list is now', shoplist) print('i will sort my list now')
shoplist.sort() print('sorted shopping list is', shoplist[0])
olditem = shoplist[0]
del shoplist[0]
print('i bought the', olditem)
print('i bought list is now',shoplist) # code032 tuple is also a alignment
zoo = ('python', 'elephant', 'penguin')
print('Number of animals in the zoo is', len(zoo))
new_zoo = 'monkey', 'camel', zoo
print('Number of cages in the new_zoo is', len(new_zoo))
print('All animals in new_zoo are', new_zoo)
print('animals brought from old zoo are', zoo)
print('last animal brought from old zoo is', new_zoo[2][2])
print('number of animals in the new zoo is', len(new_zoo)-1+len(new_zoo[2])) # code033 dict
ab = {
'Swaroop': 'swaroop@swaroopch.com',
'Larry': 'larry@wall.org',
'Matsumoto': 'matz@ruby-lang.org',
'Spammer': 'spammer@hotmail.com',
'Guido' : 'guido@python.org'
}
print("Swaroop's address is", ab['Swaroop'])
del ab['Spammer']
print('\nThere are {} contacts in the address.book\n'.format(len(ab)))
for name, address in ab.items():
print('Contact {} at {}'.format(name, address))
ab['Guido'] = 'guido@python.org'
if 'Guidio' in ab:
print("\nGuido's address is", ab['Guido']) # code034 sequence
shoplist = ['apple', 'mango', 'carrot', 'banana']
name = 'swaroop'
print('item 0 is', shoplist[0])
print('item 1 is', shoplist[1])
print('item 2 is', shoplist[2])
print('item 3 is', shoplist[3])
print('item -1 is', shoplist[-1])
print('item -2 is', shoplist[-2])
print('Character 0 is', name[0]) print('item 1 to 3 is', shoplist[1:3])
print('item 2 to end is', shoplist[2:])
print('item 1 to -1 is', shoplist[1:-1])
print('item start to end is', shoplist[:]) print('item 1 to 3 is', name[1:3])
print('item 2 to end is', name[2:])
print('item 1 to -1', name[1:-1])
print('characters start to end is', name[:]) # code035 reference comparision between copyscript and slice
print('simple assignment')
shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist
del shoplist[0]
print('shoplist is', shoplist)
print('mylist is', mylist)
del mylist[0]
print('shoplist is', shoplist)
print('mylist is', mylist)
print('copy by making a full slice')
mylist = shoplist[:]
del mylist[0]
print('shoplist is', shoplist)
print('mylist is', mylist) # code035 other strings
name = 'swaroop'
if name.startswith('swa'):
print('yes, the string starts with "swa"')
if 'a' in name:
print('yes, it contains the string "a"')
if name.find('war') == 1:
print('yes, it contains the string "war"')
delimiter = '_*_'
space = ' '
mylist = ['brazil', 'russia', 'india', 'china']
print(delimiter.join(mylist))
print(space.join(mylist))
print(mylist) # code036 solve problems create a zipfile
import os
import time
source = ['/Users/swa/notes']
target_dir = '/Users/swa/backup'
target = target_dir + os.sep + \
time.strftime('%Y%m%d%H%M%S') + 'zip'
if not os.path.exists(target_dir):
os.mkdir(target_dir)
zip_command = 'zip -r {0} {1}'.format(target,
' '.join(source))
print('zip command is:')
print(zip_command)
print('Running:')
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup Failed') # code037 class_1
class Person:
pass
p = Person()
print(p) # code038 class_self
class Person:
def say_hi(self):
print('hello, how are you?')
p = Person()
p.say_hi() # code039 __init__ implucitly to involk function
class Person:
def __init__(self, name):
self.name = name def say_hi(self):
print('hello, my name is', self.name) p = Person('swaroop')
p.say_hi() # code 040 obejvar
class Robot:
"""表示有一个带有名字的机器人"""
population = 0 def __init__(self, name):
self.name = name
print("(Initializing {})".format(self.name))
Robot.population +=1 def die(self):
print("{} is being destroyed!".format(self.name))
Robot.population -= 1 #Robot.population 类变量
if Robot.population == 0:
print("{} was the last one.".format(self.name))
else:
print("there are still {:d} robots working.".format(Robot.population)) def say_hi(self):
print("Greetings, my masters call me {}".format(self.name))
@classmethod
def how_many(cls):
"""打印出当前的人口数量"""
print("we have {:d} robots.".format(cls.population)) #cls.population 类方法 droid1 = Robot("R2-D2")
droid1.say_hi()
droid1.how_many() droid2 = Robot("C-3P0")
droid2.say_hi()
droid2.how_many() print("\nRobots can do some work here.\n")
print("Robots have finished their work. So let's destroy them.")
droid1.die()
droid2.die()
Robot.how_many() # code 041 subclass
class SchoolMember:
'''代表任何学校里的成员'''
def __init__(self, name, age):
self.name = name
self.age = age
print('(Initialized SchoolMember: {})'.format(self.name))
def tell(self):
print('Name:"{}" Age:"{}"'.format(self.name, self.age), end=" ") #end=" " 不换行并且空一格 class Teacher(SchoolMember):
'''代表一位老师'''
def __init__(self, name, age, salary):
SchoolMember.__init__(self, name, age)
self.salary = salary
print('(Initialized Teacher: {})'.format(self.name))
def tell(self):
SchoolMember.tell(self)
print('Salary: "{:d}"'.format(self.salary)) class Student(SchoolMember):
'''代表一位学生'''
def __init__(self, name, age, marks):
SchoolMember.__init__(self, name, age)
self.marks = marks
print(('Initialized Student: {}').format(self.name)) def tell(self):
SchoolMember.tell(self)
print('Marks: "{:d}"'.format(self.marks)) t = Teacher('Mrs. Shrividya', 40, 30000)
s = Student('Swaroop', 25, 75) # 打印一行空白行
print()
members = [t,s]
for member in members:
member.tell() # code 042 input
def reverse(text):
return text[::-1] #逆向输出所有字符
def is_palindrome(text):
return text == reverse(text) #判断是否是palindrome字符
something = input("Enter text: ")
if is_palindrome(something):
print("Yes, it is a palindrome")
else:
print("No, it is not a palindrome") # code 043 input_exercise
def reverse(text):
return text[::-1] #逆向输出所有字符 def is_palindrome(text):
return text == reverse(text) #判断是否是palindrome字符 something = input("Enter text: ")
if is_palindrome(something):
print("Yes, it is a palindrome")
else:
print("No, it is not a palindrome") # code044 using_file
poem = '''\
Programming is fun
when the work is done
if you wanna make your work also fun:
use python!
'''
#打开文件以编辑
f = open('poem.txt','w')
#向文件中编写文本
f.write(poem)
#关闭文件
f.close() #如果没有特别指定,嘉定启用默认的阅读(‘r’ead模式)
f = open('poem.txt')
while True:
line = f.readline()
#零长度指示EOF
if len(line) == 0:
break
#每行('line')的末尾
#都有换行符
#因它是从一个文件中进行读取的
print(line, end='')
#关闭文件
f.close()
help(open) # code 045 pickle.py
import pickle
#我们存储相关对象的文件的名称
shoplistfile = 'shoplist.data'
#需要购买的物品清单
shoplist = ['apple', 'mango', 'carrot']
#准备写入文件
f = open(shoplistfile, 'wb')
#转移对象至文件
pickle.dump(shoplist, f)
f.close()
#清除shoplist 变量
del shoplist
#重新打开存储文件
f = open(shoplistfile, 'rb')
#从文件中载入对象
storedlist = pickle.load(f)
print(storedlist) # code046 unicode
import io
f = io.open("abc.txt", "wt", encoding="utf-8") #io.open()指明目前正在使用utf-8
f.write(u"Imagine non-English language here")
f.close()
text = io.open("abc.txt", encoding="utf-8").read()
print(text) import io
f = io.open("abc.txt", "wt", encoding="utf-8")
f.write(u"Imagine non-English language here")
f.close() text = io.open("abc.txt", encoding="utf-8").read()
print(text) import io
f = io.open("abc.txt", "wt", encoding=utf-8)
f.write(u"Imagine non-English language here")
f.close() text = io.open("abc.txt",encoding="utf-8").read()
print(text) s = ''
while 1:
t = input("go on(g) or quit(q)\n")
if t != 'q':
name = input('')
pwd = input('')
email = input('')
if len(name) > 20:
name = name[0:20]
if len(pwd) > 20:
pwd = pwd[0:20]
if len(email) > 20:
email = email[0:20]
if t == 'q':
print(s.expandtabs(20), end='')
break
temp = "{0}\t{1}\t{2}\n"
v = temp.format(name,pwd,email)
s = s + v
print(s.expandtabs(20),end='') # code047 exceptions_handle
try:
text = input('Enter something -->')
except EOFError:
print('Why did y do an EOF on me?')
except KeyboardInterrupt:
print('Y cancelled the operation.')
else:
print('y entered {}'.format(text)) # code048 exceptions_raise.py
class shortInputException(Exception):
'''一个由用户定义的异常类'''
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast try:
text = input('Enter something --> ')
if len(text) < 3:
raise ShortInputException(len(text), 3)
except EOFError:
print('Why did y do an EOF on me?')
except ShortInputException as ex:
print(('ShortInputException: The input was ' + '{0} long, expected at least {1}')
.format(ex.length, ex.atleast))
else:
print('No exception was raised.') # code 049 exceptions_finally
import sys
import time f = None
try:
f = open("poem.txt")
while True:
line = f.readline()
if len(line) == 0:
break
print(line, end='')
sys.stdout.flush()
print("Press ctrl+c now")
time.sleep(2)
except IOError:
print("Could not find file poem.txt")
except KeyboardInterrupt:
print("!! You cancelled the reading from the file")
finally:
if f:
f.close()
print("(Cleaning up: Closed the file)") # code050 exceptions_using_with
# with 语句会在代码块开始之前调用 thefile.__enter__ 函数,并且总会在代码块执行完毕之后调
# 用 thefile.__exit__
with open("poem.txt") as f:
for line in f:
print(line, end='')

python简明教程代码的更多相关文章

  1. python简明教程

    Python简明教程 MachinePlay关注 0.7072018.09.26 01:49:43字数 2,805阅读 9,287 Python一小时快速入门 1.Python简介   pylogo. ...

  2. Python 简明教程 --- 3,Python 基础概念

    微信公众号:码农充电站pro 个人主页:https://codeshellme.github.io 控制复杂性是计算机编程的本质. -- Brian Kernighan 了解了如何编写第一个Pytho ...

  3. Python 简明教程 --- 2,第一个Python 程序

    微信公众号:码农充电站pro 个人主页:https://codeshellme.github.io 如果你发现特殊情况太多,那你肯定是用错方法了. -- Carig Zerouni 当你在自己的电脑上 ...

  4. Python 简明教程 --- 18,Python 面向对象

    微信公众号:码农充电站pro 个人主页:https://codeshellme.github.io 代码能借用就借用. -- Tom Duff 目录 编程可分为面向过程编程和面向对象编程,它们是两种不 ...

  5. Python 简明教程 --- 13,Python 集合

    微信公众号:码农充电站pro 个人主页:https://codeshellme.github.io 如果代码和注释不一致,那很可能两者都错了. -- Norm Schryer 目录 前几节我们已经介绍 ...

  6. Python 简明教程 --- 14,Python 数据结构进阶

    微信公众号:码农充电站pro 个人主页:https://codeshellme.github.io 如果你发现特殊情况太多,那很可能是用错算法了. -- Carig Zerouni 目录 前几节我们介 ...

  7. Python 简明教程 --- 15,Python 函数

    微信公众号:码农充电站pro 个人主页:https://codeshellme.github.io 测试只能证明程序有错误,而不能证明程序没有错误. -- Edsger Dijkstra 目录 本节我 ...

  8. Python 简明教程 --- 17,Python 模块与包

    微信公众号:码农充电站pro 个人主页:https://codeshellme.github.io 正确的判断来源于经验,然而经验来源于错误的判断. -- Fred Brooks 目录 我们已经知道函 ...

  9. Python 简明教程 --- 8,Python 字符串函数

    微信公众号:码农充电站pro 个人主页:https://codeshellme.github.io 好代码本身就是最好的文档.当你需要添加一个注释时,你应该考虑如何修改代码才能不需要注释. -- St ...

随机推荐

  1. 关于windows映射网络驱动器,登录时重新连接

    如果想登录系统后映射盘符还在,但是不自动连接,则参考下面方法.方法其实很简单,关键的步骤是:登录共享的时候,登录界面取消选中“保存凭据”,然后映射的时候,选择“下次开机是重新连接” 这样,下次开机的时 ...

  2. 【javascript小案例】从0开始实现一个俄罗斯方块

    写在前面得话: 这篇文章主要记录了我是怎么一步一步写出俄罗斯方块,整个代码用的函数编程,主要是为了让一些不熟悉es6, 面向对象写法得 新手能更容易看明白,全部得代码中都是一些js的基础知识,很容易理 ...

  3. python 语法的一些特性记录

    装饰器@符号 装饰器本质上是一个 Python 函数或类,它可以让其他函数或类在不需要做任何代码修改的前提下增加额外功能,装饰器的返回值也是一个函数/类对象.它经常用于有切面需求的场景,比如:插入日志 ...

  4. logback-MDC日志唯一标识

    自定义LogbackFilter: import org.slf4j.MDC; import javax.servlet.*; import javax.servlet.annotation.WebF ...

  5. 【笔记】.NET开发环境下使用PostgreSQL+Oracle_fdw 实现两个数据库之间数据交互操作(二)

    一 新的可视化工具 因为前文所提到的,看不到外部服务器和外部表的问题,我更换了可视化工具. 好用的新工具PostgreSQL Maestro! 当然如此好用的工具不是免费的,如果想免费使用还请自己去找 ...

  6. 神州数码DEIGRP路由协议配置

    实验要求:了解DEIGRP及其配置方法 拓扑如下 R1 enable 进入特权模式 config 进入全局模式 hostname R1 修改名称 interface l0 进入端口 ip addres ...

  7. 从hivesql结果中读取数值到shell变量的方法

    为了检查hive表中的数据,并统计展现,需要将查出的结果传入到shell变量,然后统一输出到文本. 最后使用了以下两个方法: 方法一 QUAN=$(hive -S -e "select co ...

  8. webpack根据开发与生产环境配置不同变量--webpack.DefinePlugin

    webpack有一个DefinePlugin接口,可以实现根据开发与生产环境配置不同变量.范例如下: 需求:开发环境请求baseUrl = '':生产环境请求 baseUrl = 'http://lo ...

  9. 关于OSI

    OSI模型,即开放式通信系统互联参考模型(Open System Interconnection,OSI/RM,Open Systems Interconnection Reference Model ...

  10. Java程序第二次作业

    1.编写“人”类及其测试类.1.1 “人”类: 类名:Person 属性:姓名.性别.年龄.身份证号码 方法:在控制台输出各个信息1.2 测试类 类名:TestPerson 方法:main ...