A byte of Python

A byte of Python

To know the basic of Python

listing 5.1 while loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
number = 23
running = True

while(running):
guess = int(input('Enter an integer:'))

if guess == number:
print("Congratulations, you guessed it .")
print("but you do not win any prizes!")
running = False
elif guess < number:
print("No it is a litter higher than that")
else:
print("No it is a little lower than that")
else:
print('Done')

listing 5.2 for loop

1
2
3
4
for i in range(1,5):
print(i)
else:
print('the for loop is over')

listing break statement

1
2
3
4
5
6
while(True):
s = input('Enter something:')
if(s=='quit'):
break
print('Length of the string is',len(s))
print('Done')

listing 5.4 continue

1
2
3
4
5
6
7
8
9
10
while(True):
s = input('Enter something:')
if(s=='quit'):
break
if len(s)<3:
print('Input is of sufficient length')
continue

print('Length of the string is',len(s))
print('Done')

listing 5.5 python

1
2
3
4
5
6
7
8
9
10
11
def sayHello():
print('Hello,World')
#block belonging to the function

#call the function
sayHello()

#you cant define synNo after sayNo() call
def sayNo():
print('No No')
sayNo()

listing 7.2 using function x para

1
2
3
4
5
6
7
8
9
10
def printMax(a,b):
if(a>b):
print(a,'is maximum')
else:
print(b,'is maximum')

printMax(3,4)
x = 5
y = 7
printMax(x,y)

listing 7.3 using local variable

1
2
3
4
5
6
7
8
9
def func(x):
print('x is ', x)
x = 2
print('changed local x to ',x)

x = 50
func(x)

print('x is still',x)

listing 7.4 using global statement

1
2
3
4
5
6
7
8
9
def globalF():
global x
print('x is ',x)
x=2
print('changed local x to ',x)

x = 50
globalF()
print('Value of x is',x)

listing 7.5 using default paras

1
2
3
4
5
def say(message,times = 1):
print(message * times)
say("Hello")
say("World",5)
#console : Hello WorldWorldWorldWorldWorld

listing 7.6 use key para

1
2
3
4
5
6
7
8
9
10
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)

#a is 3 and b is 7 and c is 10
#a is 25 and b is 5 and c is 24
#a is 100 and b is 5 and c is 50

listing 7.7 use return

1
2
3
4
5
6
7
def maximum(x,y):
if x>y:
return x
else:
return y

print(maximum(2,3))

listing 7.8

1
2
def someFuntion():
pass

listing 7.9 docStrings

1
2
3
4
5
6
7
8
9
10
11
12
13
def printMax(x,y):
'Prints the maximum of two numbers\
The two values must be integers'
x = int(x)
y = int(y)

if(x>y):
print(x,'is Max')
else:
print(y,'is Max')

printMax(3,5)
print (printMax.__doc__)

listing 8.1 using System module

1
2
3
4
5
6
import sys
print('the command line arguments are:')
for i in sys.argv:
print(i)

print ('\n\nthe python paht is ',sys.path)

listing 8.2 using module name

1
2
3
4
if(__name__=='__main__'):
print('This program is being run by itself')
else:
print('i am being imported from another module')

listing 8.3 how to use module

1
2
3
4
5
6
7
8
9
10
11
12
#mymodule.py
def sayHi():
print('Hi , this is my module speaking')

version = '0.1'
#End of my module.py

#usemymodule.py
import mymodule

mymodule.sayHi();
print('Version ',mymodule.version)

listing 8.4 dir()

1
2
3
4
5
6
7
8
$python
>>>import sys
>>>dir(sys)
>>>dir()
>>>a = 5
>>>dir()
>>>del a
>>>dir()

