#!/usr/bin/python
2 ways to print output variables
Name= ' Zhangsan '
Print "Badou Hadoop study!,your name is%s"% (name)
Print "You name is", name
Defining functions
def print_your_name (name):
Print "Your name is", name
Return ""
Print print_your_name (' Zhangsan ')
Print print_your_name (' Lisi ')
Collection of Python in 3
# Python:hashmap, Dict, {}
# Python:array, List-a []
# Python:set, set, set ()
# Dict
color = {"Red": 0.2, "green": 0.4, "Blue": 0.4}
Print color["Red"]
Print color["Green"]
# list
Color_list = [' Red ', ' blue ', ' green ', ' yellow ']
Print Color_list[2]
#set can go heavy
A_set = set ()
A_set.add (' 111 ')
A_set.add (' 222 ')
A_set.add (' 333 ')
A_set.add (' 111 ')
Judgment statement
A=1
If a > 0:
print ' a GT 0 '
elif A = = 0:
print ' a EQ 0 '
Else
print ' A LT 0 '
For list array
A_list = []
A_list.append (' 111 ')
A_list.append (' 333 ')
A_list.append (' 555 ')
A_list.append (' 222 ')
A_list.append (' 444 ')
For value in A_list:
Print value
For Dict (map) unordered
B_dict = {}
b_dict[' aaa '] = 1
b_dict[' bbb '] = 2
b_dict[' CCC '] = 3
b_dict[' ddd '] = 4
b_dict[' eee '] = 5
For Key,value in B_dict.items ():
Print key + ":" + str (value)
For set unordered
C_set = set ()
C_set.add (' a ')
C_set.add (' B ')
C_set.add (' C ')
C_set.add (' d ')
C_set.add (' e ')
For value in C_set:
Print value
Number accumulation
sum = 0
For value in range (1,11):
Sum + = value
Print sum
While
CNT =2
While CNT > 0:
print ' Love Python '
CNT-= 1
Print Dual
I =1
While I < 10:
i + = 1
If i%2 > 0:
Continue
Print I
String length
str = ' ABCDEFG '
Print Len (str)
String interception
Print Str[2:5]
String uppercase to lowercase
str = ' ABCDEF '
Print Str.lower ()
Throw exception
Try
A = 6
b = a/0
Except Exception,e:
Print Exception, ":", E
IO exception
Try
FH = open (' Testfile ', ' R ')
Except IOError, E:
Print E
Else
print ' OK '
Fh.close ()
Math
Import Math
2 of the 3-time Square
Print Math.pow (2,3)
Floating point number
Print Math.floor (4.9)
Rounded
Print round (4.9)
Import Random
Output array unordered
Items = [1,2,3,4,5,6]
Random.shuffle (items)
Print items
Output a random number
A = Random.randint (0,3)
Print a
Randomly extract the specified number
S_list = random.sample (' ABCDEFG ', 3)
Print S_list
Basic syntax for Python strings, collections, for loops, exceptions, and so on