python简明教程所有代码

#!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 break
# print('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__ = '1'

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': '[email protected]',
    'Larry': '[email protected]',
    'Matsumoto': '[email protected]',
    'Spammer': '[email protected]',
    'Guido' : '[email protected]'
}

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'] = '[email protected]'
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='')

猜你喜欢

转载自www.cnblogs.com/yuyukun/p/10177163.html