python learning 2_basic programming

Basic use of while loops

The execution order of a program is divided into three categories: Sequence - executing code sequentially from top to bottom

Branching - the branching that determines the execution of the code based on conditions

* Loop - let specific code execute repeatedly

The most common scenario for a while loop is to have the code executed repeat a specified number of times

Simple exercise:

'''
//Requirements:
//Calculate the cumulative sum of all numbers between 1 and 100
//Use both while and for
'''
i = 1
# Define variable save and
sum = 0
while i<101:
    sum = sum + i               #A very important way to handle it.
    i += 1                      # Modify Loop Variables
print(sum)
# python does not increase or decrease
###########for mode
sum = 0
for ele in range(1,101):        #  range(1,101) left closed right open
    sum += ele
print(sum)

Use of break and continue

* When a break condition is met, the subsequent duplicate code in the loop is no longer executed and the loop exits

When a condition of continue is satisfied, the subsequent duplicate code in the loop is no longer executed, but the next loop judgment goes on, and there are only certain conditions in the entire loop that do not require the execution of the loop code, while other conditions require the execution of the loop code.

Example:

'''
//Find all non-3-bit palindromes
'''
i=100
while i<1000:
    bai=i//100
    ge=i%10
    zhongjianzhi=i
    i+=1          #Note: When using continue, special attention should be paid to the code in the conditional processing section, which can cause an inadvertent endcycle
    if bai==ge:
        continue   #If pass is used here, i+=1 can be placed at the end
    else:
        print(zhongjianzhi)
'''
//Find the 10th 5-digit palindrome number
'''
i=10000
count=0                          # Counter, Important****, used when counting is required
while i<100000:
    wan=i//10000
    ge=i%10
    qian=i%10000//1000
    shi=i%100//10
    if (wan==ge) and (qian==shi):
        count+=1
        if count==10            # The first time this condition is met is the first palindrome number
        	print(i)
            break               # break will not be executed until the 10th time, jumping out of the loop after execution
    i+=1

pass

An empty command, do nothing.To preserve the integrity of the program structure

Nested loop

Example:

# Print 3 times from 1 to 5. ******** Notice how many times the outermost layer of the nested example indicates what to do, and the inner layer indicates what to do.
j = 1
while j < 4:
    i = 1
    while i < 6:
        print(i)
        i += 1
    j += 1

Nested Loop Exercise: Nine-nine Multiplication Table

lie=1
while lie<10:
    hang=1
    while hang<lie+1:
        print('%d * %d = %d'%(lie,hang,lie*hang),end='\t') 
         # End=''means no line break, \t means tab stop, \n means line break, \r means carriage return print instruction defaults to line break if no rear end is added
        hang+=1
    print()
    lie+=1

for loop

Role: Traverse elements in data (**container)**, any Iterable data can be traversed through a for loop.String belongs to container

Example:

#Print every element in hello world
str = 'hello world'
for ele in str:
    print(ele)

In and not in

The Python in operator is used to determine if an element exists in a container and returns true if it exists or false if it does not.

Example:

str =  'hello'
if 'h' in str:    #Determine if a letter belongs to a string
    print('h' not in  str)
    #The result is False

Use continue and braeak in for loop

* continue and break can also be used in for loops to jump out of loops in a manner consistent with the while loop, traversing all elements in a string.

####Traversing through all elements in a string using while
str = 'hello world'
# String Length
length = len(str)             # Container length len() calculation
i = 0
while i<length:
    # Get Elements
    ele = str.__getitem__(i)   #Or use str[i]
    print(ele)
    # Modify Variables
    i += 1

Round Robin exercises

""" 
//Print all elements of the string'hello world'before the third'l' appears (excluding the third'l') 
"""
str = 'hello world'
# count
count = 0                          #Note the use of counts
for ele in str:
    if ele == 'l':
        count += 1
        if count == 3:
            break                  #Jump out of for loop terminator immediately after break execution
    print(ele)

Section

* range() creates a list of integers, commonly used in a for loop.Left Close Right Open

Interval operation

* Get an element in the interval_getitem_ (corner)

* Traversal interval for ele in rang(1,101)

* Determine if a number is in an interval if ele in rang(1,101): Return Rure if it is in an interval

Circular Summary

The difference between a while loop and a for loop is:

* while loop is a conditional loop statement in python

for loop is a loop traversal statement in python

Cyclic binding else

* Statements in else execute when the loop finishes (that is, for is not interrupted by a break), as does the while loop

* Code in else will not execute if break is executed in the for loop

Circulation with else exercises

'''
//Requirements:
//Determine whether the login password'hhew2383dW_fkf&E@^'is legal
//Requirement:
1. Password must be a number, letter(Both uppercase and lowercase),And underline,Otherwise illegal
2. If the password is legal,On Output'Password is legal,Can log on'(Logon Operation)
'''

pwd = 'hhew2383dW_fkf&E@^'
# Define Containers
str = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_'
# Counter
count = 0
# Judging legality
for ele in pwd:
    if ele not in str:
        break
else:
    print('Can log on')
    
# Judging the number of legal characters
# count+=1
# if count == len(pwd):
#     print('can log in')
# else:
#     print('not logged in')

Advanced variable types

Includes: List Tuple Collection String Dictionary Public Grammar

All non-numeric variables support the following characteristics:

Each is a sequence, or a container.

Value

* Traverse for in

* Calculate Length, Maximum/Minimum, Compare, Delete

* Links + Duplicates*

Slices***

list

Specially designed to store a series of data called elements

List Add, Delete and Modify Elements, Query, Sort and Value

