A Beginner's Guide to Python: Learn Python Programming from Scratch

foreword

Python is a simple yet powerful programming language that has gained worldwide popularity for a variety of application scenarios, including web development, data analysis, artificial intelligence, and scientific computing, among others. This blog will provide beginners with an introductory guide to Python to help you master the basics of Python programming from scratch.

Install Python

First, we need to install the Python interpreter. Go to the Python official website (https://www.python.org/) to download the latest version of Python, and then follow the installation wizard to install it. During the installation process, be sure to check the "Add Python to system environment variables" option so that you can run Python on the command line.
You can also refer to: Python download and environment installation

Variables and Data Types

1. Definition of variables

For data that is reused and often needs to be modified, it can be defined as a variable to improve programming efficiency.
The syntax for defining a variable is: variable name = variable value. (The role of = here is to assign a value.)
After defining a variable, you can use the variable name to access the variable value.
A variable is a variable quantity that can be modified at any time.
Programs are used to process data, and variables are used to store data.

name = '小尘要自信'

2. The type of variable

In python, as long as a variable is defined and has data, its type has been determined, and the system will automatically identify it without the need for the developer to take the initiative to explain its type. That is to say, when using it, "variables have no type, but data have type".

Number: int (signed integer), long (long integer), float (floating point), complex (complex), Boolean
: true, false
string: string
List: list
Tuple: tuple
dictionary: dictionary

# int
age = 18
# float
money = 18.0
# boll 男  True
sex = True
gender = False

# string 
# 字符串 使用的是单引号 或者双引号
s = '小尘要自信'
# list  列表
# 应用场景:当获取到了很多个数据的时候 那么我们可以将他们存储到列表中 然后直接使用列表访问
name_list = ['罗志祥','吴亦凡']
print(name_list)
# tuple 元组
age_tuple = (18,19,20,21)
print(age_tuple)
# dict  字典
# 应用场景:scrapy框架使用
# 格式:变量的名字 = {
    
    key:value,key1:value1}
person = {
    
    'name':'小尘要自信','age':18}
print(person)

If you want to check the data type stored in a variable temporarily, you can use type (the name of the variable) to check the data type stored in the variable.

a = type(age)
print(a)
  • string

Common operations on strings include:
Get length: len The len function can get the length of a string.

s = 'china'
print(len(s))

Find content: find finds whether the specified content exists in the string, and returns the index value of the first occurrence of the content in the string if it exists, or returns -1 if it does not exist

s1 = 'china'
print(s1.find('a'))

Judgment: startswith, endswith Judging whether the string starts/ends with so and so

s2 = 'china'
print(s2.startswith('h'))
print(s2.endswith('n'))

Count the number of occurrences: count returns the number of times str appears in mystr between start and end

s3 = 'aaabb'
print(s3.count('b'))

Replacement content: replace replaces the content specified in the string. If count is specified, the replacement will not exceed count times.

s4 = 'cccdd'
print(s4.replace('c','d'))

Cut the string: split cuts the string by the content of the parameter

s5 = '1#2#3#4'
print(s5.split('#'))

Modify the case: upper and lower exchange the upper and lower case in the string

s6 = 'china'
print(s6.upper())
s7 = 'CHINA'
print(s7.lower())

Space processing: strip to remove spaces

s8 = '   a   '
print(len(s8))
print(len(s8.strip()))

String splicing: join string splicing

s9 = 'a'
print(s9.join('hello'))
  • the list

  • add element

append adds elements at the end

# append  追加   在列表的最后来添加一个对象/数据
food_list = ['铁锅炖大鹅','酸菜五花肉']
print(food_list)
food_list.append('小鸡炖蘑菇')
print(food_list)

insert inserts an element at the specified position

char_list = ['a','c','d']
print(char_list)
# index的值就是你想插入数据的那个下标
char_list.insert(1,'b')
print(char_list)

extend merges two lists

num_list = [1,2,3]
num1_list = [4,5,6]
num_list.extend(num1_list)
print(num_list)
  • modify element

List elements are accessed by specifying a subscript, so when modifying an element, assign a value to the specified list subscript to modify the element

