each line within a basic block must be idented by the same amount.
Use keyword end to avoid the newline after output.
12345
>>>a,b=0,1>>>whileb<1000:print(b,end=',')# specify what character is used after output.a,b=b,a+b1,1,2,3,5,8,
If Statement
elif and else part is optional
1234567891011
>>>x=int(input("Please enter an integer: "))# Defulat input will return a stringPleaseenteraninteger:42>>ifx<0:x=0elifx==0:print('Zero')elifx==1:print('Single')else:print('More')More
For Statement
Iterates the items of a list or string in the order they appear.
if you modify the sequence, you may create a dead loop program
123456
>>>words=['cat','window','defenestrate']>>>forwinwords[:]:# word[:] will not make the program dead loop. If u use words, program will be dead loopiflen(w)>6:words.insert(0,w)>>>words['defenestrate','cat','window','defenestrate']
Loop statement can have else clause. It is executed when loop terminates through exhaustion of list (for) or when condition becauses false (while)
else of loop statement cannot executed when loop is terminated by a break statement.
12345678910111213141516
>>>forninrange(2,10):>>>forxinrange(2,n):>>>ifn%x==0:>>>print(n,'equals',x,'*',n//x)>>>break>>>else:# look at this intentation>>>print(n,'is a prime number')2isaprimenumber3isaprimenumber4equals2*25isaprimenumber6equals2*37isaprimenumber8equals2*49equals3*3
continue statement continues with the next iteration of the loop
1234567891011121314
>>>fornuminrange(2,10):>>>ifnum%2==0:>>>print("Found an even number",num)>>>continue# if 'if' is executed, the second print will not be executed.>>>print("Found a number",num)Foundanevennumber2Foundanumber3Foundanevennumber4Foundanumber5Foundanevennumber6Foundanumber7Foundanevennumber8Foundanumber9
Pass Statement
It does nothing.
12
>>>whileTrue:pass# dead loop
Define Functions
12345678
>>>deffib(n):# write Fibonacci seriesa,b=0,1whilea<n:print(a,end=' ')a,b=b,a+bprint()>>># Call the functionfib(2000)
Execution of a function introduces a new symbol table for local variables. All function parameters will be stored in this table.
When you pass the arguments some values, the values are always the object reference not the value of the object
A function definition introduces the function name in current symbol stable. You can also assign the function name to other parameter
1234
>>>fib<functionfibat10042ed0>>>>f=fib>>>f(100)# same as fib(100)
Actually, each function has a return value. At least it is None
12
print(fib(0))None
Lets change the fib functions to store the reurn value temporally
12345678910
>>>deffib2(n):result=[]# store the result valuea,b=0,1whilea<n:result.append(a)# the method we use to add the a,b=b,a+breturnresult>>>f100=fib2(100)# call the function>>>f100[0,1,1,2,3,5,8,13,21,34,55,89]
Specify a default value for one or more arguments
1234567891011
defask_ok(prompt,retries=4,complaint='Yes or no, please!'):whileTrue:ok=input(prompt)ifokin('y','ye','yes'):# in can test if ok is in a sequencereturnTrueifokin('n','no','nop','nope'):returnFalseretries=retries-1ifretries<0:raiseOSError('uncooperative user')print(complaint)
The default value is evaluated only once.
1234567891011
>>>deff(a,L=[]):# L = [] will only be done once.L.append(a)returnL>>>print(f(1))>>>print(f(2))>>>print(f(3))[1][1,2][1,2,3]
If you have default parameter in your function. You can choose not to pass value to the default parameter. But you still need to pass values to other regular parameters.
parrot(1000)# 1 positional argumentparrot(voltage=1000)# 1 keyword argumentparrot(voltage=1000,'action='VBOOM')parrot(action='VBoom',voltage=1000)# The order of keyword parameter is not importantparrot('a million','berere','jump')parrot('a thousand',state='fdaf')
But the following is not acceptable
123
parrot()# require keyword argumentparrot(voltage=5.0,'dead')# After keyword argument, you must use keyword argumentparrot(1000,voltage=220)# duplicate value for the same arguement
You define *name and **name. But *name must be put before **name
1234567
deftest(kind,*arguments,**keywords):print("Do you have",kind,"?")forarginarguments:print(arg)key=sorted(keywords.keys())# sort the dictionaryforkwinkeys:print(kw,":",keywords[kw])
Call it like this
123456
test("Limburger","It's very runny","It's very very runny"# this two parameters will be sent to *argumentsshopkeeper="Michael"client="John"sketch="Cheese")# this three will be sent to **keywords
It will display
123456
DoyouhaveLimburger?It's very runny,It's very very runnyclient:johnshopkeeper:Michaelsketch:Cheese
Arbitrary argument, after *args, must use keywords rather than positional arguments.
123456
>>>defconcat(*args,sep="/"):# after *args, you must use keywrod instead of positional argumentsreturnsep.join(args)>>>concat("earth","mars","venus")'earth/mars/venus'>>>concat("earth","mars",sp=".")'earth/mars/
Call function with unpacked arguments
12345
>>>list(range(3,6)# normal call with separate arguments[3,4,5]>>>args=[3,6]>>>list(range(*args))# call with arguments unpacked[3,4,5]
call function with dictionary to deliver arguments