py
https://github.com/kindsof/flask-vue-word-cloud
https://dormousehole.readthedocs.io/en/latest/quickstart.html
100+ Python challenging programming exercises
1. Level description
Level Description
Level 1 Beginner means someone who has just gone through an introductory Python course. He can solve some problems with 1 or 2 Python classes or functions. Normally, the answers could directly be found in the textbooks.
Level 2 Intermediate means someone who has just learned Python, but already has a relatively strong programming background from before. He should be able to solve problems which may involve 3 or 3 Python classes or functions. The answers cannot be directly be found in the textbooks.
Level 3 Advanced. He should use Python to solve more complex problem using more rich libraries functions and data structures and algorithms. He is supposed to solve the problem using several Python standard packages and advanced techniques.
2. Problem template
#----------------------------------------#
Question
Hints
Solution
3. Questions
#----------------------------------------#
Question 1
Level 1
Question:
Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5,
between 2000 and 3200 (both included).
The numbers obtained should be printed in a comma-separated sequence on a single line.
Hints:
Consider use range(#begin, #end) method
Solution:
l=[]
for i in range(2000, 3201):
if (i%7==0) and (i%5!=0):
l.append(str(i))
print ','.join(l)
#----------------------------------------#
#----------------------------------------#
Question 2
Level 1
Question:
Write a program which can compute the factorial of a given numbers.
The results should be printed in a comma-separated sequence on a single line.
Suppose the following input is supplied to the program:
8
Then, the output should be:
40320
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
def fact(x):
if x == 0:
return 1
return x * fact(x - 1)
x=int(raw_input())
print fact(x)
#----------------------------------------#
#----------------------------------------#
Question 3
Level 1
Question:
With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary.
Suppose the following input is supplied to the program:
8
Then, the output should be:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Consider use dict()
Solution:
n=int(raw_input())
d=dict()
for i in range(1,n+1):
d[i]=i*i
print d
#----------------------------------------#
#----------------------------------------#
Question 4
Level 1
Question:
Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number.
Suppose the following input is supplied to the program:
34,67,55,33,12,98
Then, the output should be:
['34', '67', '55', '33', '12', '98']
('34', '67', '55', '33', '12', '98')
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
tuple() method can convert list to tuple
Solution:
values=raw_input()
l=values.split(",")
t=tuple(l)
print l
print t
#----------------------------------------#
#----------------------------------------#
Question 5
Level 1
Question:
Define a class which has at least two methods:
getString: to get a string from console input
printString: to print the string in upper case.
Also please include simple test function to test the class methods.
Hints:
Use __init__ method to construct some parameters
Solution:
class InputOutString(object):
def __init__(self):
self.s = ""
def getString(self):
self.s = raw_input()
def printString(self):
print self.s.upper()
strObj = InputOutString()
strObj.getString()
strObj.printString()
#----------------------------------------#
#----------------------------------------#
Question 6
Level 2
Question:
Write a program that calculates and prints the value according to the given formula:
Q = Square root of [(2 * C * D)/H]
Following are the fixed values of C and H:
C is 50. H is 30.
D is the variable whose values should be input to your program in a comma-separated sequence.
Example
Let us assume the following comma separated input sequence is given to the program:
100,150,180
The output of the program should be:
18,22,24
Hints:
If the output received is in decimal form, it should be rounded off to its nearest value (for example, if the output received is 26.0, it should be printed as 26)
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
#!/usr/bin/env python
import math
c=50
h=30
value = []
items=[x for x in raw_input().split(',')]
for d in items:
value.append(str(int(round(math.sqrt(2*c*float(d)/h)))))
print ','.join(value)
#----------------------------------------#
#----------------------------------------#
Question 7
Level 2
Question:
Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j.
Note: i=0,1.., X-1; j=0,1,¡Y-1.
Example
Suppose the following inputs are given to the program:
3,5
Then, the output of the program should be:
[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]
Hints:
Note: In case of input data being supplied to the question, it should be assumed to be a console input in a comma-separated form.
Solution:
input_str = raw_input()
dimensions=[int(x) for x in input_str.split(',')]
rowNum=dimensions[0]
colNum=dimensions[1]
multilist = [[0 for col in range(colNum)] for row in range(rowNum)]
for row in range(rowNum):
for col in range(colNum):
multilist[row][col]= row*col
print multilist
#----------------------------------------#
#----------------------------------------#
Question 8
Level 2
Question:
Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically.
Suppose the following input is supplied to the program:
without,hello,bag,world
Then, the output should be:
bag,hello,without,world
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
items=[x for x in raw_input().split(',')]
items.sort()
print ','.join(items)
#----------------------------------------#
#----------------------------------------#
Question 9
Level 2
Question£º
Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized.
Suppose the following input is supplied to the program:
Hello world
Practice makes perfect
Then, the output should be:
HELLO WORLD
PRACTICE MAKES PERFECT
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
lines = []
while True:
s = raw_input()
if s:
lines.append(s.upper())
else:
break;
for sentence in lines:
print sentence
#----------------------------------------#
#----------------------------------------#
Question 10
Level 2
Question:
Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically.
Suppose the following input is supplied to the program:
hello world and practice makes perfect and hello world again
Then, the output should be:
again and hello makes perfect practice world
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
We use set container to remove duplicated data automatically and then use sorted() to sort the data.
Solution:
s = raw_input()
words = [word for word in s.split(" ")]
print " ".join(sorted(list(set(words))))
#----------------------------------------#
#----------------------------------------#
Question 11
Level 2
Question:
Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence.
Example:
0100,0011,1010,1001
Then the output should be:
1010
Notes: Assume the data is input by console.
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
value = []
items=[x for x in raw_input().split(',')]
for p in items:
intp = int(p, 2)
if not intp%5:
value.append(p)
print ','.join(value)
#----------------------------------------#
#----------------------------------------#
Question 12
Level 2
Question:
Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number.
The numbers obtained should be printed in a comma-separated sequence on a single line.
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
values = []
for i in range(1000, 3001):
s = str(i)
if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0):
values.append(s)
print ",".join(values)
#----------------------------------------#
#----------------------------------------#
Question 13
Level 2
Question:
Write a program that accepts a sentence and calculate the number of letters and digits.
Suppose the following input is supplied to the program:
hello world! 123
Then, the output should be:
LETTERS 10
DIGITS 3
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
s = raw_input()
d={"DIGITS":0, "LETTERS":0}
for c in s:
if c.isdigit():
d["DIGITS"]+=1
elif c.isalpha():
d["LETTERS"]+=1
else:
pass
print "LETTERS", d["LETTERS"]
print "DIGITS", d["DIGITS"]
#----------------------------------------#
#----------------------------------------#
Question 14
Level 2
Question:
Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters.
Suppose the following input is supplied to the program:
Hello world!
Then, the output should be:
UPPER CASE 1
LOWER CASE 9
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
s = raw_input()
d={"UPPER CASE":0, "LOWER CASE":0}
for c in s:
if c.isupper():
d["UPPER CASE"]+=1
elif c.islower():
d["LOWER CASE"]+=1
else:
pass
print "UPPER CASE", d["UPPER CASE"]
print "LOWER CASE", d["LOWER CASE"]
#----------------------------------------#
#----------------------------------------#
Question 15
Level 2
Question:
Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a.
Suppose the following input is supplied to the program:
9
Then, the output should be:
11106
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
a = raw_input()
n1 = int( "%s" % a )
n2 = int( "%s%s" % (a,a) )
n3 = int( "%s%s%s" % (a,a,a) )
n4 = int( "%s%s%s%s" % (a,a,a,a) )
print n1+n2+n3+n4
#----------------------------------------#
#----------------------------------------#
Question 16
Level 2
Question:
Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers.
Suppose the following input is supplied to the program:
1,2,3,4,5,6,7,8,9
Then, the output should be:
1,3,5,7,9
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
values = raw_input()
numbers = [x for x in values.split(",") if int(x)%2!=0]
print ",".join(numbers)
#----------------------------------------#
Question 17
Level 2
Question:
Write a program that computes the net amount of a bank account based a transaction log from console input. The transaction log format is shown as following:
D 100
W 200
D means deposit while W means withdrawal.
Suppose the following input is supplied to the program:
D 300
D 300
W 200
D 100
Then, the output should be:
500
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
netAmount = 0
while True:
s = raw_input()
if not s:
break
values = s.split(" ")
operation = values[0]
amount = int(values[1])
if operation=="D":
netAmount+=amount
elif operation=="W":
netAmount-=amount
else:
pass
print netAmount
#----------------------------------------#
#----------------------------------------#
Question 18
Level 3
Question:
A website requires the users to input username and password to register. Write a program to check the validity of password input by users.
Following are the criteria for checking the password:
1. At least 1 letter between [a-z]
2. At least 1 number between [0-9]
1. At least 1 letter between [A-Z]
3. At least 1 character from [$#@]
4. Minimum length of transaction password: 6
5. Maximum length of transaction password: 12
Your program should accept a sequence of comma separated passwords and will check them according to the above criteria. Passwords that match the criteria are to be printed, each separated by a comma.
Example
If the following passwords are given as input to the program:
ABd1234@1,a F1#,2w3E*,2We3345
Then, the output of the program should be:
ABd1234@1
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solutions:
import re
value = []
items=[x for x in raw_input().split(',')]
for p in items:
if len(p)<6 or len(p)>12:
continue
else:
pass
if not re.search("[a-z]",p):
continue
elif not re.search("[0-9]",p):
continue
elif not re.search("[A-Z]",p):
continue
elif not re.search("[$#@]",p):
continue
elif re.search("\s",p):
continue
else:
pass
value.append(p)
print ",".join(value)
#----------------------------------------#
#----------------------------------------#
Question 19
Level 3
Question:
You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string, age and height are numbers. The tuples are input by console. The sort criteria is:
1: Sort based on name;
2: Then sort based on age;
3: Then sort by score.
The priority is that name > age > score.
If the following tuples are given as input to the program:
Tom,19,80
John,20,90
Jony,17,91
Jony,17,93
Json,21,85
Then, the output of the program should be:
[('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')]
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
We use itemgetter to enable multiple sort keys.
Solutions:
from operator import itemgetter, attrgetter
l = []
while True:
s = raw_input()
if not s:
break
l.append(tuple(s.split(",")))
print sorted(l, key=itemgetter(0,1,2))
#----------------------------------------#
#----------------------------------------#
Question 20
Level 3
Question:
Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n.
Hints:
Consider use yield
Solution:
def putNumbers(n):
i = 0
while i<n:
j=i
i=i+1
if j%7==0:
yield j
for i in reverse(100):
print i
#----------------------------------------#
#----------------------------------------#
Question 21
Level 3
Question£º
A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following:
UP 5
DOWN 3
LEFT 3
RIGHT 2
¡
The numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer.
Example:
If the following tuples are given as input to the program:
UP 5
DOWN 3
LEFT 3
RIGHT 2
Then, the output of the program should be:
2
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
import math
pos = [0,0]
while True:
s = raw_input()
if not s:
break
movement = s.split(" ")
direction = movement[0]
steps = int(movement[1])
if direction=="UP":
pos[0]+=steps
elif direction=="DOWN":
pos[0]-=steps
elif direction=="LEFT":
pos[1]-=steps
elif direction=="RIGHT":
pos[1]+=steps
else:
pass
print int(round(math.sqrt(pos[1]**2+pos[0]**2)))
#----------------------------------------#
#----------------------------------------#
Question 22
Level 3
Question:
Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically.
Suppose the following input is supplied to the program:
New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.
Then, the output should be:
2:2
3.:1
3?:1
New:1
Python:5
Read:1
and:1
between:1
choosing:1
or:2
to:1
Hints
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
freq = {} # frequency of words in text
line = raw_input()
for word in line.split():
freq[word] = freq.get(word,0)+1
words = freq.keys()
words.sort()
for w in words:
print "%s:%d" % (w,freq[w])
#----------------------------------------#
#----------------------------------------#
Question 23
level 1
Question:
Write a method which can calculate square value of number
Hints:
Using the ** operator
Solution:
def square(num):
return num ** 2
print square(2)
print square(3)
#----------------------------------------#
#----------------------------------------#
Question 24
Level 1
Question:
Python has many built-in functions, and if you do not know how to use it, you can read document online or find some books. But Python has a built-in document function for every built-in functions.
Please write a program to print some Python built-in functions documents, such as abs(), int(), raw_input()
And add document for your own function
Hints:
The built-in document method is __doc__
Solution:
print abs.__doc__
print int.__doc__
print raw_input.__doc__
def square(num):
'''Return the square value of the input number.
The input number must be integer.
'''
return num ** 2
print square(2)
print square.__doc__
#----------------------------------------#
#----------------------------------------#
Question 25
Level 1
Question:
Define a class, which have a class parameter and have a same instance parameter.
Hints:
Define a instance parameter, need add it in __init__ method
You can init a object with construct parameter or set the value later
Solution:
class Person:
# Define the class parameter "name"
name = "Person"
def __init__(self, name = None):
# self.name is the instance parameter
self.name = name
jeffrey = Person("Jeffrey")
print "%s name is %s" % (Person.name, jeffrey.name)
nico = Person()
nico.name = "Nico"
print "%s name is %s" % (Person.name, nico.name)
#----------------------------------------#
#----------------------------------------#
Question:
Define a function which can compute the sum of two numbers.
Hints:
Define a function with two numbers as arguments. You can compute the sum in the function and return the value.
Solution
def SumFunction(number1, number2):
return number1+number2
print SumFunction(1,2)
#----------------------------------------#
Question:
Define a function that can convert a integer into a string and print it in console.
Hints:
Use str() to convert a number to string.
Solution
def printValue(n):
print str(n)
printValue(3)
#----------------------------------------#
Question:
Define a function that can convert a integer into a string and print it in console.
Hints:
Use str() to convert a number to string.
Solution
def printValue(n):
print str(n)
printValue(3)
#----------------------------------------#
2.10
Question:
Define a function that can receive two integral numbers in string form and compute their sum and then print it in console.
Hints:
Use int() to convert a string to integer.
Solution
def printValue(s1,s2):
print int(s1)+int(s2)
printValue("3","4") #7
#----------------------------------------#
2.10
Question:
Define a function that can accept two strings as input and concatenate them and then print it in console.
Hints:
Use + to concatenate the strings
Solution
def printValue(s1,s2):
print s1+s2
printValue("3","4") #34
#----------------------------------------#
2.10
Question:
Define a function that can accept two strings as input and print the string with maximum length in console. If two strings have the same length, then the function should print al l strings line by line.
Hints:
Use len() function to get the length of a string
Solution
def printValue(s1,s2):
len1 = len(s1)
len2 = len(s2)
if len1>len2:
print s1
elif len2>len1:
print s2
else:
print s1
print s2
printValue("one","three")
#----------------------------------------#
2.10
Question:
Define a function that can accept an integer number as input and print the "It is an even number" if the number is even, otherwise print "It is an odd number".
Hints:
Use % operator to check if a number is even or odd.
Solution
def checkValue(n):
if n%2 == 0:
print "It is an even number"
else:
print "It is an odd number"
checkValue(7)
#----------------------------------------#
2.10
Question:
Define a function which can print a dictionary where the keys are numbers between 1 and 3 (both included) and the values are square of keys.
Hints:
Use dict[key]=value pattern to put entry into a dictionary.
Use ** operator to get power of a number.
Solution
def printDict():
d=dict()
d[1]=1
d[2]=2**2
d[3]=3**2
print d
printDict()
#----------------------------------------#
2.10
Question:
Define a function which can print a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys.
Hints:
Use dict[key]=value pattern to put entry into a dictionary.
Use ** operator to get power of a number.
Use range() for loops.
Solution
def printDict():
d=dict()
for i in range(1,21):
d[i]=i**2
print d
printDict()
#----------------------------------------#
2.10
Question:
Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the values only.
Hints:
Use dict[key]=value pattern to put entry into a dictionary.
Use ** operator to get power of a number.
Use range() for loops.
Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs.
Solution
def printDict():
d=dict()
for i in range(1,21):
d[i]=i**2
for (k,v) in d.items():
print v
printDict()
#----------------------------------------#
2.10
Question:
Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the keys only.
Hints:
Use dict[key]=value pattern to put entry into a dictionary.
Use ** operator to get power of a number.
Use range() for loops.
Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs.
Solution
def printDict():
d=dict()
for i in range(1,21):
d[i]=i**2
for k in d.keys():
print k
printDict()
#----------------------------------------#
2.10
Question:
Define a function which can generate and print a list where the values are square of numbers between 1 and 20 (both included).
Hints:
Use ** operator to get power of a number.
Use range() for loops.
Use list.append() to add values into a list.
Solution
def printList():
li=list()
for i in range(1,21):
li.append(i**2)
print li
printList()
#----------------------------------------#
2.10
Question:
Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the first 5 elements in the list.
Hints:
Use ** operator to get power of a number.
Use range() for loops.
Use list.append() to add values into a list.
Use [n1:n2] to slice a list
Solution
def printList():
li=list()
for i in range(1,21):
li.append(i**2)
print li[:5]
printList()
#----------------------------------------#
2.10
Question:
Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the last 5 elements in the list.
Hints:
Use ** operator to get power of a number.
Use range() for loops.
Use list.append() to add values into a list.
Use [n1:n2] to slice a list
Solution
def printList():
li=list()
for i in range(1,21):
li.append(i**2)
print li[-5:]
printList()
#----------------------------------------#
2.10
Question:
Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print all values except the first 5 elements in the list.
Hints:
Use ** operator to get power of a number.
Use range() for loops.
Use list.append() to add values into a list.
Use [n1:n2] to slice a list
Solution
def printList():
li=list()
for i in range(1,21):
li.append(i**2)
print li[5:]
printList()
#----------------------------------------#
2.10
Question:
Define a function which can generate and print a tuple where the value are square of numbers between 1 and 20 (both included).
Hints:
Use ** operator to get power of a number.
Use range() for loops.
Use list.append() to add values into a list.
Use tuple() to get a tuple from a list.
Solution
def printTuple():
li=list()
for i in range(1,21):
li.append(i**2)
print tuple(li)
printTuple()
#----------------------------------------#
2.10
Question:
With a given tuple (1,2,3,4,5,6,7,8,9,10), write a program to print the first half values in one line and the last half values in one line.
Hints:
Use [n1:n2] notation to get a slice from a tuple.
Solution
tp=(1,2,3,4,5,6,7,8,9,10)
tp1=tp[:5]
tp2=tp[5:]
print tp1
print tp2
#----------------------------------------#
2.10
Question:
Write a program to generate and print another tuple whose values are even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10).
Hints:
Use "for" to iterate the tuple
Use tuple() to generate a tuple from a list.
Solution
tp=(1,2,3,4,5,6,7,8,9,10)
li=list()
for i in tp:
if tp[i]%2==0:
li.append(tp[i])
tp2=tuple(li)
print tp2
#----------------------------------------#
2.14
Question:
Write a program which accepts a string as input to print "Yes" if the string is "yes" or "YES" or "Yes", otherwise print "No".
Hints:
Use if statement to judge condition.
Solution
s= raw_input()
if s=="yes" or s=="YES" or s=="Yes":
print "Yes"
else:
print "No"
#----------------------------------------#
3.4
Question:
Write a program which can filter even numbers in a list by using filter function. The list is: [1,2,3,4,5,6,7,8,9,10].
Hints:
Use filter() to filter some elements in a list.
Use lambda to define anonymous functions.
Solution
li = [1,2,3,4,5,6,7,8,9,10]
evenNumbers = filter(lambda x: x%2==0, li)
print evenNumbers
#----------------------------------------#
3.4
Question:
Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10].
Hints:
Use map() to generate a list.
Use lambda to define anonymous functions.
Solution
li = [1,2,3,4,5,6,7,8,9,10]
squaredNumbers = map(lambda x: x**2, li)
print squaredNumbers
#----------------------------------------#
3.5
Question:
Write a program which can map() and filter() to make a list whose elements are square of even number in [1,2,3,4,5,6,7,8,9,10].
Hints:
Use map() to generate a list.
Use filter() to filter elements of a list.
Use lambda to define anonymous functions.
Solution
li = [1,2,3,4,5,6,7,8,9,10]
evenNumbers = map(lambda x: x**2, filter(lambda x: x%2==0, li))
print evenNumbers
#----------------------------------------#
3.5
Question:
Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included).
Hints:
Use filter() to filter elements of a list.
Use lambda to define anonymous functions.
Solution
evenNumbers = filter(lambda x: x%2==0, range(1,21))
print evenNumbers
#----------------------------------------#
3.5
Question:
Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included).
Hints:
Use map() to generate a list.
Use lambda to define anonymous functions.
Solution
squaredNumbers = map(lambda x: x**2, range(1,21))
print squaredNumbers
#----------------------------------------#
7.2
Question:
Define a class named American which has a static method called printNationality.
Hints:
Use @staticmethod decorator to define class static method.
Solution
class American(object):
@staticmethod
def printNationality():
print "America"
anAmerican = American()
anAmerican.printNationality()
American.printNationality()
#----------------------------------------#
7.2
Question:
Define a class named American and its subclass NewYorker.
Hints:
Use class Subclass(ParentClass) to define a subclass.
Solution:
class American(object):
pass
class NewYorker(American):
pass
anAmerican = American()
aNewYorker = NewYorker()
print anAmerican
print aNewYorker
#----------------------------------------#
7.2
Question:
Define a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area.
Hints:
Use def methodName(self) to define a method.
Solution:
class Circle(object):
def __init__(self, r):
self.radius = r
def area(self):
return self.radius**2*3.14
aCircle = Circle(2)
print aCircle.area()
#----------------------------------------#
7.2
Define a class named Rectangle which can be constructed by a length and width. The Rectangle class has a method which can compute the area.
Hints:
Use def methodName(self) to define a method.
Solution:
class Rectangle(object):
def __init__(self, l, w):
self.length = l
self.width = w
def area(self):
return self.length*self.width
aRectangle = Rectangle(2,10)
print aRectangle.area()
#----------------------------------------#
7.2
Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as argument. Both classes have a area function which can print the area of the shape where Shape's area is 0 by default.
Hints:
To override a method in super class, we can define a method with the same name in the super class.
Solution:
class Shape(object):
def __init__(self):
pass
def area(self):
return 0
class Square(Shape):
def __init__(self, l):
Shape.__init__(self)
self.length = l
def area(self):
return self.length*self.length
aSquare= Square(3)
print aSquare.area()
#----------------------------------------#
Please raise a RuntimeError exception.
Hints:
Use raise() to raise an exception.
Solution:
raise RuntimeError('something wrong')
#----------------------------------------#
Write a function to compute 5/0 and use try/except to catch the exceptions.
Hints:
Use try/except to catch exceptions.
Solution:
def throws():
return 5/0
try:
throws()
except ZeroDivisionError:
print "division by zero!"
except Exception, err:
print 'Caught an exception'
finally:
print 'In finally block for cleanup'
#----------------------------------------#
Define a custom exception class which takes a string message as attribute.
Hints:
To define a custom exception, we need to define a class inherited from Exception.
Solution:
class MyError(Exception):
"""My own exception class
Attributes:
msg -- explanation of the error
"""
def __init__(self, msg):
self.msg = msg
error = MyError("something wrong")
#----------------------------------------#
Question:
Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the user name of a given email address. Both user names and company names are composed of letters only.
Example:
If the following email address is given as input to the program:
john@google.com
Then, the output of the program should be:
john
In case of input data being supplied to the question, it should be assumed to be a console input.
Hints:
Use \w to match letters.
Solution:
import re
emailAddress = raw_input()
pat2 = "(\w+)@((\w+\.)+(com))"
r2 = re.match(pat2,emailAddress)
print r2.group(1)
#----------------------------------------#
Question:
Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the company name of a given email address. Both user names and company names are composed of letters only.
Example:
If the following email address is given as input to the program:
john@google.com
Then, the output of the program should be:
google
In case of input data being supplied to the question, it should be assumed to be a console input.
Hints:
Use \w to match letters.
Solution:
import re
emailAddress = raw_input()
pat2 = "(\w+)@(\w+)\.(com)"
r2 = re.match(pat2,emailAddress)
print r2.group(2)
#----------------------------------------#
Question:
Write a program which accepts a sequence of words separated by whitespace as input to print the words composed of digits only.
Example:
If the following words is given as input to the program:
2 cats and 3 dogs.
Then, the output of the program should be:
['2', '3']
In case of input data being supplied to the question, it should be assumed to be a console input.
Hints:
Use re.findall() to find all substring using regex.
Solution:
import re
s = raw_input()
print re.findall("\d+",s)
#----------------------------------------#
Question:
Print a unicode string "hello world".
Hints:
Use u'strings' format to define unicode string.
Solution:
unicodeString = u"hello world!"
print unicodeString
#----------------------------------------#
Write a program to read an ASCII string and to convert it to a unicode string encoded by utf-8.
Hints:
Use unicode() function to convert.
Solution:
s = raw_input()
u = unicode( s ,"utf-8")
print u
#----------------------------------------#
Question:
Write a special comment to indicate a Python source code file is in unicode.
Hints:
Solution:
# -*- coding: utf-8 -*-
#----------------------------------------#
Question:
Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0).
Example:
If the following n is given as input to the program:
5
Then, the output of the program should be:
3.55
In case of input data being supplied to the question, it should be assumed to be a console input.
Hints:
Use float() to convert an integer to a float
Solution:
n=int(raw_input())
sum=0.0
for i in range(1,n+1):
sum += float(float(i)/(i+1))
print sum
#----------------------------------------#
Question:
Write a program to compute:
f(n)=f(n-1)+100 when n>0
and f(0)=1
with a given n input by console (n>0).
Example:
If the following n is given as input to the program:
5
Then, the output of the program should be:
500
In case of input data being supplied to the question, it should be assumed to be a console input.
Hints:
We can define recursive function in Python.
Solution:
def f(n):
if n==0:
return 0
else:
return f(n-1)+100
n=int(raw_input())
print f(n)
#----------------------------------------#
Question:
The Fibonacci Sequence is computed based on the following formula:
f(n)=0 if n=0
f(n)=1 if n=1
f(n)=f(n-1)+f(n-2) if n>1
Please write a program to compute the value of f(n) with a given n input by console.
Example:
If the following n is given as input to the program:
7
Then, the output of the program should be:
13
In case of input data being supplied to the question, it should be assumed to be a console input.
Hints:
We can define recursive function in Python.
Solution:
def f(n):
if n == 0: return 0
elif n == 1: return 1
else: return f(n-1)+f(n-2)
n=int(raw_input())
print f(n)
#----------------------------------------#
#----------------------------------------#
Question:
The Fibonacci Sequence is computed based on the following formula:
f(n)=0 if n=0
f(n)=1 if n=1
f(n)=f(n-1)+f(n-2) if n>1
Please write a program using list comprehension to print the Fibonacci Sequence in comma separated form with a given n input by console.
Example:
If the following n is given as input to the program:
7
Then, the output of the program should be:
0,1,1,2,3,5,8,13
Hints:
We can define recursive function in Python.
Use list comprehension to generate a list from an existing list.
Use string.join() to join a list of strings.
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
def f(n):
if n == 0: return 0
elif n == 1: return 1
else: return f(n-1)+f(n-2)
n=int(raw_input())
values = [str(f(x)) for x in range(0, n+1)]
print ",".join(values)
#----------------------------------------#
Question:
Please write a program using generator to print the even numbers between 0 and n in comma separated form while n is input by console.
Example:
If the following n is given as input to the program:
10
Then, the output of the program should be:
0,2,4,6,8,10
Hints:
Use yield to produce the next value in generator.
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
def EvenGenerator(n):
i=0
while i<=n:
if i%2==0:
yield i
i+=1
n=int(raw_input())
values = []
for i in EvenGenerator(n):
values.append(str(i))
print ",".join(values)
#----------------------------------------#
Question:
Please write a program using generator to print the numbers which can be divisible by 5 and 7 between 0 and n in comma separated form while n is input by console.
Example:
If the following n is given as input to the program:
100
Then, the output of the program should be:
0,35,70
Hints:
Use yield to produce the next value in generator.
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
def NumGenerator(n):
for i in range(n+1):
if i%5==0 and i%7==0:
yield i
n=int(raw_input())
values = []
for i in NumGenerator(n):
values.append(str(i))
print ",".join(values)
#----------------------------------------#
Question:
Please write assert statements to verify that every number in the list [2,4,6,8] is even.
Hints:
Use "assert expression" to make assertion.
Solution:
li = [2,4,6,8]
for i in li:
assert i%2==0
#----------------------------------------#
Question:
Please write a program which accepts basic mathematic expression from console and print the evaluation result.
Example:
If the following string is given as input to the program:
35+3
Then, the output of the program should be:
38
Hints:
Use eval() to evaluate an expression.
Solution:
expression = raw_input()
print eval(expression)
#----------------------------------------#
Question:
Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list.
Hints:
Use if/elif to deal with conditions.
Solution:
import math
def bin_search(li, element):
bottom = 0
top = len(li)-1
index = -1
while top>=bottom and index==-1:
mid = int(math.floor((top+bottom)/2.0))
if li[mid]==element:
index = mid
elif li[mid]>element:
top = mid-1
else:
bottom = mid+1
return index
li=[2,5,7,9,11,17,222]
print bin_search(li,11)
print bin_search(li,12)
#----------------------------------------#
Question:
Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list.
Hints:
Use if/elif to deal with conditions.
Solution:
import math
def bin_search(li, element):
bottom = 0
top = len(li)-1
index = -1
while top>=bottom and index==-1:
mid = int(math.floor((top+bottom)/2.0))
if li[mid]==element:
index = mid
elif li[mid]>element:
top = mid-1
else:
bottom = mid+1
return index
li=[2,5,7,9,11,17,222]
print bin_search(li,11)
print bin_search(li,12)
#----------------------------------------#
Question:
Please generate a random float where the value is between 10 and 100 using Python math module.
Hints:
Use random.random() to generate a random float in [0,1].
Solution:
import random
print random.random()*100
#----------------------------------------#
Question:
Please generate a random float where the value is between 5 and 95 using Python math module.
Hints:
Use random.random() to generate a random float in [0,1].
Solution:
import random
print random.random()*100-5
#----------------------------------------#
Question:
Please write a program to output a random even number between 0 and 10 inclusive using random module and list comprehension.
Hints:
Use random.choice() to a random element from a list.
Solution:
import random
print random.choice([i for i in range(11) if i%2==0])
#----------------------------------------#
Question:
Please write a program to output a random number, which is divisible by 5 and 7, between 0 and 10 inclusive using random module and list comprehension.
Hints:
Use random.choice() to a random element from a list.
Solution:
import random
print random.choice([i for i in range(201) if i%5==0 and i%7==0])
#----------------------------------------#
Question:
Please write a program to generate a list with 5 random numbers between 100 and 200 inclusive.
Hints:
Use random.sample() to generate a list of random values.
Solution:
import random
print random.sample(range(100), 5)
#----------------------------------------#
Question:
Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive.
Hints:
Use random.sample() to generate a list of random values.
Solution:
import random
print random.sample([i for i in range(100,201) if i%2==0], 5)
#----------------------------------------#
Question:
Please write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 , between 1 and 1000 inclusive.
Hints:
Use random.sample() to generate a list of random values.
Solution:
import random
print random.sample([i for i in range(1,1001) if i%5==0 and i%7==0], 5)
#----------------------------------------#
Question:
Please write a program to randomly print a integer number between 7 and 15 inclusive.
Hints:
Use random.randrange() to a random integer in a given range.
Solution:
import random
print random.randrange(7,16)
#----------------------------------------#
Question:
Please write a program to compress and decompress the string "hello world!hello world!hello world!hello world!".
Hints:
Use zlib.compress() and zlib.decompress() to compress and decompress a string.
Solution:
import zlib
s = 'hello world!hello world!hello world!hello world!'
t = zlib.compress(s)
print t
print zlib.decompress(t)
#----------------------------------------#
Question:
Please write a program to print the running time of execution of "1+1" for 100 times.
Hints:
Use timeit() function to measure the running time.
Solution:
from timeit import Timer
t = Timer("for i in range(100):1+1")
print t.timeit()
#----------------------------------------#
Question:
Please write a program to shuffle and print the list [3,6,7,8].
Hints:
Use shuffle() function to shuffle a list.
Solution:
from random import shuffle
li = [3,6,7,8]
shuffle(li)
print li
#----------------------------------------#
Question:
Please write a program to shuffle and print the list [3,6,7,8].
Hints:
Use shuffle() function to shuffle a list.
Solution:
from random import shuffle
li = [3,6,7,8]
shuffle(li)
print li
#----------------------------------------#
Question:
Please write a program to generate all sentences where subject is in ["I", "You"] and verb is in ["Play", "Love"] and the object is in ["Hockey","Football"].
Hints:
Use list[index] notation to get a element from a list.
Solution:
subjects=["I", "You"]
verbs=["Play", "Love"]
objects=["Hockey","Football"]
for i in range(len(subjects)):
for j in range(len(verbs)):
for k in range(len(objects)):
sentence = "%s %s %s." % (subjects[i], verbs[j], objects[k])
print sentence
#----------------------------------------#
Please write a program to print the list after removing delete even numbers in [5,6,77,45,22,12,24].
Hints:
Use list comprehension to delete a bunch of element from a list.
Solution:
li = [5,6,77,45,22,12,24]
li = [x for x in li if x%2!=0]
print li
#----------------------------------------#
Question:
By using list comprehension, please write a program to print the list after removing delete numbers which are divisible by 5 and 7 in [12,24,35,70,88,120,155].
Hints:
Use list comprehension to delete a bunch of element from a list.
Solution:
li = [12,24,35,70,88,120,155]
li = [x for x in li if x%5!=0 and x%7!=0]
print li
#----------------------------------------#
Question:
By using list comprehension, please write a program to print the list after removing the 0th, 2nd, 4th,6th numbers in [12,24,35,70,88,120,155].
Hints:
Use list comprehension to delete a bunch of element from a list.
Use enumerate() to get (index, value) tuple.
Solution:
li = [12,24,35,70,88,120,155]
li = [x for (i,x) in enumerate(li) if i%2!=0]
print li
#----------------------------------------#
Question:
By using list comprehension, please write a program generate a 3*5*8 3D array whose each element is 0.
Hints:
Use list comprehension to make an array.
Solution:
array = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)]
print array
#----------------------------------------#
Question:
By using list comprehension, please write a program to print the list after removing the 0th,4th,5th numbers in [12,24,35,70,88,120,155].
Hints:
Use list comprehension to delete a bunch of element from a list.
Use enumerate() to get (index, value) tuple.
Solution:
li = [12,24,35,70,88,120,155]
li = [x for (i,x) in enumerate(li) if i not in (0,4,5)]
print li
#----------------------------------------#
Question:
By using list comprehension, please write a program to print the list after removing the value 24 in [12,24,35,24,88,120,155].
Hints:
Use list's remove method to delete a value.
Solution:
li = [12,24,35,24,88,120,155]
li = [x for x in li if x!=24]
print li
#----------------------------------------#
Question:
With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], write a program to make a list whose elements are intersection of the above given lists.
Hints:
Use set() and "&=" to do set intersection operation.
Solution:
set1=set([1,3,6,78,35,55])
set2=set([12,24,35,24,88,120,155])
set1 &= set2
li=list(set1)
print li
#----------------------------------------#
With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print this list after removing all duplicate values with original order reserved.
Hints:
Use set() to store a number of values without duplicate.
Solution:
def removeDuplicate( li ):
newli=[]
seen = set()
for item in li:
if item not in seen:
seen.add( item )
newli.append(item)
return newli
li=[12,24,35,24,88,120,155,88,120,155]
print removeDuplicate(li)
#----------------------------------------#
Question:
Define a class Person and its two child classes: Male and Female. All classes have a method "getGender" which can print "Male" for Male class and "Female" for Female class.
Hints:
Use Subclass(Parentclass) to define a child class.
Solution:
class Person(object):
def getGender( self ):
return "Unknown"
class Male( Person ):
def getGender( self ):
return "Male"
class Female( Person ):
def getGender( self ):
return "Female"
aMale = Male()
aFemale= Female()
print aMale.getGender()
print aFemale.getGender()
#----------------------------------------#
Question:
Please write a program which count and print the numbers of each character in a string input by console.
Example:
If the following string is given as input to the program:
abcdefgabc
Then, the output of the program should be:
a,2
c,2
b,2
e,1
d,1
g,1
f,1
Hints:
Use dict to store key/value pairs.
Use dict.get() method to lookup a key with default value.
Solution:
dic = {}
s=raw_input()
for s in s:
dic[s] = dic.get(s,0)+1
print '\n'.join(['%s,%s' % (k, v) for k, v in dic.items()])
#----------------------------------------#
Question:
Please write a program which accepts a string from console and print it in reverse order.
Example:
If the following string is given as input to the program:
rise to vote sir
Then, the output of the program should be:
ris etov ot esir
Hints:
Use list[::-1] to iterate a list in a reverse order.
Solution:
s=raw_input()
s = s[::-1]
print s
#----------------------------------------#
Question:
Please write a program which accepts a string from console and print the characters that have even indexes.
Example:
If the following string is given as input to the program:
H1e2l3l4o5w6o7r8l9d
Then, the output of the program should be:
Helloworld
Hints:
Use list[::2] to iterate a list by step 2.
Solution:
s=raw_input()
s = s[::2]
print s
#----------------------------------------#
Question:
Please write a program which prints all permutations of [1,2,3]
Hints:
Use itertools.permutations() to get permutations of list.
Solution:
import itertools
print list(itertools.permutations([1,2,3]))
#----------------------------------------#
Question:
Write a program to solve a classic ancient Chinese puzzle:
We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have?
Hint:
Use for loop to iterate all possible solutions.
Solution:
def solve(numheads,numlegs):
ns='No solutions!'
for i in range(numheads+1):
j=numheads-i
if 2*i+4*j==numlegs:
return i,j
return ns,ns
numheads=35
numlegs=94
solutions=solve(numheads,numlegs)
print solutions
#----------------------------------------#
-----------------------------------------------------
解释器
Linux/Unix 的系统上,Python 解释器通常被安装在 /usr/local/bin/python3.4 这样的有效路径(目录)里。
我们可以将路径 /usr/local/bin 添加到您的 Linux/Unix 操作系统的环境变量中,这样您就可以通过 shell 终端输入下面的命令来启动 Python 。
在 Linux/Unix 系统中,你可以在脚本顶部添加以下命令让 Python 脚本可以像 SHELL 脚本一样可直接执行:
#! /usr/bin/env python3.4
注释
Python 中的注释有三种形式:
以 # 开头
以 ''' 开始,以 ''' 结尾
以 """ 开始,以 """ 结尾
# 单行注释
'''
这是多行注释,用三个单引号
这是多行注释,用三个单引号
这是多行注释,用三个单引号
'''
"""
这是多行注释,用三个双引号
这是多行注释,用三个双引号
这是多行注释,用三个双引号
"""
数据类型
Python3 中有六个标准的数据类型:
Numbers(数字)
String(字符串)
List(列表)
Tuple(元组)
Sets(集合)
Dictionaries(字典)
操作符
Python 语言支持以下类型的运算符:
算术运算符
比较(关系)运算符
赋值运算符
逻辑运算符
位运算符
成员运算符
身份运算符
运算符优先级
算术运算符
运算符 描述 实例
+ 加 - 两个对象相加 a + b 输出结果 31
- 减 - 得到负数或是一个数减去另一个数 a - b 输出结果 -11
* 乘 - 两个数相乘或是返回一个被重复若干次的字符串 a * b 输出结果 210
/ 除 - x 除以 y b / a 输出结果 2.1
% 取模 - 返回除法的余数 b % a 输出结果 1
** 幂 - 返回 x 的 y 次幂 a**b 为 10 的 21 次方
// 取整除 - 返回商的整数部分 9//2 输出结果 4 , 9.0//2.0 输出结果 4.0
比较运算符
运算符 描述 实例
== 等于 - 比较对象是否相等 (a == b) 返回 False。
!= 不等于 - 比较两个对象是否不相等 (a != b) 返回 True.
> 大于 - 返回 x 是否大于 y (a > b) 返回 False。
< 小于 - 返回 x 是否小于 y。所有比较运算符返回 1 表示真,返回 0 表示假。这分别与特殊的变量 True 和 False 等价。注意,这些变量名的大写。 (a < b) 返回 True。
>= 大于等于 - 返回 x 是否大于等于 y。 (a >= b) 返回 False。
<= 小于等于 - 返回 x 是否小于等于 y。 (a <= b) 返回 True。
赋值运算符
运算符 描述 实例
= 简单的赋值运算符 c = a + b 将 a + b 的运算结果赋值为 c
+= 加法赋值运算符 c += a 等效于 c = c + a
-= 减法赋值运算符 c -= a 等效于 c = c - a
*= 乘法赋值运算符 c _= a 等效于 c = c _ a
/= 除法赋值运算符 c /= a 等效于 c = c / a
%= 取模赋值运算符 c %= a 等效于 c = c % a
**= 幂赋值运算符 c **= a 等效于 c = c ** a
//= 取整除赋值运算符 c //= a 等效于 c = c // a
位运算符
运算符 描述 实例
& 按位与运算符:参与运算的两个值,如果两个相应位都为 1,则该位的结果为 1,否则为 0 (a & b) 输出结果 12 ,二进制解释: 0000 1100
| 按位或运算符:只要对应的二个二进位有一个为 1 时,结果位就为 1。 (a | b) 输出结果 61 ,二进制解释: 0011 1101
^ 按位异或运算符:当两对应的二进位相异时,结果为 1 (a ^ b) 输出结果 49 ,二进制解释: 0011 0001
~ 按位取反运算符:对数据的每个二进制位取反,即把 1 变为 0,把 0 变为 1 (~a ) 输出结果 -61 ,二进制解释: 1100 0011, 在一个有符号二进制数的补码形式。
<< 左移动运算符:运算数的各二进位全部左移若干位,由"<<"右边的数指定移动的位数,高位丢弃,低位补 0。 a << 2 输出结果 240 ,二进制解释: 1111 0000
>> 右移动运算符:把">>"左边的运算数的各二进位全部右移若干位,">>"右边的数指定移动的位数 a >> 2 输出结果 15 ,二进制解释: 0000 1111
逻辑运算符
运算符 逻辑表达式 描述 实例
and x and y 布尔"与" - 如果 x 为 False,x and y 返回 False,否则它返回 y 的计算值。 (a and b) 返回 20。
or x or y 布尔"或" - 如果 x 是 True,它返回 x 的值,否则它返回 y 的计算值。 (a or b) 返回 10。
not not x 布尔"非" - 如果 x 为 True,返回 False 。如果 x 为 False,它返回 True。 not(a and b) 返回 False
成员运算符
运算符 描述 实例
in 如果在指定的序列中找到值返回 True,否则返回 False。 x 在 y 序列中 , 如果 x 在 y 序列中返回 True。
not in 如果在指定的序列中没有找到值返回 True,否则返回 False。 x 不在 y 序列中 , 如果 x 不在 y 序列中返回 True。
身份运算符
运算符 描述 实例
is is 是判断两个标识符是不是引用自一个对象 x is y, 如果 id(x) 等于 id(y) , is 返回结果 1
is not is not 是判断两个标识符是不是引用自不同对象 x is not y, 如果 id(x) 不等于 id(y). is not 返回结果 1
运算符优先级
运算符 描述
** 指数 (最高优先级)
~ + - 按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@)
* / % // 乘,除,取模和取整除
+ - 加法减法
>> << 右移,左移运算符
& 位 'AND'
^ | 位运算符
<= < > >= 比较运算符
<> == != 等于运算符
= %= /= //= -= += *= **= 赋值运算符
is is not 身份运算符
in not in 成员运算符
not or and 逻辑运算符
控制语句
条件语句
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3
循环语句
while
while 判断条件:
statements
for
for <variable> in <sequence>:
<statements>
range()
for i in range(0, 10, 3) :
print(i)
break 和 continue
break 语句可以跳出 for 和 while 的循环体。
continue 语句被用来告诉 Python 跳过当前循环块中的剩余语句,然后继续进行下一轮循环。
pass
pass 语句什么都不做。它只在语法上需要一条语句但程序不需要任何操作时使用.例如:
while True:
pass # 等待键盘中断 (Ctrl+C)
函数
Python 定义函数使用 def 关键字,一般格式如下:
def 函数名(参数列表):
函数体
函数变量作用域
#!/usr/bin/env python3
a = 4 # 全局变量
def print_func1():
a = 17 # 局部变量
print("in print_func a = ", a)
def print_func2():
print("in print_func a = ", a)
print_func1()
print_func2()
print("a = ", a)
以上实例运行结果如下:
in print_func a = 17
in print_func a = 4
a = 4
关键字参数
函数也可以使用 kwarg=value 的关键字参数形式被调用.例如,以下函数:
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print("-- This parrot wouldn't", action, end=' ')
print("if you put", voltage, "volts through it.")
print("-- Lovely plumage, the", type)
print("-- It's", state, "!")
可以以下几种方式被调用:
parrot(1000) # 1 positional argument
parrot(voltage=1000) # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump') # 3 positional arguments
parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword
以下为错误调用方法:
parrot() # required argument missing
parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument
parrot(110, voltage=220) # duplicate value for the same argument
parrot(actor='John Cleese') # unknown keyword argument
可变参数列表
最后,一个最不常用的选择是可以让函数调用可变个数的参数.这些参数被包装进一个元组(查看元组和序列).在这些可变个数的参数之前,可以有零到多个普通的参数:
def arithmetic_mean(*args):
sum = 0
for x in args:
sum += x
return sum
返回值
Python 的函数的返回值使用 return 语句,可以将函数作为一个值赋值给指定变量:
def return_sum(x,y):
c = x + y
return c
异常
异常处理
try 语句按照如下方式工作;
首先,执行 try 子句(在关键字 try 和关键字 except 之间的语句)
如果没有异常发生,忽略 except 子句,try 子句执行后结束。
如果在执行 try 子句的过程中发生了异常,那么 try 子句余下的部分将被忽略。如果异常的类型和 except 之后的名称相符,那么对应的 except 子句将被执行。最后执行 try 语句之后的代码。
如果一个异常没有与任何的 except 匹配,那么这个异常将会传递给上层的 try 中。
不管 try 子句里面有没有发生异常,finally 子句都会执行。
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
finally:
# 清理行为
抛出异常
Python 使用 raise 语句抛出一个指定的异常。例如:
>>> raise NameError('HiThere')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: HiThere
自定义异常
可以通过创建一个新的 exception 类来拥有自己的异常。异常应该继承自 Exception 类,或者直接继承,或者间接继承。
当创建一个模块有可能抛出多种不同的异常时,一种通常的做法是为这个包建立一个基础异常类,然后基于这个基础类为不同的错误情况创建不同的子类:
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class InputError(Error):
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed.
Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
"""
def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message
大多数的异常的名字都以"Error"结尾,就跟标准的异常命名一样。
面向对象
面向对象技术简介
类(Class): 用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例。
**类变量:**类变量在整个实例化的对象中是公用的。类变量定义在类中且在函数体之外。类变量通常不作为实例变量使用。
**数据成员:**类变量或者实例变量用于处理类及其实例对象的相关的数据。
**方法重写:**如果从父类继承的方法不能满足子类的需求,可以对其进行改写,这个过程叫方法的覆盖(override),也称为方法的重写。
**实例变量:**定义在方法中的变量,只作用于当前实例的类。
**继承:**即一个派生类(derived class)继承基类(base class)的字段和方法。继承也允许把一个派生类的对象作为一个基类对象对待。例如,有这样一个设计:一个 Dog 类型的对象派生自 Animal 类,这是模拟"是一个(is-a)"关系(例图,Dog 是一个 Animal)。
**实例化:**创建一个类的实例,类的具体对象。
**方法:**类中定义的函数。
**对象:**通过类定义的数据结构实例。对象包括两个数据成员(类变量和实例变量)和方法。
类定义
语法格式如下:
class ClassName:
<statement-1>
.
.
.
<statement-N>
类实例化后,可以使用其属性,实际上,创建一个类之后,可以通过类名访问其属性。
类对象
类对象支持两种操作:属性引用和实例化。
属性引用使用和 Python 中所有的属性引用一样的标准语法:obj.name。
类对象创建后,类命名空间中所有的命名都是有效属性名。所以如果类定义是这样:
#!/usr/bin/python3
class MyClass:
"""一个简单的类实例"""
i = 12345
def f(self):
return 'hello world'
# 实例化类
x = MyClass()
# 访问类的属性和方法
print("MyClass 类的属性 i 为:", x.i)
print("MyClass 类的方法 f 输出为:", x.f())
实例化类:
# 实例化类
x = MyClass()
# 访问类的属性和方法
以上创建了一个新的类实例并将该对象赋给局部变量 x,x 为空的对象。
执行以上程序输出结果为:
MyClass 类的属性 i 为: 12345
MyClass 类的方法 f 输出为: hello world
很多类都倾向于将对象创建为有初始状态的。因此类可能会定义一个名为 init() 的特殊方法(构造方法),像下面这样:
def __init__(self):
self.data = []
类定义了 init() 方法的话,类的实例化操作会自动调用 init() 方法。所以在下例中,可以这样创建一个新的实例:
x = MyClass()
当然, init() 方法可以有参数,参数通过 init() 传递到类的实例化操作上。例如:
>>> class Complex:
... def __init__(self, realpart, imagpart):
... self.r = realpart
... self.i = imagpart
...
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)
类的方法
在类地内部,使用 def 关键字可以为类定义一个方法,与一般函数定义不同,类方法必须包含参数 self,且为第一个参数:
#!/usr/bin/python3
#类定义
class people:
#定义基本属性
name = ''
age = 0
#定义私有属性,私有属性在类外部无法直接进行访问
__weight = 0
#定义构造方法
def __init__(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s 说: 我 %d 岁。" %(self.name,self.age))
# 实例化类
p = people('W3Cschool',10,30)
p.speak()
执行以上程序输出结果为:
W3Cschool 说: 我 10 岁。
继承
Python 同样支持类的继承,如果一种语言不支持继承就,类就没有什么意义。派生类的定义如下所示:
class DerivedClassName(BaseClassName1):
<statement-1>
.
.
.
<statement-N>
需要注意圆括号中基类的顺序,若是基类中有相同的方法名,而在子类使用时未指定,python 从左至右搜索 即方法在子类中未找到时,从左到右查找基类中是否包含方法。
BaseClassName(示例中的基类名)必须与派生类定义在一个作用域内。除了类,还可以用表达式,基类定义在另一个模块中时这一点非常有用:
class DerivedClassName(modname.BaseClassName):
实例
#!/usr/bin/python3
#类定义
class people:
#定义基本属性
name = ''
age = 0
#定义私有属性,私有属性在类外部无法直接进行访问
__weight = 0
#定义构造方法
def __init__(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s 说: 我 %d 岁。" %(self.name,self.age))
#单继承示例
class student(people):
grade = ''
def __init__(self,n,a,w,g):
#调用父类的构函
people.__init__(self,n,a,w)
self.grade = g
#覆写父类的方法
def speak(self):
print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))
s = student('ken',10,60,3)
s.speak()
执行以上程序输出结果为:
ken 说: 我 10 岁了,我在读 3 年级
多继承
Python 同样有限的支持多继承形式。多继承的类定义形如下例:
class DerivedClassName(Base1, Base2, Base3):
<statement-1>
.
.
.
<statement-N>
需要注意圆括号中父类的顺序,若是父类中有相同的方法名,而在子类使用时未指定,python 从左至右搜索 即方法在子类中未找到时,从左到右查找父类中是否包含方法。
#!/usr/bin/python3
#类定义
class people:
#定义基本属性
name = ''
age = 0
#定义私有属性,私有属性在类外部无法直接进行访问
__weight = 0
#定义构造方法
def __init__(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s 说: 我 %d 岁。" %(self.name,self.age))
#单继承示例
class student(people):
grade = ''
def __init__(self,n,a,w,g):
#调用父类的构函
people.__init__(self,n,a,w)
self.grade = g
#覆写父类的方法
def speak(self):
print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))
#另一个类,多重继承之前的准备
class speaker():
topic = ''
name = ''
def __init__(self,n,t):
self.name = n
self.topic = t
def speak(self):
print("我叫 %s,我是一个演说家,我演讲的主题是 %s"%(self.name,self.topic))
#多重继承
class sample(speaker,student):
a =''
def __init__(self,n,a,w,g,t):
student.__init__(self,n,a,w,g)
speaker.__init__(self,n,t)
test = sample("Tim",25,80,4,"Python")
test.speak() #方法名同,默认调用的是在括号中排前地父类的方法
执行以上程序输出结果为:
我叫 Tim,我是一个演说家,我演讲的主题是 Python
方法重写
如果你的父类方法的功能不能满足你的需求,你可以在子类重写你父类的方法,实例如下:
#!/usr/bin/python3
class Parent: # 定义父类
def myMethod(self):
print ('调用父类方法')
class Child(Parent): # 定义子类
def myMethod(self):
print ('调用子类方法')
c = Child() # 子类实例
c.myMethod() # 子类调用重写方法
执行以上程序输出结果为:
调用子类方法
类属性与方法
类的私有属性
__private_attrs:两个下划线开头,声明该属性为私有,不能在类地外部被使用或直接访问。在类内部的方法中使用时self.__private_attrs。
类的方法
在类地内部,使用 def 关键字可以为类定义一个方法,与一般函数定义不同,类方法必须包含参数 self,且为第一个参数
类的私有方法
__private_method:两个下划线开头,声明该方法为私有方法,不能在类地外部调用。在类的内部调用 slef.__private_methods。
实例如下:
#!/usr/bin/python3
class JustCounter:
__secretCount = 0 # 私有变量
publicCount = 0 # 公开变量
def count(self):
self.__secretCount += 1
self.publicCount += 1
print (self.__secretCount)
counter = JustCounter()
counter.count()
counter.count()
print (counter.publicCount)
print (counter.__secretCount) # 报错,实例不能访问私有变量
执行以上程序输出结果为:
1
2
2
Traceback (most recent call last):
File "test.py", line 16, in <module>
print (counter.__secretCount) # 报错,实例不能访问私有变量
AttributeError: 'JustCounter' object has no attribute '__secretCount'
类的专有方法:
**init :** 构造函数,在生成对象时调用
**del :** 析构函数,释放对象时使用
**repr :** 打印,转换
**setitem :** 按照索引赋值
**getitem:** 按照索引获取值
**len:** 获得长度
**cmp:** 比较运算
**call:** 函数调用
**add:** 加运算
**sub:** 减运算
**mul:** 乘运算
**div:** 除运算
**mod:** 求余运算
**pow:** 乘方
运算符重载
Python 同样支持运算符重载,我么可以对类的专有方法进行重载,实例如下:
#!/usr/bin/python3
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)
以上代码执行结果如下所示:
Vector(7,8)
标准库概览
操作系统接口
os 模块提供了不少与操作系统相关联的函数。
>>> import os
>>> os.getcwd() # 返回当前的工作目录
'C:\\Python34'
>>> os.chdir('/server/accesslogs') # 修改当前的工作目录
>>> os.system('mkdir today') # 执行系统命令 mkdir
0
文件通配符
glob 模块提供了一个函数用于从目录通配符搜索中生成文件列表:
>>> import glob
>>> glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']
命令行参数
通用工具脚本经常调用命令行参数。这些命令行参数以链表形式存储于 sys 模块的 argv 变量。例如在命令行中执行 python demo.py one two three 后可以得到以下输出结果:
>>> import sys
>>> print(sys.argv)
['demo.py', 'one', 'two', 'three']
错误输出重定向和程序终止
sys 还有 stdin,stdout 和 stderr 属性,即使在 stdout 被重定向时,后者也可以用于显示警告和错误信息。
>>> sys.stderr.write('Warning, log file not found starting a new one\n')
Warning, log file not found starting a new one
字符串正则匹配
re 模块为高级字符串处理提供了正则表达式工具。对于复杂的匹配和处理,正则表达式提供了简洁、优化的解决方案:
>>> import re
>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
['foot', 'fell', 'fastest']
>>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
'cat in the hat'
数学
math 模块为浮点运算提供了对底层 C 函数库的访问:
>>> import math
>>> math.cos(math.pi / 4)
0.70710678118654757
>>> math.log(1024, 2)
10.0
资料
https://github.com/vinta/awesome-python - 资源大全
https://github.com/jobbole/awesome-python-cn - 资源大全
https://github.com/scrapy/scrapy - python 爬虫框架
https://github.com/faif/python-patterns - python 设计模式
https://github.com/kennethreitz/python-guide - python 最佳实践