-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPractice of Python.py
More file actions
212 lines (172 loc) · 6.93 KB
/
Practice of Python.py
File metadata and controls
212 lines (172 loc) · 6.93 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# DECLARATION
# Hello World
firstString = "hello"
secondString = ", python!\t"
print(firstString + secondString)
# Combine Strings
print("\n")
assembledString = firstString + secondString + "\t"
print(2*(assembledString))
# Length of String
numberOfString = len(firstString)
print("\nThe length of the firstString is: ", numberOfString, "\n")
numberOfRepeatedString = assembledString.count("o")
print("The letter \"o\" in the firstString repeated for ", numberOfRepeatedString, " times.")
# Integer
firstInteger = 5
secondInteger = 2
print(firstInteger)
MultipliedResult = firstInteger*secondInteger
print(str(firstInteger) + " muitiply " + str(secondInteger) + " equal to " + str(MultipliedResult))
# I need to transfer integer into string through the function str() if I want to print integer with string together.
# Bool
firstBool = bool(0)
secondBool = bool(2)
print("\n0 means " + str(firstBool) + " in python")
print("The number over than 0 means " + str(secondBool) + " in python")
# Array
firstArray = [1, 2, 3, 4, 5]
print("The second element in the firstArray is: " + str(firstArray[1]))
print("The number of elements in the firstArray is: " + str(len(firstArray)))
firstArray.append(6)
print("\nThe new element is: " + str(firstArray[5]))
firstArray.remove(6)
print("The length of firstArray has been returned to: " + str(len(firstArray)))
print("\nThe max element in firstArray is: " + str(max(firstArray)))
print("The sum of every elements in firstArray is: " + str(sum(firstArray)))
# Slice of An Array
secondArray = firstArray[1:3]
print(secondArray)
# Tuple
firstTup = (5, 2, 3, 4, 1) # Tuple is inmutable.
print("The element 2 in firstTup is at", str(firstTup.index(2)), ".")
# Dictionary
firstDic = {}
firstDic["firstGirlfriend"] = "Cindy"
firstDic["secondGirlfriend"] = "Tina"
firstDic["thirdGirlfriend"] = "Betty"
# Search Value with Key
print("The length of my firstDictionary is: " + str(len(firstDic)))
print("The second element of firstDic is: " + str(firstDic["secondGirlfriend"]))
'''print(firstDic[0]) # This would not work since I could not use order to
extract the value, it is a difference between array
and dictionary.'''
print(firstDic.get("forthGirlfriend", "Alisa")) # .get(key, default value) method could be used as try & except.
print(firstDic.values()) # .values() method could be used to get all the values in the dictionary.
# .sorted(dictionary) could be used to read the key orderly, while the data in the dictionary was not stored in order in python.
# Search Key with Value
for key in firstDic:
if firstDic[key] == "Betty":
print("\n" + str(key))
print(firstDic.get("firstGirlfriend", "Error"))
print("\n")
# Use Error Type to Prevent Crash
try:
print(firstDic["secondGirlfriend"])
print(firstDic["forthGirlfriend"])
except KeyError:
print("No value!")
# Use .setdefault function to do the same thing
print(firstDic.setdefault("secondGirlfriend", "No value!")) # If the value of particular key exist, return the value, or return default value "No value!".
print(firstDic.setdefault("forthGirlfriend", "No value!"))
#CONTROL FLOW
# Loop
for i in range(1, 10) :
for j in range(2, 9) :
if j == 8:
print(str(j) + " * " + str(i) + " = " + str(i*j))
else:
print(str(j) + " * " + str(i) + " = " + str(i*j), end = '\t')
# Input
answer = 4
userWinTheGame = bool(0)
print("\nPlease guess a number between 0 to 5. You could guess for three times.")
for i in range(1, 4):
userInpu = int(input())
if userInpu == answer:
print("\nBingo!")
userWinTheGame = bool(1)
break
else:
if i != 3:
print("\nPlease guess again")
if userWinTheGame == 0:
print("\nGame over!")
# If & Function with Input and Output
def firstFunction(numberOfMyGirlfriend):
if numberOfMyGirlfriend == 0:
return "I am single"
else:
return "I am not single"
print(firstFunction(5) + "\n")
# Function with Input of Array
def seeTheArray(inputArray):
for i in range(0, len(inputArray)):
print(inputArray[i])
seeTheArray(firstArray)
print("\n")
# Find
target = ["bee", "zoo", "beneficial", "face", "close", "efficient"]
criteria1 = "be"
criteria2 = "o"
criteria3 = "fi"
for i in range(0, len(target)):
if target[i].find(criteria1) == -1:
if target[i].find(criteria2) == -1:
if target[i].find(criteria3) == -1:
print("Did not find anything!")
else:
print("Find ", criteria3, " successfully!")
else:
print("Find ", criteria2, " successfully!")
else:
print("Find ", criteria1, " successfully!")
# Generate Random Number
import random
randomMatrix = []
for i in range(0, 50):
randomMatrix.append(random.randint(0, 50000))
print(randomMatrix)
# While
a = 0
while True:
while a < 3:
print("The code \"while True\" means \"always\" I guess, I should stop it!")
a += 1
# Note with Multipal Lines
'''
I could press "control" and "/" to create note with multipal lines.
'''
# None and is
strangeNumber = None # None is a kind of "flag type".
strangeBul = True
for i in range(0, 2):
if strangeNumber is None:
print(type(strangeNumber))
strangeNumber = 1
else:
print(type(strangeNumber))
if strangeBul is True: # "is" was used for boolean and None, it is similar to "==".
print("Yes")
strangeBul = False
else:
print("No")
strangeBul = True
# Read A File
'''
fileHandle= open("THE NAME OF YOUR FILE.txt", 'r') # open() could open a file and store it in the memory,
"print(fileHandle)" only shows the address. Make sure
that the file of this python codes and the file you
want to read (here is .txt file) should be put in the
same place.
data = fileHandle.read() # read() could transfer the file handle into readable data.
# It seems that read() may read each "character" in the txt file, I could take into account readlines() instead.
for eachLine in data: # Run through each line in the data.
print(eachLine.rstrip()) # rstrip() could be used to remove some useless "\n", the type of the output is string.
if eachLine.startswith("From:") is True: # .startwith() method could be used to check specific syntax, it would return a boolean.
print("Find it!")
'''
# Split Sentence
sentence = "I love you!"
seperatedWords = sentence.split() # .split() method could be used to split the words, the type of the output is list.
print(seperatedWords[1])