for-in loop : Determine the specific number of cycles
while loop : Not sure how many times to cycle
total = 0
# range(a,b) function [a,b) Left closed right away
for i in range(1, 101):
total += i
print(total)
range() function : The interval between left and right
Just write a number , The default left side is 0
range(101): produce 0-100 Integer between
range(2,101): produce 2-100 Integer between
range(0,101,2): produce 0-100 Even number between ( Step size is set ——2)
for i in range(0, 101, 2):
print(i)
1、 A dead cycle
i = 0
while i >= 0:
i += i
2、while Examples used
sum = 0
flag = True
i = 1
while flag:
if i <= 100:
sum += i
i += 1
else:
flag = False
print(sum)
break: End break Cycle
continue: Terminate the current cycle , Enter next cycle
for i in range(1, 101):
if i == 50:
# break
continue
else:
print(i)
for i in range(1, 10):
for j in range(1, i + 1):
# print('%d X %d = %d'%(i,j,i*j))
# print('{}*{}={}'.format(i,j,i*j)) # The two lines work the same , But it's all in one column ( You need to change the last default character )
# modify print() Of end Parameters
print('{} * {} = {}'.format(i, j, i * j), end='\t')
# Wrap after each line is printed
print()
num = int(input(' Enter a positive integer :'))
judge = False
if num == 1 or num == 2:
print('{} Prime number '.format(num))
else:
for i in range(2, num // 2 + 1):
if num % i == 0:
print('%d Not primes ' % num)
judge = True
break
else:
continue
# print('{} Prime number '.format(num))
# problem : Why is there no cyclic output here {} Prime number ?
if not judge:
print('%d Prime number ' % num)
A finite sequence of zero or more characters
stay Python in , One or more characters enclosed in single or double quotation marks , It's called a string
s1 = 'Hello,World!'
s2 = 'Violets'
s1 = 'Hello,World!'
s2 = 'Violets'
print(s1 + s2)
print(s1 + '!')
s1 = 'Hello,World!'
s2 = 'Violets'
print(s1 * 3)
1、ASCII Size to size
print('a' > 'b')
print('boy' > 'girl')
2、ord() Convert characters to ASCII code
print(ord('a'), ord('o'))
print(ord(' Li '))
3、 Members of the operation :in\not in
s1 = 'abcd'
print('a' in s1)
print('c' not in s1)
print(len(s1))
s1 = 'abcd'
print(s1[2])
print(s1[-1])
# The result is d
print(s1[-4])
# The result is a
The default step size is 1
Slices are also left closed and right open
Do not write parameters before the first colon , The default from the 0 Start
Do not write parameters after the first colon , Default to the end of the string
s2 = ' Drunk light at the sword , Dream back to blow the horn camp .'
print(s2[0:])
print(len(s2))
print(s2[3:7])
# The third parameter is also the step size
print(s2[::2])
# Inverted extraction
print(s2[-1:-11:-2])
# Loop through the string
# Output each element of the string
for i in s2:
print(i)
# Output string every position index
for i in range(len(s2)):
print(i)
for i in range(len(s2)):
print(i,s2[i])
s3 = 'Hello!World!'
# Capitalize the first letter of the string :capitalize()
print(s3.capitalize())
# Capitalize the first letter of each word in a string
print(s3.title())
# Capitalize all letters of the string
a = s3.upper()
print(a)
# Make all letters of the string lowercase :lower()
print(a.lower())
# index()\find() By default, search from left to right , Find the element and stop immediately
print(s3.index('l'))
# index() An error is reported when the element is not found :ValueError: substring not found
# print(s3.index('a'))
# find()
# find() Element not found , return -1
print(s3.find('l'))
print(s3.find('a'))
# find() You can specify from the index N Start looking for
print(s3.find('l', 4))
# rfind() Search from right to left
print(s3.rfind('d'))
s3 = 'hello world'
# center() Fill the string with a length of N String , The blank position is filled with the specified string , The original string is placed in the middle of the current string
print(s3.center(20, '*'))
# rjust()
print(s3.rjust(20, '*'))
# ljust()
print(s3.ljust(20, '*'))
s = ' hello world \n\t'
# strip() Space the left and right sides of the string , Escape characters are removed
print(s.strip())
A list is an arrangement of elements in a certain order
A variety of data can be stored in the list
You can save... In the list Duplicate data
One line of code shows multiple lines , Use backslash \ Connect
list = ['hello world', 2022, 6, \
16, 3.1415, [1, 2, 3], \
{
10, 20}, {
'name': ' Zhang San '}]
list1 = [10, 20, 30]
list2 = ['a', 'b', 'c']
print(list1 + list2)
print(list1 * 3)
print(10 in list1)
print(list1[0])
print(list1[-1])
list3 = [10, 20, 30, 40, 50, 60, 70, 80]
print(list3[:])
print(list3[2:5])
print(list3[::2])
print(list3[-1:-7:-1])
print(list3[-1::-1])
'>'not supported between instance of 'int' and 'str'
list1 = [10, 20, 30]
list2 = ['a', 'b', 'c']
print(list1 > list2)
Compare the size of the two lists , The comparison is the list Same index location The size of the element
The element at the same index position of the two lists that compare sizes must be Same data type
list1 = [10, 20]
list2 = [20, 30]
print(list1 > list2)
for i in list1:
print(i)
# Don't write the two cycles together
# for i in range(len(list1)):
# print(i)
# print(i, list1[i])
list3 = []
list3.append(10)
list3.append(10)
list3.append('Python')
print(list3)
list3.insert(0, 'java')
print(list3)
# del
# Delete the specified index location element
del list3[0]
print(list3)
# pop(): The deleted element is stored in an element
a = list3.pop(0)
print(list3)
print(a)
# remove(): Delete a specific element in the list
list3.remove('Python')
print(list3)
list4 = ['abc', 10, 50, 80, 40]
# index()
print(list4.index('abc'))
# # Elements that are not in the list ,index() Report errors
# print(list4.find(10))
# count(): No output 0
print(list4.count(10))
print(list4.count(30))
list5 = [10, 90, 40, 20, 70]
# sort(): The default order is from small to large
list5.sort()
print(list5)
# reverse(): Reverse order
list5.reverse()
print(list5)
list6 = []
for i in range(1, 11):
list6.append(i)
print(list6)
list7 = [i for i in range(1, 11)]
print(list7)
Function is to encapsulate a relatively independent part of the code
def Is the key to define a function 、fac Function name 、num The parameters to be passed
def fac(num):
pass
pass Keep the integrity of the code structure , Not involved in the execution of the program
fac(12)
# Example , No implementation
def total(num):
sum = 0
for i in range(1, num + 1):
sum += i
print(sum)
return sum
total(100)
# return Return the internal result of the function to the external , Don't write return The result of data in the external calling function is null (none)
a = total(1000)
print(a)
When some statements are correct , Wrong results may occur , To ensure that the program does not terminate , Exception handling is introduced
Wrong cases :
try……except……finally
num = int(input(' Please enter an integer :'))
print(num)
# ValueError: invalid literal for int() with base 10: 'abc'
try Case study :
num = int(input(' Please enter an integer :'))
print(num)
except Exception as error:
print(error)
# invalid literal for int() with base 10: 'abc'
print(' Something unusual happened ')
finally:
print(' Program end ')
# fianlly The following code whether or not there is an exception , Will eventually be implemented
list1 = [10, 20, 30, 'abc', 20, 'UFO']
for i in list1:
try:
a = i / 10
print(a)
except Exception as err:
print(err)
continue
Container data type
tuple
A tuple 、 Binary 、 Multiple groups
tuple_1 = (25,)
print(type(tuple_1))
# type() Methods to get data types
Creating a tuple without a comma is not a tuple
tuple_2 = (25)
print(type(tuple_2))
tuple_3 = ('abc')
print(type(tuple_3))
tuple_2 = (10, 20)
# Get tuple length len()
print(len(tuple_2))
t1 = (20,)
t2 = (30, 10)
print(t1 + t2)
print(t1 * 3)
print(10 in t2)
print(t2[0])
print(t2[-1])
t3 = (10, 20, 30, 40, 50)
print(t3[:])
print(t3[2:4])
print(t3[::2])
print(t3[-1:-6:-1])
t4 = ()
print(type(t4))
# Tuples are immutable types , Once created , No more changes , That is, you cannot add , Delete and other similar operations
a = 1, 2, 3
print(a, type(a))
# The number of variables on the left of the equal sign should be equal to the length of tuples to be packed
i, j, z = a
print(i, j, z)
# The wrong sample 1
# ValueError: too many values to unpack (expected 2)
# i, j = a
# print(i, j)
# The wrong sample 2
# The number of variables on the left of the equal sign is greater than the tuple length
# i, j, z, h =a
# print(i, j, z, h)
# ValueError: not enough values to unpack (expected 4, got 3)
# Asterisk expression : Used to solve the problem that the number of variables on the left of the equal sign is insufficient
# Give priority to variables without an asterisk , It is best to consider variables with asterisks
b = (1, 2, 3)
i, *j = b
print(i, j)
c = (1, 2, 3, 4)
i, *j, z = c
print(i, j, z)
i, j, *z = c
print(i, j, z)
i = 1
j = 2
# C Language version
z = i
i = j
j = z
print(i, j)
# Python edition
i, j = j, i
print(i, j)