Quick Introduction to python study Notes

  • 2020-06-15 09:19:29
  • OfStack

This article is not intended to teach you how to learn python, but for those who need more detailed and in-depth study, please refer to: Summary of Python Basic Language learning Notes (Essences). This article summarizes the notes and experience of learning python in one week's quick study of the basic knowledge of python.

##1: Syntax elements

Comment, variable, space use

annotation

Single-line comments begin with # and multi-line comments begin and end with ''

variable

Variables do not need to be declared before the data type, but must be assigned

Variable names can use a combination of upper and lower case letters, Numbers, and underscores, but only upper and lower case letters or underscores, not Spaces

Non-alphabetic symbols such as Chinese can also be used as names

Use of whitespace

The Spaces that represent indentation are immutable

Whitespace cannot split a name

In addition to the above two, the program can use any space to increase the readability of the program

Input function, output function

Input function

The input() function gets the user's input from the console using the variable =input(prompt message)

If the user input is saved in a variable as a string, such as val="28C", then val[-1] means that the substring of the first two characters of the last character "C" can be represented by val[0:2], representing the interval from 1 [0,2)

Output function

The %f data in print(" text ") is the value after the quotation marks. For example, print("the value of a is "%a)

Branch statement, loop statement

Branch statement A branch statement indicates the ownership of a branch by indentation

if < Condition 1 > : < The expression 1 > elif < Condition 2 > : < The expression of 2 > else : < The expression of 3 >

Loop statement The loop statement determines the number of runs of 1 segment of the program according to the judgment condition or counting condition, for example:


for i in range (10):< The expression group >

The above expression group will run the for loop 10 times. The number of loops will be fixed. Note that the indenting while is the same as C1, as well as break and continue ###4

Reserved words in

Determine if the content on the left is in the set on the right such as val[-1] in ['c','C'], if true, true; if not, false

Synchronous replication replicates multiple variables at the same time, that is, all expressions on the right are evaluated first, and then the expression result is assigned to the left simultaneously. For example, x and y exchange values x,y=y,x

import and def and turtle libraries

import import can bring in external libraries

def can define its own functions note that all indenting in def is a function in def

Reference library functions: from math import * or import math, but after this function you need to use the math. Function () to use the function


import turtle
def draw(rad,angle,len,neckrad):
for i in range(len):
turtle.circle(rad,angle)// Draw the radius and Angle of the circle 
turtle.circle(-rad,angle)
turtle.circle(rad,angle/2)
turtle.fd(rad)// Draw the length of the line 
turtle.circle(neckrad+1,180)
turtle.fd(rad*2/3) 
def main ():
turtle.setup(1300,800,0,0)// The launch window's width and height with the upper-left coordinates, down as y The axis, the right-hand side is theta x shaft 
pythonsize=30
turtle.pensize(pythonsize)// Width of track (pixels) 
turtle.pencolor("blue")// (Track color) 
turtle.seth(-40)// The direction in which you start moving 
draw(40,80,5,pythonsize/2)
main()

turtle draw five-point stars


from turtle import Turtle
p=Turtle()
p.speed(3)
p.pensize(5)
p.color("black","yellow")
p.fillcolor("red")
p.begin_fill()
for i in range (5):
p.forward(200)
p.right(144)
p.end_fill()

eval function vs. repr function

Evaluates a string as a valid Python expression and returns the result of the evaluation


x = 1
eval('x+1')
eval('x==1')

The repr function, which converts the variables and expressions of Python to string representations


repr(x==1)
repr(x+1)

##2. Data types

1. Integer type (unlimited value range limit)

decimal

0X,0x starts with a hexadecimal number

0b, 0B starts with base 2

0o, 0O starts with eight

Floating point Numbers Floating point Numbers can be counted scientifically, using e or E as symbols for powers, 1️ Base 10, for example 2ES186en-10 means 2 to the -10

The plural type z=a+bj,a is the real part, b is the imaginary part, the narrative part is identified by j or J, and the same bit floating-point type a and b, for example, z=12.3+4.2j for the plural z, the real and imaginary parts can be obtained by using z. real and z. imag

Integer - > Floating point Numbers - > There is a mixed operation between different numeric types of complex Numbers, the result of which is the widest type. The function can be converted between the three types: int(4.5)=4, float(4)=4.0, complex(4)=4+0j

The type of x can be obtained from type(x) and applies to all types

运算符或函数 作用
x//y 表示x/y商的整数部分
x%y 表示x/y商的余数部分
x**y 获得x的y次幂
divmod(x,y) 同时返回求商和余
pow(x,y) x的y次幂

String type

A string is one or more characters enclosed in double or single quotes

Strings can be stored in variables or stand alone

If you want to output quotation marks, prefix them with an escape character \

Strings can operate between + and *

The len(str) function returns the length of the str string

函数名称 作用
string.upper() 将字符串中字母大学
string.lower() 字母变为小写
string.capitalize() 首字母大写
string.strip() 去掉两边的空格及去掉指定字符
string.split() 按指定字符分割字符串为数组
string.isdigit() 判断是否是数字类型
string.find() 搜索指定字符串
string.replace() 字符串替换

Iterate over each character of the string for < var > in < string > :

A tuple type

A tuple contains multiple elements separated by commas. t=123,456,"hello"

Tuples can be empty t=()

The outside of a tuple can be either parenthesis or unparenthesis

Three characteristics of tuples

Elements in tuples can be of different types' t=12,32,("hello","world")

Elements in a tuple can be accessed by index such as t[1]

Tuples cannot be modified or deleted after they are defined

Like a string, some elements of a tuple can be accessed through an index interval such as t[1:]. Likewise, tuple views can be evaluated using the + and * operators

random and math library random can generate random Numbers, randomly generate lists, randomly pick Numbers and other math inventory mathematical functions

##python syntax ### exception handling


tre:
<body>
except <ErrorType1>:
<handler1>
except <ErrorType2>:
<handler2>
else :
<process_else>
finally:

First, execute the statement in try. If the error is reported, execute the exception handling statement in except. If there is no exception, continue processing the statement in else regardless of the exception

Boolean expression

and is equivalent to & &

So or is the same thing as |

not equivalent!

# # # def function < The function name > ( < parameter > ) : `

You do not need to return a type, but you can return any type of parameter

No return value returns return None

A function can return multiple values, separated by commas

### file operations

Open file open () function variable = open (disk file name, open the way) | operation name meaning | | | : - : | : - | | r | read only, if the file does not exist, the output error | | w | write only, if the file does not exist, create file | | a | attached to the end of the file | | rb | read only 2 into the file, if the file does not exist, the output error | | wb | write only two hexadecimal file, if the file does not exist, Then automatically create file | |ab| attached to the end of base 2 file | |r+| read and write | example code:


infile=open("number.dat","r")

| returns 1 string containing the entire contents of the file | |readline() |0 returns 1 string containing the contents of the entire file |1 |2 readlines() |3 returns a list of the entire contents of the file, with each line being ️ The 1-line string | ends with a newline character

The sample code

Output the text of the file


def main()
fname = input("Enter filename:")
infile = open(fname,"r")
data=infile.read()
print(data)
main()

write()| writes a string containing either text data or binary data blocks to a file | |writelines() |0 accepts a list of strings as parameters for the list operation, writes them to the file, and the line terminations are not automatically added to the |1 sample code


outfile=open("outfile.txt","w")
outfile.writeliens(["hello"," ","world"])
outfile.close()
infile=open("outfile.txt","r")
infile.read()


Related articles: