Introduction
Programming statements are used to expresse action or assign a variable in program.Each statement has own syntax and purpose. We can combine these statements to achieve specific purpose.
Assignment Statements
Assingment statement is used to set reference of object or value stored in monery address by a variable name.
(1) normal assignment : fruit = “apple”
(2) sequence assignment: a,b = 'Jack', 'John'
(3) List assignment :
(4) Augmented assignment:
>>>a =1
>>>a+=1
(5) Sequence assignment
- Sequence one to one
>>>seq = [1, 2, 3, 4] >>> a,b,c,d = seq >>> a,b = seq #seq have 4 elements, but assignemnt elements just have 2 Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> a,b = seq ValueError: too many values to unpack (expected 2) >>> a,b,c,d = seq >>>a 1 |
- Sequence one and rest
>>>seq = [1, 2, 3, 4] >>> e, *f = seq[0:3] #e get first element, other element assign f >>> e 1 >>> f [2, 3] >>> *g, h = seq[0:3] # |
- Boundary cases
>>>seq = [1, 2, 3, 4] >>>
|
(6) Mulitple-target assignment
There has many assignment variable.
>>> a = b =0 |
Control Statements
1.if/elif/else statment
- Syntax
if expression : |
- Example
(1) There are a fruit list , we check apple if it is in the list.
fruit = ["apple","banana"] if "apple" in fruit: print("found it!) else: print("don’t found it!") -------------------------------------- found it ! |
(2) Jack
grade = {"Jack":90, "Joe":60, "Bryant":50, "Hacker":30} hard |
2. for/else
- Syntax
for var inm sequence: |
(1)
list1 = {1,2,3,4,5} |
3.while/else
- Syntax
while( expression): |
while True: |
Handling Errors
In python when the programe is executed how to handle it and throw message to notify operator.
- Syntax
try: |
while True: |
留言
張貼留言