Note 2 - body and structure
标签(空格分隔): python
Learning techniques
Assuming you are playing << call of duty >> and need go through one difficult scene where has many options and the duplicate operations like pulling trigger.
1.Condition statement
1.1 Definition
#syntax
#boolean expression :a cimbination of comparsion operators and logic operators
if boolean expression :
elif boolean expression :
else :
Example:
# if
age = 20
if age < 18 :
print("youngster")
elif age == 18 :
print("18")
else:
print("adult")
1.2 deeper intuition
If statement exactly follows the sementic rules as if these statements looks like a short story!
if bool(true)->keep going
bool(false)->else / elif(iteration)
Extra point: input()
a = input("please input your age!")
The terminal prompts you to input age-> that means you need to type your age on the console.
1.3 nested if statement
Inner one if statement is nested into the outer if statement
if boolean expression :
if boolean expression :
#....
2. loop statement
- while
- for
keywords:
- continue
- break
- else
- pass
2.1 while
Example:
i = 1
while i <= 10 :
print("still in loop body",i)
i += 1
if i == 10 :
break
else :
print("jump out of loop then execute else")
We can single out some important points:
1.syntax
while boolean-expression :
loop body
continue # stop this sub-course and jump directly to next sub-course
break # terminate the whole loop and execute the next statement
else:
##else executed if the entire lopp is executed but jump over to the underneath statement if loop ##body executes break
2.2 for
Example:
for element in collection :
continue # same as while
break # same as while
else:
# same as while when break within loop body is executed makes else block cannot be executed
When I first learned to program with python in the way as I do in Java,especially retrieving the entire list in python.I hardly got used to code for statement in python.But a suggestion is given for this problem.
for i in range(10)[
# equivalent to ->
# for (int i = 0 ; i < a.length ; i++ )
2.3 pass
As result of facilitating the complement for code in the future,we can use keyword pass to occupy some space to be available later.
3.iterator and generator
what we learn here is just getting our feet wet.
3.1 Iterator
Iterator is for retrieving the whole element in a collection like list and so forth.
There are two crucial functions of it: iter() [exclusive]and next()[general]
a = [1,2,3,4,5,6,7,8,9,10]
iterator = iter(a)
while True :
print(next(iterator),end=",")
The terminal shows:
1,2,3,4,5,6,7,8,9,10,Traceback (most recent call last):
File "d:\workspace\python\learning_06.py", line 6, in <module>
print(next(iterator),end=",")
StopIteration
3.2 generator
pass block
range([start],end,[step]) generates a number list :start from [start],end up to end,go forward one timee with one step ↩︎