This is the fifth day of my participation in Gwen Challenge


The introduction

Here is a list of some basic Python syntax to give beginners a general idea of Python syntax.


Python annotation

Single-line comments

Everything to the right of the # is treated as a caption, not as an actual program to be executed, but as an auxiliary illustration

#! /usr/bin/python3
# -*- coding:utf-8 -*-

# This is the first one-line comment
print('hello python')

print('hello world')	# second one-line comment
Copy the code


Multiline comment

To use multi-line comments in Python programs, you can use a pair of three consecutive quotes (either single quote “” or double quote “” will work)

#! /usr/bin/python3
# -*- coding:utf-8 -*-

""" This is a multi-line comment type Hello Hui """
print('hello hui')
Copy the code


identifier

Identifiers are programmer – defined variable names, function names, class names, and so on.


  • Identifiers can consist of letters, underscores, and numbers
  • You can’t start with a number
  • Identifiers are case-sensitive


Python keywords

  • The keywordIs in thePythonAn identifier that is already used internally
  • Keywords have special functions and meanings


All the keywords in Python 3.7.9 are shown below:

'False'.'None'.'True'.'and'.'as'.'assert'.'async'.'await'.'break'.'class'.'continue'.'def'.'del'.'elif'.'else'.'except'.'finally'.'for'.'from'.'global'.'if'.'import'.'in'.'is'.'lambda'.'nonlocal'.'not'.'or'.'pass'.'raise'.'return'.'try'.'while'.'with'.'yield'
Copy the code


Python simple data types

  • String typestr
  • Integer typesint
  • Floating point typefloat
#! /usr/bin/python3
# -*- coding:utf-8 -*-

# string type variable
name = 'hui'

Integer type variable
age = 21

Float type variable
price = 520.1314

Copy the code


A primer on Python operators

Arithmetic operator

The operator describe The instance
+ add 3 + 6
- Reduction of Ten to five
* take 10 * 20
/ In addition to 10/20
// Take the divisible Returns the integer part of the division (quotient)9 / / 2Output Result 4
% modulo Returns the remainder of the division9% 2
支那 power Also known as power, power,2 * * 3


Comparison operator

Let’s say x is equal to 20, y is equal to 30

The operator describe The instance
= = Is equal to the Return False
! = Is not equal to (a ! = b) returns True
> Is greater than A > b returns False
< Less than (a < b) returns True
> = Greater than or equal to (a >= b) returns False
< = Less than or equal to (a <= b) returns True


The assignment operator

The operator describe The instance
= A simple assignment operator C = a + b Assigns the result of a + b to c
+ = The addition assignment operator C plus a is the same thing as c is equal to c plus a
- = The subtraction assignment operator C minus a is the same thing as c minus a
* = Multiplication assignment operator C times a is the same thing as c times a
/ = The division assignment operator C/a is the same thing as c = c/a
/ / = Takes the divisible assignment operator C //= a is equivalent to c = c // a
% = takedie(remainder) assignment operator C %= a is the same thing as c = c % a
* * = Power assignment operator c **= aEquivalent to c = c** a


Logical operator

The operator Logical expression describe
and x and y Boolean “and”– x and y returns the value of x if x is False, otherwise returns the calculated value of y.
or x or y Boolean “or”– If x is True, it returns the value of x, otherwise it returns the calculated value of y.
not not x Boolean “not”– If x is True, return False. If x is False, it returns True.


There are a few other operators in Python, and I won’t list them here. There will be a section on testing Python operators later

  • An operator
  • Member operator
  • Identity operator


Python branch structure

Single IF judgment

#! /usr/bin/python3
# -*- coding:utf-8 -*-

name = 'hui'

if name == 'hui':
    print('my name is hui')
    
My name is hui
Copy the code


if … else … judge

#! /usr/bin/python3
# -*- coding:utf-8 -*-

age = 21

if age < 23:
    print(Little Sister)
else:
    print('Sister Beauty')
    
The output is: little sister
Copy the code


if … elif … The else judge