city_list = ['北京','上海','深圳','武汉','西安']
print(city_list)
# 将列表中的元素的值修改
# 可以通过下标来修改,注意列表中的下标是从0开始的
city_list[4] = '大连'
print(city_list)
  • find element

The so-called search is to see if the specified element exists. It mainly includes the following methods:
in and not in
in, not in
The common method of searching in python is:
in (exist), if it exists, the result is true, otherwise it is false
not in (does not exist), if it does not exist then the result is true, otherwise false

# in 是判断某一个元素是否在某一个列表中
# food_list = ['锅包肉','汆白肉','东北乱炖']

# 判断一下在控制台输入的那个数据 是否在列表中
# food = input('请输入您想吃的食物')
#
# if food in food_list:
#     print('在')
# else:
#     print('不在,一边拉去')


# not in

ball_list = ['篮球','台球']

# 在控制台上输入你喜欢的球类 然后判断是否不在这个列表中
ball = input('请输入您喜欢的球类')

if ball not in ball_list:
    print('不在')
else:
    print('在')
  • delete element

It is analogous to real life, if a classmate is transferred, then the name of the student after this entry should be deleted; this function of deleting is often used in development.
The common deletion methods of list elements are:
del: delete according to the subscript
pop: delete the last element
remove: delete according to the value of the element

# in 是判断某一个元素是否在某一个列表中
# food_list = ['锅包肉','汆白肉','东北乱炖']

# 判断一下在控制台输入的那个数据 是否在列表中
# food = input('请输入您想吃的食物')
#
# if food in food_list:
#     print('在')
# else:
#     print('不在,一边拉去')


# not in

ball_list = ['篮球','台球']

# 在控制台上输入你喜欢的球类 然后判断是否不在这个列表中
ball = input('请输入您喜欢的球类')

if ball not in ball_list:
    print('不在')
else:
    print('在')
  • tuple

Python's tuples are similar to lists, except that the elements of the tuple cannot be modified. Use parentheses for tuples and square brackets for lists.
Accessing tuples
Modifying tuples
Python does not allow modifying the data of tuples, including deleting elements.
Define a tuple with only one data
To define a tuple with only one element, you need to write a comma after the only element

# a_tuple = (1,2,3,4)
# print(a_tuple[0])
# print(a_tuple[1])
# 元组是不可以修改里面的内容的
# a_tuple[3] = 5
# print(a_tuple)
# a_list = [1,2,3,4]
# print(a_list[0])
#
# a_list[3] = 5
# print(a_list)
# 列表中的元素是可以修改的 而元组中的元素是不可以被修改
a_tuple = (5)
print(type(a_tuple))
# 当元组中只要一个元素的时候  那么他是整型数据
# 定义只有一个元素的元组,需要在唯一的元素后写一个逗号
b_tuple = (5,)
print(type(b_tuple))
  • slice

Slicing refers to the operation of intercepting a part of the object being operated on. Strings, lists, and tuples all support slice operations.
Slicing syntax: [Start:End:Step], you can also use [Start:End] in simplified form
Note: The selected interval starts from the "Start" bit and ends at the previous bit of the "End" bit (not including The end bit itself), the step size represents the selection interval.

s ='hello world'
# 在切片中直接写一个下标
print(s[0])
# 左闭右开区间   包含坐标的数据 不包含右边的数据
print(s[0:4])
# 是从起始的值开始  一直到末尾
print(s[1:])
# 是下标为0的索引的元素开始 一直到第二参数为止   遵循左闭右开区间
print(s[:4])
# hello  world
# 从下标为0的位置开始 到下标为6的位置结束  每次增长2个长度
print(s[0:6:2])
  • dictionary

view element

In addition to using key to find data, you can also use get to get data

# 定义一个字典
person = {
    
    'name':'吴签','age':28}
# 访问person的name
# print(person['name'])
# print(person['age'])
# 使用[]的方式,获取字典中不存在的key的时候  会发生异常   keyerror
# print(person['sex'])
# 不能使用.的方式来访问字典的数据
# print(person.name)
# print(person.get('name'))
# print(person.get('age'))
# 使用.的方式,获取字典中不存在的key的时候  会返回None值
print(person.get('sex'))

