Welfare is coming!! Python basic syntax dry goods

Programming Lao yuan 2021-11-25 18:48:14
welfare coming python basic syntax

In recent days , Give you a brief introduction to the basic python The content and difficulty of learning , And the direction of employment , It is estimated that everyone is interested in python I believe I have a certain foundation to understand . meanwhile , Lao yuan spent the afternoon tidying up here ,python Some basic operators and some strings are used and introduced , I hope my friends can finish it patiently , Study carefully .

Variable

What is a variable

In computer system , Variables are data stored in memory , Every time a variable is created, a memory space will be opened up in the system for its use .

We don't need to know how the created variables are stored in memory at this time , As long as you know i = 1 This is a variable assignment statement , among i Is a variable name. , This variable represents 1, The equal sign in the middle is the assignment operator .

Variable naming rule

• Case English 、 Numbers and _ The combination of , And can't start with a number ;

• System keywords cannot be used as variable names ; Get keyword list : help(‘keywords’)

• Python Variable names in are case sensitive ;

• Variable names cannot contain spaces , But you can use an underline to separate the words ;

• Do not use python The name of the built-in function is used as the variable name ;

Built in functions

abs()

delattr()

hash()

memoryview()

set()

all()

dict()

help()

min()

setattr()

any()

dir()

hex()

next()

slice()

ascii()

divmod()

id()

object()

sorted()

bin()

enumerate()

input()

oct()

staticmethod()

bool()

eval()

int()

open()

str()

breakpoint()

exec()

isinstance()

ord()

sum()

bytearray()

filter()

issubclass()

pow()

super()

bytes()

float()

iter()

print()

tuple()

callable()

format()

len()

property()

type()

chr()

frozenset()

list()

range()

vars()

classmethod()

getattr()

locals()

repr()

zip()

compile()

globals()

map()

reversed()

__import__()

complex()

hasattr()

max()

round()

Variable assignment process

x = 1 The equal sign in programming does not mean equal , yes assignment It means , hold 1 Assign a value to x

x = x + 1 So this statement is to put x+1 Then the value is assigned to x, here x The value of is 2

Advanced assignment process

Assign the same content to multiple variables at the same time : a = b = c = 100

Give different contents to multiple variables at the same time : a, b, c = 1, 2, 3

data type

Digital : Count

such as 1 、9999 、5.28 wait ;

character string :‘ ’ perhaps “ ”

such as ‘I love China’ 、‘ it's a nice day today ’ 、 “vndihgihb*@." wait ;

list :[ , , ]

such as [1,3,5.5,9.0] 、[“my",“name",“is",“Jack"] 、['qq',37] wait ;

Tuples :( , , )

such as (1.0,'two',3.89,'four') wait ;

Dictionaries :{ key1 : value1 , key2 : value2}

