Getting started with python-1

Main content: environment configuration, basic data type, basic sequence type

Reference: Getting started with python light speed at station B, python official documentation

python environment configuration

python release for windows vscode anconda environment configuration is recommended to use anconda vscode tutorial online Baidu many

Python basic data types

Numerical type bool bool

>>> bi=True  ##Capitalize the first letter otherwise an error will be reported
>>> b1=falseTraceback(most recent call last):
 File "<stdin>", line 1,in<module>
NameError: name 'false' is not defined
>>> b1=2>3>>>print(b1)
False

Numerical integer int and its operations +- /*

>>>3+36>>>7 /23.5>>>7//2 ####Divide 3>>>7%2 ####Find the remainder
1

Character type string

>>> s='abc'>>> s
' abc'>>> s="""abc
... def"""   #####Triple double quotation marks or three single quotation marks can be used for carriage return and line feed, and one side is used to write a lot of comments
>>> s
' abc\ndef'>>> s='abc\ndef' ######Single quotes need to add newlines
>>> s
' abc\ndef'>>>len(s) ###The length of the string
7>>> s="Haha 123">>> s
' Haha 123'>>>len(s) ###Python can directly recognize Chinese and detect a total of 5 characters
5>>> s1="123">>> t=s+s1 #####String splicing, can be added directly
>>> t
' Haha123123'>>> t=t+12 #####Can not be directly added to the int value
Traceback(most recent call last):
 File "<stdin>", line 1,in<module>
TypeError: can only concatenate str(not "int") to str
>>> t=t+str(12) ###Use str to convert an integer to a string
>>> t
' Lol 12312312'>>>isinstance(t,str) ###Used to judge whether it is a certain type
True

You can use built-in functions in Python to convert variable types

int(): Convert a numeric value or string into an integer, and you can specify the base float(): Convert a string into a floating point number. str(): Convert the specified object into a string form, you can specify the code chr(): Convert an integer into a string (a character) corresponding to the code ord(): Convert a string (a Character) into the corresponding code (integer)

Basic sequence type

list (list), turbo, range are similar to arrays in c language

Usage of list
>>> x=[1,2,3]###list can add elements
>>> type(x)<class'list'>>>> x.append(4) ###Add variables to the list
>>> x
[1,2,3,4]>>> x.append(2)>>> x
[1,2,3,4,2]>>> x[1] is x[4] ###Found that these two are identical
True
>>> t
[' a','d','c']>>> s=[1,2,3]>>> s+t   ###List addition
[1,2,3,' a','d','c']>>> x=s+t
>>> x
[1,2,3,' a','d','c']>>> x[3]="xtg"  ###List modification The objects in the list are modified, and the original objects will be released inside python
>>> x
[1,2,3,' xtg','d','c']>>> x*2  #####The list is multiplied by a number, the increase of each element of the list
[1,2,3,' xtg','d','c',1,2,3,'xtg','d','c']>>> x=[] ####Set an empty list
>>> x
[]>>> x.append(1) ###You can add elements to it
>>> x
[1]>>> x=[[]]*3 #####The three empty elements created in this way point to the same empty list
>>> x
[[],[],[]]>>> x[1].append(1)###Because it points to the same empty list, the definition will be the same
>>> x
[[1],[1],[1]]>>> x=[[],[],[]] ####The list created in this way is an empty list corresponding to three empty elements
>>> x
[[],[],[]]>>> x[1].append(1)####Adding one does not affect the other
>>> x
[[],[1],[]]
######### slice
>>> x=[1,2,3][1,2,3]>>> y=x[1:3] ####Excluding three and the list retrieved in this way is new and does not match the original one, that is, changing y does not change x.>>> y
[2,3]
Tuple
>>> x=(1,2,3)>>>x(1,2,3)>>>type(x)<class'tuple'>
##### List can be converted to tuple
>>> x=[1,2,3]>>> x
[1,2,3]>>> x=tuple(x)>>>x(1,2,3)>>>type(x)<class'tuple'>>>> x1=[1,2]>>> x2=[2,3]>>> x3=[4,5]>>> x=(x1,x2,x3)###Create tuple x
>>> x([1,2],[2,3],[4,5])>>> x1=["a","v"] ###x1 is equivalent to re-creating the list without changing x
>>> x([1,2],[2,3],[4,5])>>> x2.append(4) ###But if you add an element to the original list of x2, x will also increase because x references x2
>>> x([1,2],[2,3,4],[4,5])
String type

String creation can use single quotes', double quotes "", triple quotes """ """

>>> s="this is an apple">>> s
' this is an apple'>>>'i'm sam' #####If single quotes are used in the string, you need to add an escape character\,Otherwise it won&#39;t recognize
 File "<stdin>", line 1'i'm sam'
       ^
SyntaxError: invalid syntax
>>>' i\'m sam'
" i'm sam
###########\ The backslash does not want to be used as an escape character, you can add a prefix r, or add two\\
>>> s=r'd:\dir\t.txt'
**Format string: + (use plus signs for splicing),% (percent sign and tuple combination) **
>>> pattern ='%s is %d years old.'>>> pattern
' %s is %d years old.'>>> name ='tom'>>> age =12>>> msg = pattern %(name,age)  ######The type of percent sign plus tuple can be used as a format string pattern is(str % tuple)>>> msg
' tom is 12 years old.'>>> pattern ='%10s is %d years old.' #####Ten placeholders
>>> msg =pattern %(name,age)>>> msg
'  tom is 12 years old.'
Format string: format function

{ : Data type}.format() format brackets are the parameters that need to be added

>>> msg='{:d}+{:d}={:d}'.format(1,12,1+12)>>> msg
'1+12=13'
### Before the colon, you can specify which parameter to display
>>> msg='{1:d}+{0:d}={2:d}'.format(1,12,1+12)>>> msg
'12+1=13'
Format string: prefix f
>>> name,age('tom',12)>>> f'{name} is {age} years old''tom is 12 years old'

The string object is read-only and cannot be changed. If it is changed, a new object must be created

String method
>>> str.capitalize('trr') ####Capitalize the first letter
' Trr'>>> s ='hello, world!'>>>print(s.title()) ##Get a capitalized copy of each word in the string
Hello, World!>>>print(s.upper()) ####Obtain a copy of the string when it is capitalized
HELLO, WORLD!>>>print(s.find('or')) #Find the location of the substring from the string,Return if the difference is not found-18>>>print(s.find('t'))-1>>> s
' hello, world!'>>> s.replace('hello','hi')###Replacement string
' hi, world!'>>> text='1,2,3,4,5'>>> text
'1,2,3,4,5'>>> text.split(",") ####Separate the separator, for example, it is often used when reading text
['1','2','3','4','5']>>> text[2]'2'>>> text[2]='c'    ########The string is read-only and cannot be rewritten,Cannot be modified by removing the subscript
Traceback(most recent call last):
 File "<stdin>", line 1,in<module>
TypeError:'str' object does not support item assignment
>>> text[2:7] ###If you want to modify the way to remove the subscript, you can modify the string to a list
'2,3,4'>>> lt=list(text)>>> lt
['1',',','2',',','3',',','4',',','5']>>> lt[0]='a'>>> lt
[' a',',','2',',','3',',','4',',','5']>>> s='' ####If you want to change the list back to a string, which is troublesome, you can create an empty string first, add it at a time, and use a loop.
>>> s += lt[0]>>> s
' a'>>> s += lt[1]>>> s
' a,'>>> s += lt[2]>>> s
' a,2'

python structure control statement

if while for

if

score =int(input('hh input score: '))if score >=90:
 grade='A'
elif score>=80:
 grade='B'
elif score>=70:
 grade='C'else:
  grade='D'print(f'your grade is {grade}.') ###f string

while

i=1
sum=0while i<=100:
 sum +=i
 i +=1print(sum)

for

scores=[90,80,20,40,33,24,80]for scores in scores:if scores >=60:print("pass")else:print("nopass")
####################################
$ python python/python02/python02.py 
pass
pass
nopass
nopass
nopass
nopass
pass

Range is used in for statement
for i inrange(10):print(i)
$ python python/python02/python02.py 
0123456789
########### You can take out the subscript, then for a list, you can use range to take out all the values in the following table
score=[10,20,34,84,92,100]for i inrange(len(score)):print(score[i])
$ python python/python02/python02.py 
1020348492100
######## How can I get both the subscript and the value
score=[10,20,34,84,92,100]for score inenumerate(score):print(score)

$ python python/python02/python02.py(0,10)(1,20)(2,34)(3,84)(4,92)(5,100)

############ Tuples are replaced by values
>>> x=(1,2)>>> idx,score=x

score=[10,20,34,84,92,100]for idx,value inenumerate(score):print(idx,value)
 
$ python python/python02/python02.py 
0101202343844925100
######### I want to output the contents of the two lists zip package the two lists
score=[10,20,34,84,92,100]
names=['sam','tom','hhh','type','mary','lili']for score,names inzip(score,names):print(score,names)

$ python python/python02/python02.py 
10 sam
20 tom
34 hhh
84 type
92 mary
100 lili

Recommended Posts

Getting started with Python(18)
Getting started with Python(8)
Getting started with Python(4)
Getting started with Python (2)
Getting started with python-1
Getting started with Python(14)
Getting started with Python(7)
Getting started with Python(17)
Getting started with Python(15)
Getting started with Python(10)
Getting started with Python(11)
Getting started with Python(6)
Getting started with Python(3)
Getting started with Python(12)
Getting started with Python(5)
Getting started with Python (18+)
Getting started with Python(13)
Getting started with Python(16)
Getting started with Numpy in Python
Getting Started with Python-4: Classes and Objects
Getting started with python-2: functions and dictionaries
04. Conditional Statements for Getting Started with Python
Getting started python learning steps
How to get started quickly with Python
python requests.get with header
Play WeChat with Python
Web Scraping with Python
Implementing student management system with python
Centos6.7 comes with python upgrade to
Played with stocks and learned Python
Gray-level co-occurrence matrix (with python code)
Speed up Python code with Cython
How to make a globe with Python
Automatically generate data analysis report with Python
Create dynamic color QR code with Python
Python | Quickly test your Python code with Hypothesis
How to process excel table with python