#! /usr/bin/python3
# -*- coding:utf-8 -*-

score = 85

if score < 60:
    print('Fail')
elif score < 70:
    print('pass')
elif score < 80:
    print('medium')
elif score < 90:
    print('good')
else:
    print('good')
    
The output is: good
Copy the code


Python loop structure

There are two loop structures in Python called

  • The for loop
  • The while loop


The for loop

#! /usr/bin/python3
# -*- coding:utf-8 -*-

for i in range(3) :print(i)
   
# The result is as follows
# 0
# 1
# 2
Copy the code


The while loop

#! /usr/bin/python3
# -*- coding:utf-8 -*-

The sum up to # 100
result = 0

# define an integer variable to record the number of cycles
i = 0

# start loop
while i <= 100:

    result += i
    i += 1
    
print(result)	The result is 5050
Copy the code


Python functions

Definition of a function

defThe function name () :The body of the function... Such as:def hello() :
    print('hello python')
    
Copy the code


Function call

#! /usr/bin/python3
# -*- coding:utf-8 -*-

name = 'ithui'

def say_hello() :
    print("hello 1")
    print("hello 2")
    print("hello 3")
    
print(name)

say_hello()

The output is as follows:
# ithui
# hello 1
# hello 2
# hello 3
Copy the code


The use of function passing parameters

#! /usr/bin/python3
# -*- coding:utf-8 -*-

a = 10
b = 20

def sum(x, y) :
    z = x + y
    print(z)

sum(a, b)	30 # output
Copy the code


Python advanced data types

List the list

  • list(List) YesPythonThe use ofThe most frequentIn other languages, it is usually calledAn array of
  • The list with[]Definition,dataUsed between.separated
  • Can be achieved byThe indexGet elements such as[0]Index can also be calledThe subscript
#! /usr/bin/python3
# -*- coding:utf-8 -*-

li = [1.2.3.4.5]

# print list
print(li)	# [1, 2, 3, 4, 5]

Get the 0th element of the list
print(li[0])	# 1
Copy the code


Tuples tuple

  • TupleTuples are similar to lists except that of tuplesElements cannot be modified
  • A tuple with(a)Definition,dataUsed between.separated
  • Get elements by index
#! /usr/bin/python3
# -*- coding:utf-8 -*-

t = (1.2.3)

Print a tuple
print(t)	# (1, 2, 3)

Get the 0th element of the tuple
print(t[0])	# 1
Copy the code


The dictionary dict

  • dict(Dictionary) yesApart from the list PythonAmong theThe most flexibleData type of
  • Dictionary use{}define
  • Dictionary useKey/value pairStore data, used between key-value pairs.separated
#! /usr/bin/python3
# -*- coding:utf-8 -*-

person = {
    'name': 'hui'.'age': 21.'gender': True.'height': 1.75
}

Get the value based on the corresponding key
print(person['name'])    	# hui
print(person['age'])    	# 21
print(person['gender'])    	# True
print(person['height'])    	# 1.75
Copy the code


Set the set

  • setA set is similar to a list except that of a setElements do not repeat
  • Sets are also used{}Definition, but used between elements.separated
#! /usr/bin/python3
# -*- coding:utf-8 -*-

name_set = {'hui'.'wang'.'zack'.'hui'}

print(name_set)    	{'hui', 'wang', 'zack'}

Copy the code


Python class

Class to describe a collection of objects that have the same properties and methods. It defines the properties and methods that are common to each object in the collection. An object is an instance of a class. Python uses the class keyword to define classes

#! /usr/bin/python3
# -*- coding:utf-8 -*-

# define classes
class User:
    
    # class attribute
    name = 'hui'
    age = 21
    
    # methods
    def get_age(self) :
        print(self.age)
        return self.age

Create class object
user = User()

Access class properties and methods
print(user.name)
user.get_age()
Copy the code


The tail language

✍ Code writes the world and makes life more interesting. ❤ ️

✍ thousands of rivers and mountains always love, ✍ go again. ❤ ️

✍ code word is not easy, but also hope you heroes support. ❤ ️