listing 8.5 list()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# this is my shopping list
shoplist = ["apple","mango","carrot","banana"]
print("I have",len(shoplist),"items to purchase.")
print("These items are:")
for item in shoplist:
print(item)
print("\n I 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("The first item I will buy is ", shoplist[0])
olditem = shoplist[0]
del shoplist[0]
print("I bought the ",olditem)
print("My shopping list is now ",shoplist)

listing 8.6 tuple

1
2
3
4
5
6
7
8
zoo = ("wolf", "elephant", "penguin")
print("number of animals in the zoo is ", len(zoo))

new_zoo = ("monkey", "dolphin", zoo)
print("number of animals in the new zoo is",len(new_zoo))
print("all in new zoo", new_zoo)
print("form old zoo", new_zoo[2])
print("last animal brought from old zoo is ", new_zoo[2][2])

listing 8.7 using tuple output

1
age = 22

listing 8.8 using dict

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# using _dict.py
ab = { 'Swaroop':'swaroopch@byteofpython.info',
'Larry':'larry@wall.org',
'Matsumoto':'matz@ruby-lang.org',
'Spammer': 'spammer@hotmail.com'
}

print("Swaroop s address is % ",ab['Swaroop'])

ab['Guido'] = 'guido@python.org'
del ab["Spammer"]
print("----------There are " ,len(ab))
for name,address in ab.items():
print("Contact sta ",name,address)

if 'Guido' in ab:
print("Guido address is ", ab['Guido'])

using seq

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#Filename: seq.py
shoplist =['aple','mango','carrot','banana']
#Indexing or 'Subscription' operation
print("item -0- ",shoplist[0])
print("item -1- ",shoplist[1])
print("item -2- ",shoplist[2])
print("item -3- ",shoplist[3])
print("item --1- ",shoplist[-1])
print("item --2- ",shoplist[-2])

#Slicing on a list
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[:])

#Slicing on a string
name = 'swaroop'
print('characters 1 to 3 is ',name[1:3])
print('characters 2 to end is',name[2:])
print('characters 1 ~ -1 is ',name[1:-1])
print('characters start to end is ',name[:])

listing 9.6 using object and reference

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# reference
print("Simple assignment")
shoplist =['apple','mango','carrot','banana']
mylist = shoplist

del shoplist[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)

实际上就是一个是引用类型,一个是新对象?如果想要

listing 9.7 str methods

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# str_methods.py

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 = '_*_'
mylist =['Brazil','Russia','India','China']
print (delimiter.join(mylist))

listing 11.1 use class

1
2
3
4
5
6
#simple class .py
class Person:
pass

p = Person()
print(p)

listing 11.2 use object method

1
2
3
4
5
6
7
8
9
#method.py
class Person:
def sayHi(self):
print('Hello,how are you?')

p = Person()
p.sayHi()
Person().sayHi()
#Person().sayHi()

listing 11.3 using init

1
2
3
4
5
6
7
8
9
class Person:
def __init__(self,name):
self.name = name
def sayHi(self):
print('Hello,my name is ',self.name)

p = Person("Harry")
p.sayHi()
Person('Swaroop').sayHi()

listing 11.4 use class and object var

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#objvar.py
class Person:
"Represents a person."
population =0

def __init__(self,name):
'Initializes the Persons data'
self.name = name
print('Initializing %s' % self.name)
Person.population +=1

def __del__(self):
'I am dying'
print('%s says bye ' % self.name)
Person.population -=1
if Person.population == 0:
print('I am the last one')
else:
print('The is still %d' % Person.population)
def sayHi(self):
'Gretting by the person'
print('Hi , my name is %s' % self.name)

def howMany(self):
if Person.population == 1:
print('Iam the last person here')
else:
print('We have %d Persons here' % Person.population)

swaroop = Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()

kalam = Person('Abdul Kalam')
kalam.sayHi()
kalam.howMany()

swaroop.sayHi()
swaroop.howMany()

继承

listing 11.1 use inherit

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#inherit.py
class SchoolMember:
'Represents any school member'
def __init__(self,name,age):
self.name = name
self.age = age
print('Initialized School Member: %s' % self.name)

def tell(self):
'Tell my details'
print('Name: "%s" Age: "%s"'% (self.name,self.age))

class Teacher(SchoolMember):
'Represents a teacher.'
def __init__(self,name,age,salary):
SchoolMember.__init__(self,name,age)
self.salary = salary
print('Initialized Teacher: %s' % self.name)