such as {‘name':‘Jack’,‘age’:15,‘country’:‘China’} wait ;

aggregate :{ , , }

such as {1,2,3,4,5} wait ;

Boolean type :

True perhaps False .

Digital

The numeric type can be divided into integers (int) And floating point numbers (float).

Arithmetic operator

Arithmetic operators are mainly used for arithmetic calculation .

Common operators mainly include the following :

Operator

describe

+

The addition operator

-

Subtraction operators

*

Multiplication operators

/

Division operator

**

Exponential operators

%

The remainder operator , Calculate the remainder

//

Division and rounding operator , Calculate the quotient and divide by its decimal part

Comparison operator

Compare the size of the value .

Common comparison operators mainly include the following :

Operator

describe

>

Judge whether the first operand is larger than the second operand

<

Judge whether the first operand is smaller than the second operand

>=

Judge whether the first operand is greater than or equal to the second operand

<=

Judge whether the first operand is less than or equal to the second operand

==

Judge whether the two operands are the same

!=

Judge whether two operands are different

character string

The string is composed of letters 、 A sequence of numbers and special characters . The string is indexed from left to right 0 At the beginning , The maximum range is less string length 1, Right to left index default -1 At the beginning , The maximum range is at the beginning of the string .

How to create a string ?

Use single quotes 、 Double quotes or triple quotes

For example :

Automatic detection

name='hanmeimei'

number="12"

paragraph='''Hello,makerbean!

Hello,world! '''

How to get the length of a string ?

len() function : Returns the length or number of characters in a string .

For example :

Automatic detection

s1='hello world'

s2='makerbean'

print(len(s1))

print(len(s2))

How to get characters in a string ?

With name='hanmeimei’ For example :

• Get a single character :

Automatic detection

print(name[0])

String built-in methods

Method

describe

.lower()

Convert uppercase letters in a string to lowercase letters

.upper()

Convert lowercase letters in a string to uppercase letters

.find(“x”)

lookup x The first subscript of the character

.replace(“old”,”new”)

Replace the string with another string

.count(“x”)

return x The number of times a character appears in a string

.isalpha()

Returns... If the string contains only letters true

.isdigit()

Returns if the string contains only numbers true

String connection

use “+” Connect two strings together .

Automatic detection

s1='hello'

s2='world'

print(s1+s2)# Forms a string

print(s1,s2)

Read user input data

use input() Function to obtain , Note that the resulting data is of string type .

Boolean expression

Boolean value

Used to indicate yes or no in judgment , Generally used in condition testing ;

• The value is only True 、False ;

Logical operations

Used to detect whether two or more conditions are met ; Logical operations exist only in Boolean types .

and , Logic “ And ” When both operands on both sides of the operator are True when , The result is True ;

or , Logic “ or ” When there are two operands on both sides of the operator, one of the operands is True when , The result is True;

not , Logic “ Not ” Used to reverse the state of an operand .

Boolean expression

Examples are as follows :

Automatic detection

>>>3 and 5

5

>>>3 or 5

3

>>>0 or 5

5

>>>3 and not 5

False

Application of expressions —— Conditions for testing

Check whether the current variable is equal to a specific value / It's not equal ;

Compare the size of the number  ;

Check whether a specific value is in a sequence  .

Application of expressions —— Multi condition check

Use and Check multiple conditions :

Automatic detection

age_lilei = 17

age_hanmeimei = 18

age_lilei >= 18 and age_hanmeimei >=18

False

Use or Check multiple conditions :

Automatic detection

age_lilei >= 18 or age_hanmeimei >= 15

True

Automatic detection

age_lilei >=20 or age_hanmeimei >= 20

False

Python Code indentation problem

use Four spaces Or a Tab To represent indentation , But don't mix it up ;

Code with the same indentation indicates that they are the same code block  ;

if conditional

conditional ——if/else

If   It will rain tomorrow

Stay at home and play games

Otherwise, if   Court open

Go out and play

otherwise

Go to the library for self-study

It will rain tomorrow ——> Stay at home and play games

It won't rain tomorrow And Court open ——> Go out and play

It won't rain tomorrow And The court is closed ——> Go to the library for self-study

Examples are as follows ( Judge what the user has entered ):

Automatic detection

user_gender = input(" Please enter your gender (F/M):")

if user_gender == 'F':

print(" You're a cute girl ")

elif user_gender == 'M': # elif yes else if Abbreviation

print(" You are a rough man ")

else: # without else Statement and none of the preceding conditions are met, then nothing is output

print(" Incorrect input , Please enter F or M")

Assignment is equal to judgment

Single equal sign = It's assignment

such as :a = 3 , Express the 3 Assign a value to a

Double equal sign == Is to judge equality

such as :if a == 3: , Said if a The value is equal to the 3

Column surface

List structure

• Use square brackets to represent the list

• The elements in the list are separated by commas

• Note the comma under the English input method , For example :

Automatic detection

student1 = ['lilei',18,'class01',201901]

student2 = ['hanmeimei',19,'class02',201902]

The list has variability : You can modify the contents of the list

Get the elements in the list

In programming languages, the number of the first position is 0, And so on .

The following list is an example :

Automatic detection

grade = [98,99,95,80]

Get an element of the list , The position of the element is usually enclosed in square brackets .

Automatic detection

print(grade[0])

print(grade[0]+grade[3])

Display after running

Automatic detection

98

178

List common methods

Get list length len( list )

Automatic detection

student_list = [' Li lei ',' Han Meimei ',' Ma Dongmei ']

print(len(student_list))

Get the elements in the list Find the element number that needs to be modified , List name [ Number ]= The new value

Automatic detection

student_list = [' Li lei ',' Han Meimei ',' Ma Dongmei ']

student_list[0] = 'lilei'

Add elements to the list List name .append( Elements to add )

Automatic detection

inventory = [' The key ',' poison ']

inventory.append(' Antidote ')

Delete list elements del+ List element delete

Automatic detection

student_list = [' Li lei ',' Han Meimei ',' Ma Dongmei ']

del student_list[0]

Add two lists list 1+ list 2

Automatic detection

numbers1 = [0,1,2,3,4]

numbers2 = [5,6,7,8,9]

print(numbers1+numbers2)

Determine whether an element exists in the list in

Automatic detection

inventory = [' The key ',' poison ',' Antidote ']

if ' Antidote ' in inventory:

print('yes')

else:

print('no')

Gets the number of repetitions of an element in the list Use list .count( Elements ) To get

Automatic detection

numbers1 = [0,1,1,2,3,4,1]

print(numbers1.count(1))

Get the position of the first occurrence of an element in the list Use list .index( Elements ) To get

Automatic detection

numbers1 = [0,1,1,2,3,4,1] print(numbers1.index(1))

word Dian

Structure of dictionary

{key:value,key:value}

{ key : Key value }

• Use curly braces to represent the dictionary

• Every item in the dictionary consists of two elements :key and value,key and value One-to-one correspondence , The same key can only have one corresponding value ,

• The items are separated by commas

• The type of key is immutable . For example :

Automatic detection

phone_numbers = {' Li lei ':'123456',' Han Meimei ':'456',' Ma Dongmei ':'45678'}

print(phone_numbers)

Access data in the dictionary

Variable [key] , For example :

Automatic detection

grade = {' Li lei ':'98',' Han Meimei ':'99'}

print (grade[' Li lei ']) # Access the data in the dictionary

Update dictionary elements

Variable [key] = The new value

Automatic detection

grade = {' Li lei ':'98',' Han Meimei ':'99'}

grade[' Han Meimei '] = 100 # Update dictionary elements

print(grade)

Dictionary deletion operation

Automatic detection

grade = {' Li lei ':'98',' Han Meimei ':'99',' Ma Dongmei ':'95'} del grade[' Li lei ']

# Delete an item from the dictionary grade.clear() del grade

# Delete the dictionary itself del grade 

There are more dry goods today , You can collect your favorite friends and look at them slowly , Don't forget the zanga collection to facilitate learning , If you don't know how to leave a message in the welcome comment area !!!

版权声明
本文为[Programming Lao yuan]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/11/20211109102437279x.html

  1. python3.7 FileNotFoundError: [WinError 2] 系统找不到指定的文件。
  2. 最全面的Python重点知识汇总
  3. python中 我想爬取一个网页,我在cmd中pip list中已经把requests 以及bs4 弄好了 但是他还是提示我没有那个模块
  4. You can learn Python articles without reading online classes (the first day)
  5. 在Python和Go项目之后使用Rust的经验分享 - scaleway
  6. 使用PyO3从Python调用 Rust:加速Python
  7. Python 3.7 filenotfounderror: [winerror 2] le système n'a pas pu trouver le fichier spécifié.
  8. Python 一切皆对象
  9. 【Pandas学习笔记01】强大的分析结构化数据的工具集
  10. 求各位亲们可以解答一下嘛,为什么跑不出来呀,大学Python
  11. 【Pandas学习笔记01】强大的分析结构化数据的工具集
  12. python飞机大战如何让飞机始终在界面中,不能跑出界面
  13. Python代码阅读(第63篇):数字奇偶性
  14. python建立⼀個圖形介⾯應⽤(GUI app)
  15. python接口自动化的html格式报告以邮件形式发送展示的原文很丑怎么处理
  16. 针对初学者,我建议你学这 3 个 Python AutoEDA 工具包
  17. #yyds干货盘点#Python-爬虫_urlib一个类型和六个方法
  18. Pour les débutants, je vous recommande d'apprendre ces 3 kits autoeda Python
  19. 我想问python怎么入门嘞?求各路人士
  20. Summary of today's Django lessons: data reverse query triggers error field 'score_ jieshoufankui‘ expected a number but got ‘‘-20211109
  21. 关于#python_while循环的写法#的问题,如何解决?
  22. Python异常处理中异常的种类有哪些?你知道几个?
  23. Python异常處理中异常的種類有哪些?你知道幾個?
  24. Quels sont les types d'exceptions dans la gestion des exceptions python? Combien en savez - vous?
  25. À propos de # Python Comment résoudre le problème de l'écriture de la Boucle while?
  26. Python如何操作system.data.sqlite数据库
  27. python数字游戏,让你欲罢不能
  28. Python中的可迭代对象、迭代器、For循环工作机制、生成器
  29. 一个从没接触过编程的人,如何自学进入Python行业?
  30. 一份超级实用的 Python ”技巧“清单
  31. Python 程序员给上路初学者的3点忠告
  32. 3 conseils pour les débutants sur la route par les programmeurs Python
  33. Une liste de conseils Python super pratiques
  34. Comment quelqu'un qui n'a jamais été en contact avec la programmation peut - il apprendre à entrer dans l'industrie python?
  35. Objets itérables, itérateurs, pour le mécanisme de travail circulaire, générateurs en python
  36. Les Jeux de chiffres Python vous font vous arrêter
  37. Comment Python fonctionne avec la base de données system.data.sqlite
  38. Python之html与markdown互相转换
  39. Python之html與markdown互相轉換
  40. Conversion HTML et markdown de Python
  41. Python生成的随机数,要怎么设定成随机数a小于随机数b啊
  42. Python生成的隨機數,要怎麼設定成隨機數a小於隨機數b啊
  43. Le nombre aléatoire généré par Python, comment définir le nombre aléatoire a est inférieur au nombre aléatoire B
  44. Python爬虫能做什么
  45. Python老技师给上路初学者的3点忠告
  46. 3 conseils aux débutants sur la route de l'ancien technicien Python
  47. Que peuvent faire les reptiles Python
  48. The code NPM cloned from git will report a python error after it is installed!
  49. 数据分析从零开始实战,Pandas读写CSV数据
  50. Python基础(十二):类与对象
  51. Python Foundation (12): classes et objets
  52. Python基礎(十二):類與對象
  53. L'analyse des données commence à zéro et pandas lit et écrit les données CSV
  54. Python Qt GUI设计:QSlider滑动条类(基础篇—16)
  55. #yyds干货盘点#数据分析从零开始实战,Pandas读写CSV数据
  56. This paper designs an examination system for automatically setting questions and judging papers by using Python standard library language to investigate the ability of users to calculate four integers within 100.
  57. Yyds Dry Inventory # Data Analysis started from zero, pandas read and write CSV Data
  58. python数据结构:数组、列表、栈、队列及实现
  59. Python编程真的是未来人工智能的主流吗?
  60. Python编写通讯录,支持模糊查询,利用数据库存储