My python learning diary 2 (small tip in range, else statement in for, function definition and default value, and related to turtle)

Posted by praveenp on Sun, 06 Mar 2022 01:13:33 +0100

python iterative non numeric sequence can be iterated by sequence index, and range and len are used together.

#Using sequence index to iterate, you can use range () and len() together
Array=['I','have','a','nice','hobby']
for i in range(len(Array)):
    print(i,Array[i])

In addition, you can also use enumerate() to implement it. Enumerate() will change the original sequence to "[(0, 'I'), (1, 'have'), (2, 'a')...]".  

Array=['I','have','a','nice','hobby']
for i,item in enumerate(Array,0):
   print(i,item)

Because range() is an iterable object, although the objects generated by range are like a list, in fact, a specific list is not generated. Therefore, it cannot be printed directly in print.

print(range(4))
#Error in print(range(4)). The desired result is not output

#Both of the following methods are feasible
print(sum(range(4)))
print(list(range(4)))

About for statement and else statement in python

for n in range(2,10):
    for x in range(2,n):
        if n % x == 0:
            print(n,'equals',x,'*',n//x)
            break
    else:#In this case, else corresponds to the for statement
        print(n,'is a prime number')
The implementation results are:
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
9 equals 3 * 3
When used with loops, else clauses and else clauses in try statements have more in common than similar clauses in if statements: else clauses in try statements are executed when no exception occurs, while else clauses in loops are executed when no break occurs.

In addition, the use of continue is the same as that of C, indicating the next iteration in the loop. The pass statement means to do nothing. It is used when only one statement is required in syntax but do nothing. Usually, pass is used to create the smallest class. Another use of pass is as a placeholder for the body of a function or conditional clause when writing new code, so that you can keep thinking at a more abstract level.

On function definition (taking Fibonacci sequence as an example)

#Define Fibonacci function
def fib(n):
    a,b = 0,1
    while a < n:
        print(a, end=' ')
        a,b = b, a+b
    print()
f=fib
fib(2000)
f(100)

append method and constructing sequence with function

#append method and constructing sequence with function
def fib2(n):
    result=[]
    a,b = 0,1
    while a<n:
        result.append(a)
        a,b=b,a+b
    return result

print(fib2(100))

The use of the default value of the function. When calling the function, you can also use keywords to pass values. input is used to obtain strings. raise can throw exceptions, which is similar to throw in Java

#Function default value, and input to get the string, raise throws an exception
def ask_ok(prompt, retries=4,reminder='please try again!'):
    while True:
        ok = input(prompt)
        if ok in('y','ye','yes'):
            return True
        if ok in('n','no','nop','nope'):
            return False
        retries = retries-1
        if retries < 0:
            raise ValueError('invalid user response')
        print(reminder)

ask_ok('Do you really want to quit?')
ask_ok('OK to overwrite the file?',2)
ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')

Another little thing about turtle, turtle Hideturtle () can hide the brush, that is, the small arrow can be hidden. If you don't need to draw a continuous picture, you can use penup and pendowna to adjust the brush position. circle() can draw a circle with the brush as the rightmost point. The + + operator is no longer used in python, and the self increment operation can be realized by using item+=1.

#Draw a ring diagram
import turtle
#Painting speed
turtle.speed(0)
turtle.Turtle().getscreen().delay(0)
turtle.hideturtle()#Hide brush

turtle.pensize(10)
Color=['blue','black','red','yellow','green']
Cindex=0

for y in range(0,-51,-50):
    for x in range(0,241,120):
        if y==0:
            turtle.color(Color[Cindex])
            turtle.penup()
            turtle.goto(x,y)
            turtle.pendown()
            turtle.circle(50)
            Cindex+=1
        elif (y==-50) & (x>0):
            turtle.color(Color[Cindex])
            turtle.penup()
            turtle.goto(x-60,y)
            turtle.pendown()
            turtle.circle(50)
            Cindex += 1


turtle.exitonclick()#Click to close the page

The operation results are as follows:

Note: for the cross line character \, use \ to place the character array cross line.

#About cross line characters
a='there is \
some numbers just like'
b=[1,2,3,4,5,\
    7,8,9,10]
print(a,b)

Topics: Python