Python小白的学习之路 Day2
- Conditional Execution (Chapter 3)
- Functions (Chapter 4)
Conditional Execution (Chapter 3)
Comparison Operators
Python | Meaning |
---|---|
" <= " | Less than or Equal to |
" == " | Equal to |
" >= " | Greater than or Equal to |
" > " | Greater than |
" != " | Not equal |
" < " | Less than |
Indentation
- Increase indent indent after an if statement or for statement (after : )
- Maintain indent to indicate the scope of the block (which lines are affected by the if/for)
- Reduce indent back to the level of the if statement or for statement to indicate the end of the block
Nested Decisions
if x > 1 :
print('More than one')
if x < 100 :
print('Less than 100')
print('All done')
Two-way Decisions with else
if x > 2 :
print('Bigger')
else :
print('Smaller')
print('All done')
Multi-way with elif
if x < 2 :
print('small')
elif x < 10 :
print('Medium')
else :
print('LARGE')
print('All done')
- No else is also acceptable
if x < 2 :
print('Small')
elif x < 10 :
print('Medium')
print('All done')
The try / except Structure
- If the code in the try works - the except is skipped
- If the code in the try fails - it jumps to the except section
- Sample try / except :
rawstr = input('Enter a number:')
try:
ival = int(rawstr)
except:
ival = -1
if ival > 0 :
print('Nice work')
else:
print('Not a number')
Functions (Chapter 4)
Python Functions
- Built-in functions that are provided as part of Python - print(), input(), type(), float(), int(), max() …
- Functions that we define ourselves and then use
Building our Own Functions
- Once we have defined a function, we can call (or invoke) it as many times as we like
- This is the store and reuse pattern
Arguments
- An argument is a value we pass into the function as its input when we call the function
Parameters
- A parameter is a variable which we use in the function definition. It is a “handle” that allows the code in the function to access the arguments for a particular function invocation.
注意 Arguments 和 Parameters 的区别
Return Values
- Often a function will take its arguments, do some computation, and return a value to be used as the value of the function call in the calling expression. The return keyword is used for this.
- The return statement ends the function execution and “sends back” the result of the function
Multiple Parameters / Arguments
- We match the number and order of arguments and parameters
Example:
def addtwo(a, b):
added = a + b
return added
x = addtwo(3, 5)
print(x)
8
Void (non-fruitful) Functions
- When a function does not return a value, we call it a “void” function
- Functions that return values are “fruitful” functions