def tell(self):
SchoolMember.tell(self)
print('Salary: %d' % self.salary)

class Student(SchoolMember):
'''Represents a student'''
def __init__(self,name,age,marks):
SchoolMember.__init__(self,name,age)
self.marks = marks
print('Initialized Student: %s ' % self.name)

def tell(self):
SchoolMember.tell(self)
print('Marks: %d' %self.marks)

t = Teacher('Mrs.Shrividya',40,300000)
s = Student('Swaroop',22,76)

print()
members = [t,s]
for member in members:
member.tell()

文件IO

listing 12.1 use_file.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#using_file.py
poem ='''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use PyCharm!
'''

f = open('poem.txt','w') #open for writing
f.write(poem)
f.close()

f = open('poem.txt')
#if no mode is specified ,'r'ead mode is assumed by default
while True:
line = f.readline()
if len(line) == 0: #zero length indicates EOF
break
print(line),
#Notice comma to avoid automatic newline added by Python
f.close()
#close the file

数据持久化 cPickle

listing Save and load

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#Filename:pickling.py
import _pickle as p

shoplistfile = 'shoplist.data'
# the name of the file where we will store the object
shoplist = ['apple','mango','carrot']

#write to the file
f = open(shoplistfile,'wb')
p.dump(shoplist,f,-1)
p.dump(shoplist,f)
f.close()

del shoplist #remove the shoplist

# Read back from the storage
f = open(shoplistfile,'rb')
storedlist = p.load(f)
print(storedlist)

list 13.1 try catch

1
2
3
4
5
6
7
8
try:
fh = open("testfile", "w")
fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
print('no found')
else:
print("write success")
fh.close()

listing 13.2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#filename: raising.py
import sys

class ShortInputException(Exception):
'''A user-defined exception class'''
def __init__(self,length,atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast

try:
s = input("Enter Something-->")
if len(s) < 3:
raise ShortInputException(len(s),3)
except EOFError:
print('\nWhy did you do an EOF on me')
except ShortInputException:
print('Short Input Exception: the input is ')
else:
print('No exceptin was raised')

listing 13.3 use finally

1
2
3
4
5
6
7
8
9
10
11
12
import time
try:
f = open('poem.txt')
while True:
line = f.readline()
if len(line) ==0:
break;
time.sleep(2)
print(line)
finally:
f.close()
print('Cleaning up ... closed the file')

listing 14.1 use sys.argv

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# filename: cat.py
import sys


def readfile(_filename):
"""print a file to the standard output"""
f = open(_filename)
while True:
line = f.readline()
if len(line) == 0:
break
print(line)
f.close()
# Script starts from here


if len(sys.argv) < 2:
print('No action specified')
sys.exit()
if sys.argv[1].startswith('--'):
option = sys.argv[1][2:]
if option == 'version' :
print('Version 1.2')
elif option == 'help':
print('''This program prints files to the standard output
Any number of files can be specified
Options include:
--version: Prints the version number
--help : display this help''')
else:
print("Unknown option")
sys.exit()
else:
for filename in sys.argv[1:]:
readfile(filename)

listing extra uss sys.argv in C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
namespace hohoho
{
public class ccc
{
static void Main(string[] args)
{
for (int i = 0; i < args.Length; i++)
{
if(args[i].StartsWith("--"))
{
switch (args[i])
{
case "--version" :
System.Console.WriteLine("ccc version: 1.20");
break;
case "--dd" :
System.Console.WriteLine("I love dd forever");
break;
default:
break;
}
}else
{
continue;
}
}
if (args.Length == 0)
{
System.Console.WriteLine("Nonsence");
}
}
}
}

listing 15.1 use comprehension

1
2
3
4
# filename: list_comprehension.py
_listOne = [2, 3, 4]
_listTwo = [2 * i for i in _listOne if i > 2]
print(_listTwo)

listing 15.2 use lambda

1
2
3
4
5
6
7
8
9
# filename: use lambda
def make_repeater(n):
return lambda s: s * n


twice = make_repeater(2)

print(twice('world'))
print(twice(5))

只能使用表达式在lambda中