1. if
>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
... x = 0
... print('Negative changed to zero')
... elif x == 0:
... print('Zero')
... elif x == 1:
... print('Single')
... else:
... print('More')
...
More
2. for
>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
... print(w, len(w))
...
cat 3
window 6
defenestrate 12
3. range
>>> for i in range(5):
... print(i)
...
0
1
2
3
4
range(5, 10)
5 through 9
range(0, 10, 3)
0, 3, 6, 9
range(-10, -100, -30)
-10, -40, -70
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
... print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb
range() do not return a list.
list(range(5)) do this.
4. The break statements, like in C, breaks out of the smallest enclosing for or while loop.
5. Loop statement may have an else clause. It is executed when the loop terminates exhaustion of the list(with for) or when the condition becomes false(with while) , but not when the loop is terminated by a bra
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
6. continue
>>> for num in range(2, 10):
... if num % 2 == 0:
... print("Found an even number", num)
... continue
... print("Found a number", num)
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9
7.pass take up the place but do no thing.
8.Defining Function
>>> def fib(n): # write Fibonacci series up to n
... """Print a Fibonacci series up to n. docstring"""
... a, b = 0, 1
... while a < n:
... print(a, end=' ')
... a, b = b, a+b
... print()
...
>>> # Now call the function we just defined:
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
9. variable reference:
first local symbol table
then in the local symbol tables of enclosing functions
then in the global symbol table
finally in the table of built-in names
10. thus global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced. ???
11. return without an expression argument returns None.
12. Default Argument Values: The default value is evaluated only once.
13. There are something in defining function I can't understand. 4.6——4.8