程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[python notes \u 2] loop, string, list, function, exception handling

編輯:Python

List of articles

  • 1 loop
    • 1.1 loop
    • 1.2 for-in loop
    • 1.2 while loop
    • 1.3 Nested loop
      • 1.3.1 multiplication table
      • 1.3.2 Enter a positive integer , Judge whether it is a prime number
  • 2 character string
    • 2.1 Definition of string
    • 2.2 Operation of string
      • 2.2.1 Splicing
      • 2.2.2 repeat
      • 2.2.3 Comparison operations
      • 2.2.4 To obtain the length of the :len()
    • 2.3 Indexes
      • 2.3.1 Positive index
      • 2.3.2 Reverse index
    • 2.4 section
    • 2.5 String method
      • 2.5.1 Capitalize the initial
      • 2.5.2 Each letter is capitalized
      • 2.5.3 Each letter becomes lowercase
      • 2.5.4 Search operation :index()\find()
      • 2.5.5 Formatted string
      • 2.5.6 Trim operation
  • 3 list
    • 3.1 List operator
      • 3.1.1 Splicing of lists
      • 3.1.2 The list repeats
      • 3.1.3 Member operation of list :in\not in
    • 3.2 Indexes
    • 3.3 section
    • 3.4 Comparison operations
    • 3.4 Loop traversal of list
    • 3.5 List method
      • 3.5.1 Additive elements
      • 3.5.2 append(): Add an element at the end of the list
      • 3.5.3 Copy shortcut :Ctrl + D
      • 3.5.4 insert(): Add the element at the specified index position
      • 3.5.5 Delete elements in the list :del、pop、remove
    • 3.6 The position and number of occurrences of an element in the list
      • 3.6.1 Location :index()
      • 3.6.2 frequency :count()
      • 3.6.3 Sort :sort()、reverse()
    • 3.7 List generator
      • 3.7.1 The ordinary way
      • 3.7.2 Use list generation
  • 4 function
    • 4.1 Calculation 1 To N And
  • 5 exception handling
    • 5.1 practice 1
  • 6 Tuples
    • 6.1 Define components
      • 6.1.1 Define a tuple
      • 6.1.2 Binary
    • 6.2 Splicing
    • 6.3 repeat
    • 6.4 Members of the operation
    • 6.5 Indexes
    • 6.6 section
    • 6.7 Create an empty tuple
    • 6.8 Packing and unpacking tuples
    • 6.8.1 pack
    • 6.8.2 Unpack
    • 6.9 Exchange the values of two variables

1 loop

1.1 loop

for-in loop : Determine the specific number of cycles
while loop : Not sure how many times to cycle

1.2 for-in loop

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.2 while loop

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)

1.3 Nested loop

1.3.1 multiplication table

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()

1.3.2 Enter a positive integer , Judge whether it is a prime number

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)

2 character string

2.1 Definition of string

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'

2.2 Operation of string

2.2.1 Splicing

s1 = 'Hello,World!'
s2 = 'Violets'
print(s1 + s2)
print(s1 + '!')

2.2.2 repeat

s1 = 'Hello,World!'
s2 = 'Violets'
print(s1 * 3)

2.2.3 Comparison operations

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)

2.2.4 To obtain the length of the :len()

print(len(s1))

2.3 Indexes

2.3.1 Positive index

s1 = 'abcd'
print(s1[2])

2.3.2 Reverse index

print(s1[-1])
# The result is d
print(s1[-4])
# The result is a

2.4 section

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])

2.5 String method

s3 = 'Hello!World!'

2.5.1 Capitalize the initial

# Capitalize the first letter of the string :capitalize()
print(s3.capitalize())

2.5.2 Each letter is capitalized

# Capitalize the first letter of each word in a string 
print(s3.title())
# Capitalize all letters of the string 
a = s3.upper()
print(a)

2.5.3 Each letter becomes lowercase

# Make all letters of the string lowercase :lower()
print(a.lower())

2.5.4 Search operation :index()\find()

# 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'))

2.5.5 Formatted string

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, '*'))

2.5.6 Trim operation

s = ' hello world \n\t'
# strip() Space the left and right sides of the string , Escape characters are removed 
print(s.strip())

3 list

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 '}]

3.1 List operator

list1 = [10, 20, 30]
list2 = ['a', 'b', 'c']

3.1.1 Splicing of lists

print(list1 + list2)

3.1.2 The list repeats

print(list1 * 3)

3.1.3 Member operation of list :in\not in

print(10 in list1)

3.2 Indexes

print(list1[0])
print(list1[-1])

3.3 section

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])

3.4 Comparison operations

'>'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)

3.4 Loop traversal of list

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])

3.5 List method

3.5.1 Additive elements

list3 = []

3.5.2 append(): Add an element at the end of the list

list3.append(10)
list3.append(10)

3.5.3 Copy shortcut :Ctrl + D

list3.append('Python')
print(list3)

3.5.4 insert(): Add the element at the specified index position

list3.insert(0, 'java')
print(list3)

3.5.5 Delete elements in the list :del、pop、remove

# 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)

3.6 The position and number of occurrences of an element in the list

3.6.1 Location :index()

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))

3.6.2 frequency :count()

# count(): No output 0
print(list4.count(10))
print(list4.count(30))

3.6.3 Sort :sort()、reverse()

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)

3.7 List generator

3.7.1 The ordinary way

list6 = []
for i in range(1, 11):
list6.append(i)
print(list6)

3.7.2 Use list generation

list7 = [i for i in range(1, 11)]
print(list7)

4 function

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 

4.1 Calculation 1 To N And

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)

5 exception handling

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 

5.1 practice 1

list1 = [10, 20, 30, 'abc', 20, 'UFO']
for i in list1:
try:
a = i / 10
print(a)
except Exception as err:
print(err)
continue

6 Tuples

Container data type
tuple
A tuple 、 Binary 、 Multiple groups

6.1 Define components

6.1.1 Define a tuple

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))

6.1.2 Binary

tuple_2 = (10, 20)
# Get tuple length len()
print(len(tuple_2))

6.2 Splicing

t1 = (20,)
t2 = (30, 10)
print(t1 + t2)

6.3 repeat

print(t1 * 3)

6.4 Members of the operation

print(10 in t2)

6.5 Indexes

print(t2[0])
print(t2[-1])

6.6 section

t3 = (10, 20, 30, 40, 50)
print(t3[:])
print(t3[2:4])
print(t3[::2])
print(t3[-1:-6:-1])

6.7 Create an empty tuple

t4 = ()
print(type(t4))
# Tuples are immutable types , Once created , No more changes , That is, you cannot add , Delete and other similar operations 

6.8 Packing and unpacking tuples

6.8.1 pack

a = 1, 2, 3
print(a, type(a))

6.8.2 Unpack

# 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)

6.9 Exchange the values of two variables

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)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved