6 小时 Python 入门
发布时间 : 2023-09-25 00:00
字数:3.5k
阅读 :
以下操作均在 Windows 环境下进行操作,先说明一下哈
一、安装 Python 1、官网下载 Python
进入官网(https://www.python.org ),点击 Downloads,选择要下载的版本:
2、安装 Python
安装时注意下图勾选部分一定要勾选:
二、安装代码编辑器 PyCharm 1、官网下载 PyCharm
进入官网(https://www.jetbrains.com/pycharm ),点击 Downloads,选择要下载的版本:
2、安装 PyCharm
设置安装路径之后,一直点 next 即可。
3、优化 PyCharm 使用
三、HelloWorld 创建第一个项目 HelloWorld –> 创建文件 app.py –> 写入代码:
效果图:
四、Python 语法 看语法部分之前,推荐直接看下面入门练习题,潜移默化中对 Python 基本语法会有一定了解之后,再回来看这一部分,会更加熟悉 Python 的使用!
五、入门练习题 1.打印 10 个 *
使用到表达式
2.打印价格
使用到变量
3.描述医院病人的信息 1 2 3 4 5 6 7 8 9 10 11 12 """ @Time : 2020/5/18 @Author : WuGenQiang @File : hospital @Description : 描述医院病人的信息 """ full_name = 'John Smith' age = 20 is_new = True
4.接收用户输入,打印问候信息
使用输入函数 input() 进行输入
1 2 name = input ('what is your name?' ) print ('Hi ' + name)
测试:
5.打印年龄
使用到强制类型转换
1 2 3 birth_year = input ('Birth year: ' ) age = 2019 - int (birth_year) print (age)
使用 type() 打印数据类型:
6.字符串打印
三种字符串表达形式
1 2 3 4 5 6 7 8 9 course_1 = 'Python for "Beginners"' print (course_1)course_2 = "Python is my 'love'" print (course_2)course_3 = ''' Hi John welcome to python world! ''' print (course_3)
效果呈现:
获取 course_1 的第一个索引值:
获取 course_1 的最后一个索引值:
那么获取倒数第二个索引值呢:
返回索引为 0 - 2 的值:
返回索引 0 以及 0 之后的所有字符:
返回索引小于 5 的所有字符:
返回所有字符:
返回从第 2 位开始,不包括最后一位字符的字符串:
7.格式化字符串 1 2 3 4 5 6 7 8 first = 'WuGenQiang' last = 'happy' message = first + ' [' + last + '] is a coder' msg = f'{first} [{last} ] is a coder' print (message)print (msg)
8.字符串方法使用 (1)len() 函数:求字符串长度
1 2 3 course = 'Python for Beginners' print (len (course))
(2)upper() 函数:转换成大写字母
(3)lower() 函数:转换成小写字母
(4)find() 函数
1 2 print (course.find('n' ))
找不到返回 -1,并且区分大小写
(5)replace() 函数
1 2 print (course.replace('Beginners' , 'Absolute Beginners' ))
(6)in 使用:产生布尔值 False or True
1 2 print ('Python' in course)
9.算术运算符 举例:
1 2 3 4 5 6 7 8 9 10 print (10 / 3 )print (10 % 3 )print (10 * 3 )print (10 ** 3 )x = 10 x = x + 3 x += 3 print (x)
思索下面 x 为多少:
答案是 22,因为取幂运算符是优先的,所以先算 2 的 2 次方
10.引入数学模块 1 2 import mathprint (math.floor(2.9 ))
11.条件语句的使用
使用 if - elif - else
1 2 3 4 5 6 7 8 9 is_hot = False is_cold = True if is_hot: print ("It's a hot day" ) elif is_cold: print ("It's a cold day" ) else : print ("It's a lovely day" ) print ("Enjoy your day" )
当条件多个并且是 “and” 的关系时,使用:
1 2 3 4 has_high_income = True has_good_credit = True if has_good_credit and has_high_income: print ("Eligible for loan" )
若当条件多个并且是 “or” 的关系时,使用:
1 2 3 4 has_high_income = False has_good_credit = True if has_good_credit or has_high_income: print ("Eligible for loan" )
如何使用 “not”,看下面:(not 相当于取反)
1 2 3 4 has_good_credit = True has_criminal_record = False if has_good_credit and not has_criminal_record: print ("Eligible for loan" )
12.打印天气
使用比较运算符
1 2 3 4 5 temperature = 30 if temperature > 30 : print ("It's a hot day" ) else : print ("It's a cold day" )
13.打印名字是否符合要求
使用比较运算符
1 2 3 4 5 6 7 name = "James" if len (name) < 3 : print ("Name must be at least 3 character" ) elif len (name) > 50 : print ("Name must be a maximum of 50 character" ) else : print ("Name looks good" )
14.判断体重 1 2 3 4 5 6 7 8 weight = int (input ('weight: ' )) unit = input ('(L)bs or (K)g: ' ) if unit.upper() == "L" : converted = weight * 0.45 print (f"You are {converted} kilos" ) else : converted = weight / 0.45 print (f"You are {converted} pounds" )
15.打印 1 - 5
使用到 while 循环语句或者 for 循环语句
1 2 3 4 5 i = 1 while i <= 5 : print (i) i = i + 1 print ("Done" )
16.猜数(秘密号码) 1 2 3 4 5 6 7 8 9 10 11 secret_number = 9 guess_count = 0 guess_limit = 3 while guess_count < guess_limit: guess = int (input ('Guess: ' )) guess_count += 1 if guess == secret_number: print ('You won!' ) break else : print ('Sorry, you failed' )
17.Car game 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 command = "" started = False while True : command = input ("> " ).lower() if command == "start" : if started: print ("Car is already started!" ) else : started = True print ("Car started..." ) elif command == "stop" : if not started: print ("Car is already stopped!" ) else : started = False print ("Car stopped." ) elif command == "help" : print (""" start - to start the car stop - to stop the car quit - to quit """ ) elif command == "quit" : break else : print ("Sorry, I don't understand that!" )
18.for 循环使用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 for item in 'Python' : print (item) for item in ['Mosh' , 'John' , 'Sarah' ]: print (item) for item in [1 , 2 , 3 , 4 ]: print (item) for item in range (10 ): print (item) for item in range (5 , 10 ): print (item) for item in range (5 , 10 , 2 ): print (item)
19.计算价格总量
使用到 for 循环
1 2 3 4 5 prices = [10 , 20 , 30 ] total = 0 for price in prices: total += price print (f"Total: {total} " )
20.嵌套循环 1 2 3 for x in range (4 ): for y in range (3 ): print (f'({x} , {y} )' )
画个大大的 “F”
1 2 3 numbers = [5 , 2 , 5 , 2 , 2 ] for x_count in numbers: print ('x' * x_count)
1 2 3 4 5 6 numbers = [5 , 2 , 5 , 2 , 2 ] for x_count in numbers: output = '' for count in range (x_count): output += 'x' print (output)
21.List 1 2 3 4 5 6 7 8 names = ['John' , 'Bob' , 'Mosh' , 'Sarah' , 'Mary' ] print (names)print (names[:])print (names[2 :])print (names[0 ])print (names[-1 ])
22.List 中找最大值 1 2 3 4 5 6 numbers = [3 , 6 , 2 , 8 , 4 , 10 ] max = numbers[0 ]for number in numbers: if number > max : max = number print (max )
23.访问矩阵中的各项 1 2 3 4 5 6 7 8 9 10 matrix = [ [1 , 2 , 3 ], [4 , 5 , 6 ], [7 , 8 , 9 ] ] matrix[0 ][1 ] = 20 print (matrix[0 ][1 ])for row in matrix: for item in row: print (item)
24.数组中常用函数调用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 numbers = [5 , 2 , 1 , 7 , 4 ] numbers.sort() numbers.reverse() print (numbers)numbers2 = numbers.copy() print (numbers2)numbers.remove(1 ) numbers.clear() numbers.append(20 ) numbers.insert(0 , 12 ) numbers.pop() print (numbers.index(12 ))print (numbers)print (50 in numbers)print (numbers.count(12 ))
1 2 3 4 5 6 numbers = [2 , 2 , 4 , 6 , 3 , 4 , 6 , 1 ] uniques = [] for number in numbers: if number not in uniques: uniques.append(number) print (uniques)
25.元组 1 2 numbers = (1 , 2 , 3 ) print (numbers[0 ])
注意:
1 2 3 4 5 6 7 coordinates = (1 , 2 , 3 ) x, y, z = coordinates print (x)
26.使用字典
1 2 3 4 5 6 7 8 9 customer = { "name" : "John Smith" , "age" : 30 , "is_verified" : True } customer["name" ] = "Jack Smith" print (customer["name" ])print (customer.get("name" ))print (customer.get("host" , "123.12.1.1" ))
1 2 3 4 5 6 7 8 9 10 11 12 phone = input ("Phone: " ) digits_mapping = { "1" : "One" , "2" : "Two" , "3" : "Three" , "4" : "Four" , "5" : "Five" } output = "" for ch in phone: output += digits_mapping.get(ch, "!" ) + " " print (output)
27.输出表情符号 1 2 3 4 5 6 7 8 9 10 11 message = input ("> " ) words = message.split(' ' ) emojis = { ":)" : "😄" , ":(" : "😣" } output = "" for word in words: output += emojis.get(word, word) + " " print (output)
使用函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 """ @Time : 2020/5/20 @Author : WuGenQiang @File : testList @Description : """ def emoji_converter (message ): words = message.split(' ' ) emojis = { ":)" : "😄" , ":(" : "😣" } output = "" for word in words: output += emojis.get(word, word) + " " return output message = input ("> " ) result = emoji_converter(message) print (result)
28.函数
1 2 3 4 5 6 def greet_user (): print ('Hi, function!' ) print ("Start" )greet_user() print ("Finished" )
1 2 3 4 5 6 def greet_user (name ): print (f'Hi, {name} ' ) print ("Start" )greet_user("John" ) print ("Finished" )
1 2 3 4 5 def square (number ): return number * number result = square(3 ) print (result)
29.异常处理
1 2 3 4 5 6 7 8 9 try : age = int (input ('Age: ' )) income = 20000 risk = income / age print (age) except ZeroDivisionError: print ('Age cannot be 0.' ) except ValueError: print ('Invalid value' )
30.注释 1 2 3 4 5 6 print ('Sky is blue' )def square (number ): return number * number
31.类的使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Point : def __init__ (self, x, y ): self.x = x self.y = y def move (self ): print ("move" ) def draw (self ): print ("draw" ) point2 = Point(10 , 20 ) print (point2.x)
1 2 3 4 5 6 7 8 9 10 11 12 13 class Person : def __init__ (self, name ): self.name = name def talk (self ): print (f"Hi, I am {self.name} " ) john = Person("John Smith" ) john.talk() bob = Person("Bob Smith" ) bob.talk()
32.继承的使用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class Mammal : def walk (self ): print ("walk" ) class Dog (Mammal ): def bark (self ): print ("bark" ) class Cat (Mammal ): pass dog1 = Dog() dog1.walk() dog1.bark()
33.调用模块使用 先创建 converters.py:
1 2 3 4 def lbs_to_kg (weight ): return weight * 0.45 def kg_to_lbs (weight ): return weight / 0.45
然后在需要调用的 py 文件中这样写:
1 2 import convertersprint (converters.kg_to_lbs(70 ))
初步实现,然后根据需求完成自己的项目吧!
34.从整个模块中导入特定的函数 不需要模块名作为前缀
1 2 3 from converters import kg_to_lbsprint (kg_to_lbs(100 ))
由此,我们可以为之前写的一些功能实现写一个工具文件,包含着各种要实现的功能函数:
比如这样:
举例:实现求最大数
1 2 3 4 5 6 def find_max (numbers ): max = numbers[0 ] for number in numbers: if number > max : max = number return max
1 2 3 4 from utils import find_maxnumbers = [10 , 3 , 6 , 2 ] print (find_max(numbers))
35.从包中导入特定的函数 举例:
创建 Python 包 ecommerce,包中创建文件 shhipping.py,如下:
1 2 def calc_shipping (): print ("calc shipping" )
调用:
1 2 import ecommerce.shippingecommerce.shipping.calc_shipping()
1 2 from ecommerce.shipping import calc_shippingcalc_shipping()
1 2 from ecommerce import shippingshipping.calc_shipping()
36.生成随机值
1 2 3 4 5 6 import randomfor i in range (3 ): print (random.random()) print (random.randint(10 , 20 ))
1 2 3 4 5 import randommembers = ['John' , 'Mary' , 'Mosh' ] leader = random.choice(members) print (leader)
1 2 3 4 5 6 7 8 9 10 import randomclass Dice : def roll (self ): first = random.randint(1 , 6 ) second = random.randint(1 , 6 ) return first, second dice = Dice() print (dice.roll())
37.寻找目录路径 1 2 3 4 from pathlib import Pathpath = Path("ecommerce" ) print (path.exists())
如果有会输出 True,没有的话就会输出 False,那就使用下面命令创建一个新的目录
删除目录
搜索文件,打印生成器对象
1 2 3 4 from pathlib import Pathpath = Path() print (path.glob('*.*' ))
实例:
1 2 3 4 5 from pathlib import Pathpath = Path() for file in path.glob('*.py' ): print (file)
显示目录下所有文件
1 2 3 4 5 from pathlib import Pathpath = Path() for file in path.glob('*' ): print (file)
38.表格中读取信息 1 2 3 4 5 6 import openpyxl as xlwb = xl.load_workbook('transactions.xlsx' ) sheet = wb['Sheet1' ] cell = sheet['A1' ] cell = sheet.cell(1 , 1 ) print (cell.value)
查看数据有多少行:
实现图表显示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 """ @Time : 2020/5/18 @Author : WuGenQiang @File : app @Description : """ import openpyxl as xlwb = xl.load_workbook('test.xlsx' ) sheet = wb['Sheet1' ] print (sheet.max_row)from openpyxl.chart import BarChart, Referencefor row in range (1 , sheet.max_row + 1 ): cell = sheet.cell(row, 3 ) print (cell.value) corrected_price = cell.value * 0.9 + 2 corrected_price_cell = sheet.cell(row, 4 ) corrected_price_cell.value = corrected_price values = Reference(sheet, min_row=1 , max_row=sheet.max_row, min_col=4 , max_col=4 ) chart = BarChart() chart.add_data(values) sheet.add_chart(chart, 'E2' ) wb.save('test2.xlsx' )
效果图:
优化:子函数调用版
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 """ @Time : 2020/5/18 @Author : WuGenQiang @File : app @Description : """ import openpyxl as xlfrom openpyxl.chart import BarChart, Referencedef process_workbook (filename ): wb = xl.load_workbook(filename) sheet = wb['Sheet1' ] print (sheet.max_row) for row in range (1 , sheet.max_row + 1 ): cell = sheet.cell(row, 3 ) print (cell.value) corrected_price = cell.value * 0.9 + 2 corrected_price_cell = sheet.cell(row, 4 ) corrected_price_cell.value = corrected_price values = Reference(sheet, min_row=1 , max_row=sheet.max_row, min_col=4 , max_col=4 ) chart = BarChart() chart.add_data(values) sheet.add_chart(chart, 'E2' ) wb.save(filename) process_workbook('test.xlsx' )
39.CSV 文件导入数据
数据集下载:vgsales.csv
整体输出数据 1 2 3 4 import pandas as pddf = pd.read_csv('vgsales.csv' ) df
效果:
获取数据集的形状
效果:
分段输出数据
效果:
获取值
效果:
清洁数据 删除数据举例:
1 2 3 4 5 import pandas as pddf = pd.read_csv('vgsales.csv' ) x = df.drop(columns=['JP_Sales' ]) x
获取某一列数据:
1 2 3 4 5 import pandas as pddf = pd.read_csv('vgsales.csv' ) y = df['JP_Sales' ] y
40.决策树 1 2 3 4 5 6 7 8 9 10 11 12 import pandas as pdfrom sklearn.tree import DecisionTreeClassifierdf = pd.read_csv('vgsales.csv' ) x = df.drop(columns=['JP_Sales' ]) y = df['JP_Sales' ] model = DecisionTreeClassifier() model.fit(x, y) predictions = model.predict([[41.49 , 29.02 ], [29.08 , 3.58 ]]) predictions
可能数据不对,可以使用其他测试数据
测量数据精确度 数据被分为两组:训练和测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 import pandas as pdfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import accuracy_scoredf = pd.read_csv('vgsales.csv' ) x = df.drop(columns=['JP_Sales' ]) y = df['JP_Sales' ] x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2 ) model = DecisionTreeClassifier() model.fit(x_train, y_train) predictions = model.predict(x_test) score = accuracy_score(y_test, predictions) score
六、参考资料 [1] 2020 最新 Python 教程 6 小时入门
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 richffan@outlook.com