python Basics

Some connections between functions and loops:
Judge whether a starts with b
eg:
Method 1

a = "abcdef"
b = "abcd"
i = 0
while i < len(b):
    if a[i]!=b[i]:
        print("Flase")
        break
    i = i+1
else:
    print("True")

Result: True
Method 2 (function)
eg:

 "abcdef"
b = "abcd"
def startWith(x,y):
    i = 0
    while i < len(y):
        if x[i]!=y[i]:
            return False
        i = i+1
    return True
print(startWith(a,b() "abcdef"
b = "abcd"
def startWith(x,y):
    i = 0
    while i < len(y):
        if x[i]!=y[i]:
            return False
        i = i+1
    return True
print(startWith(a,b))

Result: True

Determine if string a ends with string b
eg:

a = "abcdef"
b = "def"
# print(a.endswith(b))         #a ends with b.
# From the last comparison
i = -1
while i >= -len(b):
    if a[i]!=b[i]:
        print("False")
        break
    i = i-1
else:
    print("True")
# The first comparison from the short term
i = 0
while i < len(b):
    if a[len(a)-len(b)+i]!=b[i]:
        print("False")
        break
    i = i+1
else:
    print("True")

Result: True

Add the elements corresponding to two lists to get a new list
eg:

a = [i for i in range(1,13)]
b = [i*10 for i in range(1,13)]
print(a)
print(b)
c = []                           
i = 0
while i < len(a):
    c.append(a[i]+b[i])         
    # a[i]= a[i]+b[i]               #The second way
    i = i+1
print(c) 

The result is:

Enter a number to determine whether the number is prime
eg:

x = int(input("Please enter a number:"))
if x <= 1:
    print("This is not a prime number!")
else:
    i = 2
    while i < x:
        if x%i==0:
            print("This is not a prime number!")
            break
        i = i+1
    else:
        print("This is a prime number!")

Add the corresponding elements of two lists with unequal length to get a new list
eg:

a = [1,2,3,4,5,6,7,8,9,10,11,12]
b = [1,2,3,4,5,6,7,8,9,10]
i = 0
c = []
while i < len(a) or i < len(b):
    x=y=0
    if i < len(a):
        x=a[i]
    if i < len(b):
        y=b[i]
    c.append(x+y)
    i=i+1
print(c)

The result is:

Determine whether string b exists in string a
eg:

a = "abcdde"
b = "cd"
i = 0
while i<len(a):
    if b[0]==a[i] and b[1]==a[i+1]:
        print("True")
        break
    i = i+1
else:
    print("False")

Result: True

Output a digital triangle
eg:

i = 1
while i < 7:
    j = 1
    while j <= i:
        print(j,end=" ")
        j = j+1
    print()
    i = i+1

The result is:

Output an inverted triangle of *
eg:

def paint():
    i = 1
    while i < 7:
        j = 1
        while j<=i-1:
            print(" ",end="")
            j = j+1
        k = 0
        while k<7-i:
            print("*",end="")
            k = k+1
        print()
        i = i+1
paint()

The result is:

Posted by Harry57 on Sun, 01 Dec 2019 18:20:07 -0800