The most basic syntax of Python


1. Introduction

1. Python security path

3.7.3

https://www.python.org/downloads/release/python-372/

2. Python development tools (PyCharm)

community edition

https://www.jetbrains.com/pycharm/download/#section=mac

2. Use of PyCharm

1. New project location

insert image description here

2、Hello World

print("hello Word");

insert image description here

3. Check the python version

version 2.0

python -V

version 3.0

python3 -V

4. PEP8 specification

python writing specification

After a single-line comment, you need to add a space

# 注释(正确)
#注释

3. Identifiers and keywords

identifier:

Identifiers consist of letters, underscores, and numbers, and numbers cannot begin with

Naming rules:

用下划线“_”来连接所有的单词

keywords:

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', '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']
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del',  'except', 'finally', 'for', 'from', 'global',  'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

Logical judgment statement:

'if','elif', 'else',

4. Basic data types

1. Data type

The data type in a variable is defined by data.

It can be used type( ), and the type of data can be queried.

# 数据类型
# int类型:(<class 'int'>)
a = 18
print(type(a))

# float类型: <class 'float'>
b = 18.8
print(type(b))

# str类型:<class 'str'>包含单引号和双引号
c = 'lydms'
print(type(c))

# bool类型:<class 'bool'>
e = True
f = False
print(type(e))
print(type(f))

insert image description here

2. Multiple data assignment:

a = b = c = 100
print(a)
print(b)
print(c)

result:

100
100
100
e, f, g = 1, 2, 3
print(e)
print(f)
print(g)

result:

1
2
3

3. Standard data types

  • Number
  • String (string)
  • List (list)
  • Tuple
  • Set (collection)
  • Dictionary

Among the six standard data types of Python3:

  • **Immutable data (3): **Number (number), String (string), Tuple (tuple);
  • **Variable data (3): **List (list), Dictionary (dictionary), Set (collection).

4. Formatted output

Below is the complete list which can be used with the % sign:

formatting symbols convert
%c character
%s string
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x Hexadecimal integer (lowercase 0x)
%X Hexadecimal integer (capital letter 0X)
%f floating point number
%e scientific notation (lowercase 'e')
%E scientific notation (capital "E")
%g Shorthand for %f and %e
%G Shorthand for %f and %E

Specific use

print("hello")
print(123)

# 会输出(lydms 18)。中间以空格隔开
print('lydms', 18)

# 输出1+2的结果(3)
print(1 + 2)

# 字符串占位符(%s),后面用(%name),进行数据的站位(我的名字是lydms,我很开心)
name = 'lydms'
print("我的名字是%s,我很开心" % name)

age = 18
print("我的年龄是%d" % age)

size = 170.2
print("我的身高是%f" % size)  # 全部的(我的身高是170.200000)
print("我的身高是%.2f" % size)  # 保留2位小数(我的身高是170.20)

# 格式化输出(分数比例为18%)
print("分数比例为%d%%" % age)

Multi-field output

print("我的姓名%s,年龄是%d" % (name, age))
print(f"我的姓名{
      
      name},年龄是{
      
      age}")

Newline and specified end value

# 指定最后输出值
print("换行的")  # 有换行符
 # 无换行
print("不换行的", end="")
# 指定末尾值
print("指定末尾值", end="123")

# 任意位置换行(\n)
print("任意位置\n换行")

5. Input

# 计算商品的价格
price = input("请输入价格:")
weight = input("请输入重量:")
# 计算价格
result = float(price) * float(weight)
# 打印结果
print(f"价格为:{
      
      price},重量为{
      
      weight}。需要支付价格为{
      
      result}")

6. Format conversion

# 1、Float类型转为int
pi = 3.14
num = int(3.14)
# <class 'float'>
print(type(pi))
# <class 'int'>
print(type(num))

# 2、整数类型的字符串
my_str = '10'
num1 = int(my_str)
# <class 'str'>
print(type(my_str))
# <class 'int'>
print(type(num1))
print("=========")
# 转为float
# int-->float
num2 = 10
num3 = float(num2)
# <class 'int'>
print(type(num2))
# <class 'float'>
print(type(num3))

# 数字转为float

num4 = float("3.14")
num5 = float("10")
# <class 'float'>
print(type(num4))
print(type(num5))

# 还原之前的数据类型
num6=eval("19")
num7=eval("18.4")
num8=eval("num7")
# num8=eval("hello") 报错

print(type(num6)) # int
print(type(num7)) # float
print(type(num8)) # float

4. Number (digital)

z, x, c, v = 20, 5.5, True, 4 + 4j
print(type(z), type(x), type(c), type(v))
print(a, x, c, v)

result:

<class 'int'> <class 'float'> <class 'bool'> <class 'complex'>
100 5.5 True (4+4j)

Data type judgment isinstance( ):

az = 2111
print(isinstance(az, int))
>>>
Ture

4.1. Delete

When you delete it print(var1,var2), the following will report an error

var1 =1
var2 =3
print(var1,var2)
del var1
print(var1,var2)

4.2 Addition, subtraction, multiplication and division

>>> 5 + 4  # 加法
9
>>> 4.3 - 2 # 减法
2.3
>>> 3 * 7  # 乘法
21
>>> 2 / 4  # 除法,得到一个浮点数
0.5
>>> 2 // 4 # 除法,得到一个整数
0
>>> 17 % 3 # 取余
2
>>> 2 ** 5 # 乘方
32

5. String (string)

5.1, character interception

insert image description here

str = 'Runoob'
print (str)          # 输出字符串
print (str[0:-1])    # 输出第一个到倒数第二个的所有字符
print (str[0])       # 输出字符串第一个字符
print (str[2:5])     # 输出从第三个开始到第五个的字符
print (str[2:])      # 输出从第三个开始的后的所有字符
print (str * 2)      # 输出字符串两次,也可以写成 print (2 * str)
print (str + "TEST") # 连接字符串

5.2, character escape

Python uses backslashes \to escape special characters. If you don't want backslashes to be escaped, you can add one in front of the string rto represent the original string:

>>> print('Ru\noob')
Ru
oob
>>> print(r'Ru\noob')
Ru\noob

6. List (list)

List (list) is the most frequently used data type in Python.

Lists can complete the data structure implementation of most collection classes. The types of elements in the list can be different, it supports numbers, strings can even contain lists (so-called nesting).

A list is a comma-separated list of elements written between square brackets [] .

Like strings, lists can also be indexed and truncated. After the list is truncated, a new list containing the required elements is returned.

The syntax format of list interception is as follows:

变量[头下标:尾下标]

string comparison

list = [ 'abcd', 786 , 2.23, 'runoob', 70.2 ]
tinylist = [123, 'runoob']

print (list)            # 输出完整列表
print (list[0])         # 输出列表第一个元素
print (list[1:3])       # 从第二个开始输出到第三个元素
print (list[2:])        # 输出从第三个元素开始的所有元素
print (tinylist * 2)    # 输出两次列表
print (list + tinylist) # 连接列表

List interception, can receive the third parameter.

变量[头下标:尾下标:步长]

insert image description here

5. Simple Grammar

1. Print

# 换行输出
print( "test01" )

Output without wrapping (specify end character)

# 不换行输出
print( "test02", end=" " )

Guess you like

Origin blog.csdn.net/weixin_44624117/article/details/131467078