increase

Method Explain
Append (data) Append data at the end
Insert (index, data) Insert data at the specified location (empty elements fill in before the location)
extend(Iterable) Append elements from iterative objects to the list
l.extend(ll)      #Add a list l l after list L.Or think of it as adding the order of a ll elements in List 11 to the end of List L

delete

Method Explain
del list [index] Delete data for specified index
Remove (data) Delete the first occurrence of the specified data
pop() Delete the end data and return the deleted element
Pop (index) Delete specified index data
clear() clear list
l=['Li Si','Zhang San','Li Si']
l.remove('Li Si')     #Delete the first Lisi
a=l.pop(index)            #pop has a return value that returns the specified element after it has been deleted.

modify

Method Explain
List [Index] =Data Modify the data of the specified index, there will be no error if the data does not exist

query

Method Explain
List [Index] Index does not exist and will error based on index value
Index (data) Query index based on value, return index at first occurrence, no lookup will error
Count (data) Number of times the data appears in the list
Len (list) List Length
if data in list: Check if an element is included in the list
a=l.index('Li Si')    #a = Returns the index number of'Li Si'in the list

sort

Method Explain
sort() Ascending order
sort(reverse=True) Descending order
reverse() Reverse Order, Reverse Order
l = [6,3,2,8,1]
l.sort()        #Ascending order
maxValue = max(l)    #Maximum

Maximum

Method Explain
max() Maximum
min() minimum value

List exercise: sorting

Bubble sort

'''
//There is a set of numbers [9,8,7,6,5,4,3,2,1]. Please sort this set manually (do not use the sort method)
'''
l=[9,8,7,6,5,4,3,2,1]
i=0
while i<len(l)-1:
    j=0
    while j<len(l)-1-i:              # compare
        a=l[j]                      ## Exchange, the core algorithm is to compare the elements inside and order them in turn
        l[j]=l[j+1]
        l[j+1]=a
        j+=1
    i+=1    
print(l)

Select Sort

l = [9, 99, 7, 105, 5, 120, 3, 2, 1]
i=0
while i<len(l): 
	minIndex=i                    # Assumed Minimum Angle Scale
    j=i+1
    while j<len(l):
        if l[j]<l[minIndex]        # compare
        	minIndex=j             # Change Corner
        j+=1
     # Determine Minimum Corner at the End of a Loop
     # Minimum of Swap Settings and Actual Minimum
     # Considered minimum l[i]
     # Actual minimum l[minIndex]
	l[i],l[minIndex]=l[minIndex],l[i]
	i+=1
print(l)
	

List Nesting

'''
//A school with three offices now has eight teachers waiting for assignments.
//Write a program:
1. Complete random assignments 
2. Get office information (Number of people in each office and who are they)
3. Make sure there is at least one person in each classroom
'''
import random    
classrooms=[[],[],[]]                  #Create nested empty list
teacher=['q','w','e','r','t','y','u','i']
count=0
for room in classrooms:                #Assign one person randomly in each classroom first
   index=random.randint(0,7-count)
   room.append(teacher.pop(index))     #Teachers will not participate in the assignment next time after assignment, so delete assigned people
   count+=1
for ele in teacher:
   classrooms[random.randint(0,2)].append(ele)    #Assign remaining teachers
for room in classrooms:
   print('Classroom has%d People, respectively'%len(room),tuple(room))

List Summary

***** Counts, cumulative additions, if execution precedence, else inside for and while

Count:

Note this usage in loops by setting a count variable outside the loop to record the number of loops.count+=1

Cumulative addition:

​ sum=sum+i

if Execution Priority:

The if statement execution condition should increase from top to bottom, and the above execution condition cannot contain the following.eg:<60, >=60 and <=70, >70.>70 This condition needs to be on top.

else inside for and while:

Note that unlike else in if, while executes when it is not executed and while loop executes when it is finished, but break in while does not execute and continue in while does.

'''List 1~1000 All prime numbers in-------for Traverse, while Loop, in a loop else,if Sentence synthesis'''
'''Analysis: Numbers within an interval are traversed and divided by themselves and by a number thought to be 1, which is not prime if divisible by an integer'''
for ele in rang(2,1000):
    i=2
    while i<ele:
        if ele%i==0:
            break
            #print('not a prime number')
        i+=1
	else:   ###Note: The while will execute if it is not executed here, and the while loop will execute when it is finished, but it will not execute after break ing in while.
    	print(ele)
		
        
'''
//Requirements:
//Determine whether the login user name is legal (regular expressions cannot be used)
//User name is a numeric letter or, needs 3 to 20 digits, must have 2 or more uppercase letters, 2 or more lowercase letters, 3 or more digits
hhew2383dW_fkf&E@^
'''
str = "hhew2383dW_fkfE"
numberStr = '01234565789'
lowerStr = 'abcdefghijklmnopqrstuvwxyz'
upperStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

numberCount = 0
lowCount = 0
upperCount = 0

isLegel = True
for ele in  str:
    if ele in numberStr:
        numberCount += 1
    elif ele in lowerStr:
        lowCount += 1
    elif ele in upperStr:
        upperCount += 1
    elif ele == '_':
        pass
    else:
        isLegel = False

# judge
length = len(str)
if length>=3 and length<=20 and numberCount>=3 and lowCount>=2 and upperCount >= 2 and isLegel:
    print('Password is legal')
else:
    print('Illegal password')
Three original articles were published, 0 won and 17 visited
Private letter follow

Tags: Python

Posted on Tue, 04 Feb 2020 18:58:58 -0800 by kusarigama