<> Variables and simple data types
variable
Naming of variables :
① Variable names can only contain letters , Numbers and underscores , Variable names can start with letters or underscores , But it cannot start with a number .
② Cannot Python Keywords and function names are used as variable names .
character string
A string is a series of characters ,Python in , Strings are enclosed in quotation marks , Quotation marks can be single quotation marks or double quotation marks .
Use the method to change the case of a string :
title() Show each word in uppercase , Change the first letter of each word to uppercase .
upper() Converts each letter of a string to uppercase .
lower() Converts each character of a string to lowercase .
Splice string :
Python Use plus sign (+) To merge strings .
first_name = "ada" last_name = "lovelace" full_name = first_name + " " +
last_nameprint(full_name) #ada lovelace
Add and remove whitespace :
\t Tab
\n Line feed
rstrip() Remove extra spaces at the end of the string .
lstrip Delete extra characters at the beginning of the string .
strip Delete spaces at both ends of the string .
number
integer : Can be executed on integers + - * / operation , Two multiplication signs ** Represents the power .
Floating point number :Python Numbers with decimal points are called floating point numbers .
notes : When using an integer in a string , You need to convert an integer to a string first .
for example : Want to output Happy 18th Birthday, You need to age Convert to string type age = 18 message = "Happy " + str
(age) + "th Birthday" print(message) #Happy 18th Birthday
<> list
A list consists of a series of elements arranged in a specific order , Can contain letters , Numbers and anything , Use square brackets [] To represent the list , And use commas to separate the elements .
1. Access list elements : List name [ Indexes ]
2. Add element at the end of the list : List name .append(“ Element value ”)
3. Insert element in list : List name .insert( Indexes ,“ Element value ”)
4. use del Delete list element :del List name [ Indexes ]
5. use pop Delete list element : method pop() You can delete the element at the end of the list , And can then use it . for example :
list1 = ["a","b","c"] list_pop = list1.pop() print(list_pop) #c print(list1)
#['a', 'b']
actually , have access to pop() Method pops up an element anywhere in the list , The pop-up element is no longer in the list , That is, delete elements anywhere , Simply specify the index of the element to be deleted in parentheses .
Delete element usage del still pop() :
If you want to delete an element from the list , And no longer use it in any way , Just use del sentence ; If you want to continue using the element after it is deleted , Just use pop() method .
6. Delete element based on value : When you don't know the position of the element to be deleted in the list , Only when you know the value of the element to be deleted , Available methods remove()
List name .remove(“ The value of the element to delete ”)
method remove() Delete only the first specified value , If you want to delete a value, it may appear more than once in the list , It is necessary to use the loop to determine whether all such values have been deleted .
7. use sort() Method to permanently sort the list : List name .sort() , Using this method, the order of list elements is permanently modified .
8. use sorted() Method to temporarily sort the list ,sorted(cars) , You can keep the original order of list elements , At the same time, the list elements can be displayed in a specific order .
9. List reverse order : List name .reverse()
10. Length list :len( List name )
11. Traversal list :
animals = ["dog", "cat", "pig"] for animal in animals: print(animal.title() +
",it's cute!") print("I like them") ''' Output results Dog,it's cute! Cat,it's cute!
Pig,it's cute! I like them '''
12. Create a list of values
use range() Function can easily generate a series of numbers , for example :
for i in range(1, 6): print(i) ''' Output results 1 2 3 4 5 ( Front closing and rear opening ) '''
use list() Function can directly range() Convert the results of to a list , for example :
numbers = list(range(1, 6)) print(numbers) ''' Output results [1, 2, 3, 4, 5] '''
Use function range() Time , You can also specify the step size , For example, the following code prints 1~10 Even number in :
evenNumbers = list(range(2, 11, 2)) print(evenNumbers) ''' Output results [2, 4, 6, 8,
10] '''
Calculate the list of numbers :
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] print(max(digits)) print(min(digits))
print(sum(digits)) ''' Output results 9 0 45 '''
13. List slice
animals = ["dog", "cat", "pig", "monkey", "bird"] print(animals[0:3]) #['dog',
'cat', 'pig'] print(animals[:4]) # The first index was not specified , The default slave index is 0 start ['dog', 'cat', 'pig',
'monkey'] print(animals[2:]) # No second index was specified , End at the end of the list by default ['pig', 'monkey', 'bird']
print(animals[-3:]) # A negative index returns the element at the corresponding distance from the end of the list ['pig', 'monkey', 'bird']
14. Traversal slice
If you want to traverse some elements of the list , Can be in for Use slice in loop .
for animal in animals[:3]: print(animal.title()) ''' Output results Dog Cat Pig '''
15. Copy list
① List to copy , You can create a slice that contains the entire list , The method is to omit both the start index and the end index . This gives you two lists , as follows :
animals = ["dog", "cat", "pig", "monkey", "bird"] animals2 = animals[:] animals
.append("snake") animals2.append("mouse") # Add element , The values of the two lists are different print(animals)
#['dog', 'cat', 'pig', 'monkey', 'bird', 'snake'] print(animals2) #['dog',
'cat', 'pig', 'monkey', 'bird', 'mouse']
② Assign the list directly to the new list
animals = ["dog", "cat", "pig", "monkey", "bird"] animals2 = animals animals.
append("snake") animals2.append("mouse") # Add element , The two list elements are the same print(animals) print(
animals2)
<> tuple
The list can be modified , But sometimes you need to create a series of elements that cannot be modified , Tuples can meet this need .Python
A value that cannot be modified is called immutable , The immutable list is called Yuanzu . Use parentheses to identify .
dimensions = (200, 50) # Accessing elements in tuples print(dimensions[0]) #200 print(dimensions[1]
) #50 # Traversing values in tuples for dimension in dimensions: print(dimension) # 200 50 # Modify tuple variable
dimensions= (400, 100) for dimension in dimensions: print(dimension) # 400 100
<>if sentence
use if Statement to check the current state of the program , And take corresponding measures .
age = 12 if age < 4: price = 0 elif age < 18: price = 5 elif age < 65: price =
10 else: price = 15 print("age:" + str(age) + ", price:" + str(price)) #age:12,
price:5
<> Dictionaries
A dictionary is a series of key value pairs , Each key is associated with a value , You can use the key to access the value associated with it . The value associated with the key can be a number , character string , Lists and even Dictionaries , That is, you can Python
Any object in is used as a value in the dictionary . Keys and values are separated by colons , Key value pairs are separated by commas .
animals = {'No1':'dog', 'No2':'cat', 'No3':'pig'} # Accessing values in the dictionary print(animals['No2'
]) # cat # Add key value pair animals['No4'] = 'monkey' animals['No5'] = 'snake' print(
animals) # {'No1': 'dog', 'No2': 'cat', 'No3': 'pig', 'No4': 'monkey', 'No5':
'snake'} # Modify values in the dictionary animals['No3'] = 'fish' print(animals) # {'No1': 'dog',
'No2': 'cat', 'No3': 'fish', 'No4': 'monkey', 'No5': 'snake'} # Delete key value pair del
animals['No1'] print(animals) # {'No2': 'cat', 'No3': 'fish', 'No4': 'monkey',
'No5': 'snake'} # Traverse all key value pairs in the dictionary for key, value in animals.items(): print("\nkey: "
+ key) print("value: " + value) ''' key: No2 value: cat key: No3 value: fish
key: No4 value: monkey key: No5 value: snake ''' # Traverse all keys in the dictionary for key in animals.
keys(): print(key.title()) ''' No2 No3 No4 No5 ''' # Traverse all values in the dictionary for value in
animals.values(): print(value.title()) ''' Cat Fish Monkey Snake '''
<> User input and while loop
function input()
function input() You can pause the program , Wait for the user to enter some text .
number = int(input(" Please enter a number :")) if number % 2 == 0: print(str(number) + " It's an even number ")
else: print(str(number) + " It's an odd number ")
while loop
while Continuous cycle operation , Until the specified conditions are not met .
number = 1 while number <= 5: print(number) number += 1 ''' When number greater than 5 Exit loop on 1 2
3 4 5 '''
If you want to exit now while loop , Don't run the rest of the loop , Available break sentence . If you want to return to the beginning of the loop , And decide whether to continue the cycle according to the condition test results , have access to
continue sentence .
# use break Exit loop prompt = "Please enter the name of a city:" while True: city =
input(prompt) if city == "quit": break ''' Please enter the name of a
city:Beijing Please enter the name of a city:Shanghai Please enter the name of
a city:quit Process finished with exit code 0 ''' # In circulation continue Return to the beginning of the loop
number= 0 while number < 10: number += 1 if number % 2 == 0: continue print(
number) ''' 1 3 5 7 9 '''
If you want to delete all elements in the list that contain a specific value , To delete all these elements , Should use while loop .
animals = ['dog', 'cat', 'pig', 'cat', 'cat', 'fish'] print(animals) # ['dog',
'cat', 'pig', 'cat', 'cat', 'fish'] while 'cat' in animals: animals.remove('cat'
) print(animals) # ['dog', 'pig', 'fish']
<> function
Functions are named blocks of code , Used to complete specific work .
# Pass a function whose parameters have no return value def sayHello(name): print("Hello, " + name) sayHello('Andy')
#Hello, Andy # Function with return value def getName(firstName, lastName): return firstName + " "
+ lastName print(getName('Andy', 'Liu')) #Andy Liu # Return dictionary def buildName(
firstName, lastName): ''' Returns a dictionary , It contains name information ''' return {'first':firstName, 'last':
lastName} print(buildName('Andy', 'Liu')) #{'first': 'Andy', 'last': 'Liu'} #
List as function parameter def users(names): for name in names: print("Hello, " + name) names = [
'Andy', 'Allen', 'Jay'] users(names) ''' Hello, Andy Hello, Allen Hello, Jay '''
# Pass any number of parameters def getMsg(age, *names): print(str(age) + " Years old people have :") for name in names
: print(name) getMsg(15, 'Andy') getMsg(18, 'Allen', 'Hannah', 'John')
''' Formal parameter name *names The asterisk in lets Python Create a file named names Empty tuple of , And encapsulate the value of income into this tuple 15 Years old people have : Andy 18 Years old people have :
Allen Hannah John ''' # Receive any number of key value pairs def buildProfile(first ,last, **userInfo):
''' Create an empty dictionary , Store information in ''' profile = {} profile['firstName'] = first profile[
'lasttName'] = last for key, value in userInfo.items(): profile[key] = value
return profile userProfile = buildProfile('albert', 'einstein', location =
'princeton', field = 'physics') print(userProfile)
''' Formal parameter name **userInfo The two asterisks in make Python Create a file named userInfo Empty dictionary , And encapsulate the key value pairs of revenue into this dictionary {'firstName':
'albert', 'lasttName': 'einstein', 'location': 'princeton', 'field': 'physics'}
'''
Functions can separate their code blocks from the main program , That is, the functions are stored in a separate file called a module , Then import the module into the main program . Just write one import
Statement and specify the module name in it , All functions in the module can be used in the program . Can use as Assign alias to function .
I'm fighting , Welcome criticism and correction !
Technology