Home Backend Development Python Tutorial Summary of basic knowledge about python3 learning

Summary of basic knowledge about python3 learning

Mar 19, 2017 pm 02:17 PM
python3

1. Data type

1. Number

  • int (integer type)

  • long (long integer type)

  • floatfloat

  • ##complex (plural)

2. Boolean value

  • True or False

3, String

2, Variable

Variable naming rules:

三, String splicing

1. Use the plus sign (+)

name = "Tom"age = 25print(name + "s age is " + str(age))
#输出:Toms age is 25
Copy after login

2. String formatting

name = = 25( %
Copy after login
ps: In

python, use the + sign to connect strings. Every time a + sign appears, you must re-apply for a space in the memory. How many + signs are there? How much space do you need to apply for? Generally do not use the + sign to connect strings.

4. Lists and Tuples

1. List

  • Create a list

str_list = ['Tom','Lucy','Mary']
或者
str_list = list(['Tom','Lucy','Mary'])
Copy after login
  • Index (access a value in the list)

str_list[0]
Copy after login
  • Append (add elements to the end)

str_list.append('lilei')print(str_list)#输出:['Tom', 'Lucy', 'Mary', 'lilei']
Copy after login
  • Insert (add an element at the specified position)

str_list.insert(1,'lilei')print(str_list)#输出:['Tom', 'lilei', 'Lucy', 'Mary']
Copy after login
  • Delete (delete the specified element)

str_list.remove('Lucy')print(str_list)#输出:['Tom', 'Mary']
Copy after login
  • Slice

  • str_list = [3,4,5,6,7,8,9]
    new_1 = str_list[1:3]    #从索引1开始取,取到索引3
    new_2 = str_list[0:6:2]  #从索引0开始取,每两位一取,到第6位为止
    new_3 = str_list[-2:]    # 取后面2个数
    new_4 = str_list[:3]     # 取前面3个数
    new_5 = str_list[::3]    #所有数,每3个取一个
    
    print(new_1,new_2,new_3,new_4,new_5)
    
    #输出:[4, 5] [3, 5, 7] [8, 9] [3, 4, 5] [3, 6, 9]
    Copy after login

2. Tuple

  • Creating tuples

  • age = (18,25,33)
    或者
    age = tuple((18,25,33))
    Copy after login
Except that elements cannot be modified, added, or deleted, other operations on tuples and lists are almost the same.

5. Dictionary

Use key-value storage method

  • Create dictionary

  • phone = {
        '张三':'13075632152',
        '李四':'15732015632',    
        '王五':'13420321523',
    }
    Copy after login
  • Get the value of the key in the dictionary

  • print(phone['张三'])      
    #如果key不存在,会报错,key用中括号装print(phone.get('老黄'))  
    #如果key不存在,返回None,key用小括号装#输出:13075632152
    #     None
    Copy after login
  • Assignment

phone[] =    
phone[] =
Copy after login
  • 删除

phone.pop('张三')   
#第一种方法del phone['李四']   
#第二种方法phone.popitem()    
#随机删除某一个
Copy after login
  • 遍历

for key in phone:
    print(key,phone[key])

#输出:
# 王五 13420321523
# 张三 13075632152
# 李四 15732015632
Copy after login
  • 多级嵌套

phone = {
    '人事部':{'老张':'13700112233','老李':'13432023152'},
    '财务部':{'小丽':'13230555666','小映':'13723688888'},
    '技术部':{'老罗':'13866666333'}
}

print(phone['人事部']['老李'])

#输出:13432023152
Copy after login

六、if语句

1、if...else

age = 16
if age <18:
    print(&#39;你还未成年呢&#39;)
else:
    print(&#39;你已经成年了&#39;)
Copy after login

2、if...elif....else

score = 85
if score > 0 and score< 60:
    print(&#39;你的成绩不及格&#39;)
elif score >= 60 and score <80:
    print(&#39;你的成绩及格了&#39;)
elif score>=80 and score<90:
    print(&#39;你的成绩良好&#39;)
else:
    print(&#39;你的成绩优秀&#39;)
Copy after login

七、while循环

i=0
num=0
while i<=100:
    num+=i
    i+=1
print(&#39;1-100累加等于%d&#39;%num)
Copy after login

八、for...in循环

num = []
for i in range(10):
    num.append(i)
print(num)

#输出:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy after login

九、用户交互(input)

name = input(&#39;请输入你的名字:&#39;)
height = input(&#39;请输入你的身高:&#39;)
print(&#39;%s的身高%s厘米&#39; %(name,height))
Copy after login

十、文件基本操作

打开文件:f = open('文件路径','模式') 或者 with open('文件路径','模式') as f:

模式:

  • r:以只读方式打开文件

  • w:打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。

  • a:打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。

  • w+:打开一个文件用于读写。(文件一打开就清空了,还能读到东西吗?)

  • a+:打开一个文件用于读写。

读文件:

read() readlines() readline() 的用法

f = open(&#39;d:/test.txt&#39;,&#39;r&#39;)  #以只读方式打开文件

print(f.read())  #read()一次读取文件的全部内容

for line in f.readlines():   #readlines()读取整个文件,并按行存进列表
    print(line.strip(&#39;\n&#39;))  #去掉行尾的&#39;\n&#39;

while 1:
    line = f.readline()   #readline()每次只读取一行
    print(line.strip(&#39;\n&#39;))
    if not line:
        break

f.close()   #关闭文件
Copy after login

写文件:

f =open(&#39;d:/test.txt&#39;,&#39;a&#39;)
f.write(&#39;hello,boy!\n&#39;)  
f.close()
Copy after login

The above is the detailed content of Summary of basic knowledge about python3 learning. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python vs. C  : Exploring Performance and Efficiency Python vs. C : Exploring Performance and Efficiency Apr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Which is part of the Python standard library: lists or arrays? Which is part of the Python standard library: lists or arrays? Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

Learning Python: Is 2 Hours of Daily Study Sufficient? Learning Python: Is 2 Hours of Daily Study Sufficient? Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python vs. C  : Understanding the Key Differences Python vs. C : Understanding the Key Differences Apr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python for Web Development: Key Applications Python for Web Development: Key Applications Apr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

See all articles