modify element

The data in each element of the dictionary can be modified, as long as it is found by the key, it can be modified. Add
an element.
If the "key" does not exist in the dictionary when using variable name ['key'] = data, then just will add this element

person = {
    
    'name':'张三','age':18}
# 修改之前的字典
print(person)
# 修改name的值为法外狂徒
person['name'] = '法外狂徒'
# 修改之后的字典
print(person)

demo: add new elements

person = {
    
    'name':'老马'}
print(person)
# 给字典添加一个新的key value
# 如果使用变量名字['键'] = 数据时  这个键如果在字典中不存在  那么就会变成新增元素
person['age'] = 18
# 如果这个键在字典中存在 那么就会变成这个元素
person['name'] = '阿马'
print(person)

delete element

of the

# 删除字典中指定的某一个元素
person = {
    
    'name':'老马','age':18}
# 删除之前
# print(person)
# del person['age']
# # 删除之后
# print(person)
# 删除整个字典
# 删除之前
# print(person)
# del person
# # 删除之后
# print(person)

clear()

# clear
# 清空字典 但是保留字典对象
print(person)
# 清空指的是将字典中所有的数据 都删除掉  而保留字典的结构
person.clear()
print(person)

dictionary traversal

# 遍历--》就是数据一个一个的输出
person = {
    
    'name':'阿马','age':18,'sex':'男'}

Traversing the keys of the dictionary (keys)

# (1) 遍历字典的key
# 字典.keys() 方法 获取的字典中所有的key值  key是一个变量的名字 我们可以随便起
# for key in person.keys():
#     print(key)

Traversing the value of the dictionary (value)

# (2) 遍历字典的value
# 字典.values()方法  获取字典中所有的value值   value也是一个变量 我们可以随便命名
# for value in person.values():
#     print(value)

Iterate over the items (elements) of the dictionary

# (3) 遍历字典的key和value
# for key,value in person.items():
#     print(key,value)

Traversing the dictionary's key-value (key-value pairs)

for item in person.items():
    print(item)

Summarize

This blog briefly introduces the introductory knowledge of Python programming, including installing Python, variables and data types, functions, and lists and dictionaries. This is just the tip of the iceberg in the world of Python programming, hopefully it helps you get started. In the following learning process, you can learn more features and functions of Python in depth and develop more powerful applications. Happy programming!

book recommendation

"Python Light"
insert image description here
"Python Light" will redefine the way of learning Python and help readers better apply Python to practical work.

  • Book Highlights

Zero foundation, try not to use professional vocabulary, and do not need any background knowledge;
the language is easy to understand, the explanation is simple and the explanation is simple, and the content is detailed and appropriate;
the code is concise, and the variable naming is as simple as possible;
the knowledge is comprehensive, the explanation is concise, and covers the latest language features;
The knowledge structure design is reasonable, and the learning curve is smooth;
it is application-oriented, explains the necessary third-party libraries, and is equipped with classic and practical cases.
In addition, this book does not pile up knowledge, but arranges the content reasonably, from the general to the points, from the principle to the details, from the theory to the examples, and advances layer by layer according to the reader's learning mental model. In the application part, this book selects cases in the fields of data science (data processing, data analysis, data visualization), office automation (operation on Word, Excel), graphics and interface, Web development, etc., and guides readers to apply Python in practice. . These cases are very representative, and all have detailed code explanations.
Provide massive free supporting resources, including 100 videos, 1600 practical cases, source code downloads, high-quality exercises, the author provides full counseling, mind maps presenting the essence of knowledge in the book, and complete teaching PPTs to make the learning process intuitive and easy to understand.
Getting started with Python programming is easy, regardless of learner's age, occupation, or industry. "Python Light" provides beginners with a minimalist way to get started, and is the best choice for getting started with Python programming.
insert image description here

Guess you like

Origin blog.csdn.net/qq_54796785/article/details/132059969