包含编程资料、学习路线图、源代码、软件安装包等!【[点击这里] 】!
1.打印输出:print()
print ( "欢迎来到Python编程世界!" )
name = "Alice"
print ( "你好," , name)
age = 25
print ( f"我今年 { age} 岁了。" )
first_name = "张"
last_name = "三"
print ( first_name, last_name)
print ( "这是第一行" , end= " " )
print ( "这是在同一行继续输出的内容" )
2.变量定义与赋值
my_age = 28
print ( my_age)
pi_value = 3.14159
print ( pi_value)
x, y, z = 1 , 2 , 3
print ( x, y, z)
counter = 0
counter = counter + 1
print ( counter)
price = 9.99
quantity = 3
total_cost = price * quantity
print ( total_cost)
3.数据类型转换
num_str = "100"
num_int = int ( num_str)
print ( num_int)
num_float = 3.14
num_str = str ( num_float)
print ( num_str)
list_items = [ 1 , 2 , 3 ]
tuple_items = tuple ( list_items)
print ( tuple_items)
tuple_data = ( 1 , 2 , 2 , 3 , 4 , 4 )
set_data = set ( tuple_data)
print ( set_data)
dict_data = dict ( name= "李四" , age= 30 )
print ( dict_data)
4.条件语句
score = 60
if score >= 60 :
print ( "及格" )
temperature = 75
if temperature > 80 :
print ( "天气炎热" )
else :
print ( "天气凉爽" )
user_input = 3
if user_input == 1 :
print ( "选择了选项一" )
elif user_input == 2
print ( "选择了选项二" )
else :
print ( "选择了其他选项" )
is_student = True
grade = 90
if is_student:
if grade >= 90 :
print ( "优秀学生" )
else :
print ( "普通学生" )
else :
print ( "非学生" )
height = 175
weight = 70
if height > 170 and weight < 80 :
print ( "符合标准" )
5.循环语句
fruits = [ "苹果" , "香蕉" , "橙子" ]
for fruit in fruits:
print ( fruit)
for i in range ( 1 , 5 ) :
print ( i)
count = 0
while count < 5 :
print ( count)
count += 1
squares = [ x** 2 for x in range ( 10 ) ]
for square in squares:
print ( square)
for number in range ( 1 , 10 ) :
if number == 5 :
break
6.函数定义
def greet ( ) :
"""这是一个简单的问候函数"""
print ( "你好,欢迎来到Python的世界!" )
greet( )
def say_hello ( name) :
"""根据传入的名字打印个性化问候"""
print ( f"你好, { name} !" )
say_hello( "小明" )
def add_numbers ( a, b) :
"""返回两个数相加的结果"""
return a + b
result = add_numbers( 5 , 3 )
print ( result)
def describe_pet ( pet_name, animal_type= '狗' ) :
"""描述宠物的信息"""
print ( f"\n我有一只 { animal_type} 。" )
print ( f"我的 { animal_type} 叫 { pet_name} 。" )
describe_pet( '旺财' )
describe_pet( '汤姆' , '猫' )
def make_pizza ( * toppings) :
"""打印顾客点的所有配料"""
print ( "\n制作披萨需要以下配料:" )
for topping in toppings:
print ( f"- { topping} " )
make_pizza( '蘑菇' , '青椒' , '培根' )
7.调用函数
def welcome_message ( ) :
"""显示欢迎消息"""
print ( "欢迎使用我们的服务!"
welcome_message( )
def display_message ( message) :
"""显示传递的消息"""
print ( message)
display_message( "这是通过函数传递的消息。" )
def get_formatted_name ( first_name, last_name) :
"""返回整洁的姓名"""
full_name = f" { first_name} { last_name} "
return full_name. title( )
musician = get_formatted_name( 'jimi' , 'hendrix' )
print ( musician)
def build_profile ( first, last, ** user_info) :
"""创建一个字典,其中包含我们知道的有关用户的一切"""
user_info[ 'first_name' ] = first
user_info[ 'last_name' ] = last
return user_info
user_profile = build_profile( 'albert' , 'einstein' , location= 'princeton' , field= 'physics' )
print ( user_profile)
def make_sandwich ( * items) :
"""列出三明治中的所有配料"""
print ( "\n正在为您制作含有以下配料的三明治:" )
for item in items:
print ( f"- { item} " )
make_sandwich( '火腿' , '奶酪' , '生菜' )
8.输入函数
name = input ( "请输入您的名字: " )
print ( f"您好, { name} !" )
age = int ( input ( "请输入您的年龄: " ) )
print ( f"明年您将会是 { next_year_age} 岁。" )
hobbies = [ ]
hobby = input ( "请输入您的爱好 (输入'结束'来停止): " )
while hobby != '结束' :
hobbies. append( hobby)
hobby = input ( "请输入您的下一个爱好 (输入'结束'来停止): " )
print ( "您的爱好有:" , hobbies)
height = float ( input ( "请输入您的身高(米): " ) )
weight = float ( input ( "请输入您的体重(千克): " ) )
bmi = weight / ( height * height)
print ( f"您的BMI指数是 { bmi: .2f } " )
answer = input ( "您喜欢编程吗?(yes/no): " )
if answer. lower( ) == 'yes' :
print ( "太棒了,继续加油!" )
else :
print ( "没关系,每个人都有自己的兴趣。" )
9.注释
print ( "Hello, World!" )
'''``这是一段多行注释,``用来解释下面这段代码的功能。``'''
print ( "这是一段测试代码。" )
def square_number ( n) :
"""返回给定数字的平方。参数 n: 要求平方的数字返回: 数字的平方``"""
return n * n
print ( square_number( 4 ) )
print ( "这条消息会被打印出来。" )
def factorial ( n) :
if n == 0 :
return 1
else :
return n * factorial( n- 1 )
print ( factorial( 5 ) )
10.缩进
age = 20
if age >= 18 :
print ( "成年人" )
print ( "检查完成" )
for i in range ( 5 ) :
print ( i)
print ( "循环结束" )
def my_function ( ) :
print ( "这是函数内部的代码" )
my_function( )
def another_function ( ) :
print ( "如果没有正确缩进,会抛出IndentationError" )
if True :
print ( "外层条件成立" )
if False :
print ( "内层条件不成立" )
else :
print ( "内层条件成立" )
11.退出程序
print ( "程序开始" )
exit( )
print ( "这行代码不会被执行" )
import sys
print ( "尝试正常退出..." )
sys. exit( 0 )
在函数中使用 sys.exit() 处理错误情况:
import sys
def divide ( a, b) :
if b == 0 :
print ( "除数不能为零" )
sys. exit( 1 )
return a / b
result = divide( 10 , 0 )
import sys
try :
raise ValueError( "触发一个值错误" )
except ValueError:
print ( "捕获到异常,准备退出程序" )
sys. exit( 2 )
user_input = input ( "请输入'y'来继续:" )
if user_input != 'y' :
print ( "用户决定退出" )
exit( )
print ( "继续执行程序..." )
12.数学运算符
a = 5
b = 3
print ( f" { a} + { b} = { a + b} " )
a = 10
b = 4
print ( f" { a} - { b} = { a - b} " )
a = 7
b = 6
print ( f" { a} * { b} = { a * b} " )
a = 9
b = 2
print ( f" { a} / { b} = { a / b} " )
a = 11
b = 3
print ( f" { a} // { b} = { a // b} , { a} % { b} = { a % b} " )
13.逻辑运算符
age = 20
has_license = True
if age >= 18 and has_license:
print ( "可以合法驾驶" )
is_student = False
has_discount_card = True
if is_student or has_discount_card:
print ( "可以享受折扣" )
raining = False
if not raining:
print ( "天气不错,适合外出" )
temperature = 22
humidity = 70
if temperature > 20 and humidity < 80 :
print ( "气候宜人" )
for i in range ( 1 , 11 ) :
if i % 2 == 0 and i % 3 == 0 :
print ( f" { i} 同时能被2和3整除" )
14.身份运算符
x = [ "apple" , "banana" ]
y = x
print ( x is y)
x = [ "apple" , "banana" ]
z = [ "apple" , "banana" ]
print ( x is not z)
x = [ 1 , 2 , 3 ]
y = x
print ( id ( x) , id ( y) )
print ( x is y)
a = None
b = None
if a is b:
print ( "a和b都是None,或者引用同一对象" )
x = [ 1 , 2 , 3 ]
y = list ( x)
print ( x == y)
print ( x is y)
15.成员运算符
fruits = [ "apple" , "banana" , "cherry" ]
if "banana" in fruits:
print ( "香蕉在水果列表中" )
fruits = [ "apple" , "banana" , "cherry" ]
if "orange" not in fruits:
print ( "橙子不在水果列表中" )
for fruit in [ "apple" , "banana" , "cherry" ] :
if fruit in [ "banana" , "cherry" ] :
print ( f" { fruit} 是我喜欢吃的水果之一" )
sentence = "Hello, world!"
if "world" in sentence:
print ( "找到了单词 'world'" )
student_scores = { "Alice" : 90 , "Bob" : 85 }
if "Alice" in student_scores:
print ( f"Alice的成绩是 { student_scores[ 'Alice' ] } " )
16.长度运算:len()
text = "Hello, World!"
print ( f"字符串 ' { text} ' 的长度是 { len ( text) } " )
numbers = [ 1 , 2 , 3 , 4 , 5 ]
print ( f"列表 { numbers} 中有 { len ( numbers) } 个元素" )
fruits = ( "apple" , "banana" , "cherry" )
print ( f"元组 { fruits} 的大小是 { len ( fruits) } " )
person = { "name" : "Alice" , "age" : 25 , "city" : "New York" }
print ( f"字典中有 { len ( person) } 对键值对" )
unique_numbers = { 1 , 2 , 2 , 3 , 4 , 4 , 5 }
print ( f"集合 { unique_numbers} 包含 { len ( unique_numbers) } 个唯一元素" )
17.范围生成器:range()
for i in range ( 5 ) :
print ( i)
for i in range ( 2 , 11 , 2 ) :
print ( i)
for i in range ( 9 , - 1 , - 1 ) :
print ( i)
numbers_list = list ( range ( 1 , 6 ) )
print ( f"创建的列表是 { numbers_list} " )
items = [ "apple" , "banana" , "cherry" ]
for i in range ( len ( items) ) :
print ( f"第 { i+ 1 } 项是 { items[ i] } " )
18.切片操作
my_list = [ 0 , 1 , 2 , 3 , 4 , 5 ]
slice_of_list = my_list[ 1 : 4 ]
print ( f"切片后的列表是 { slice_of_list} " )
my_string = "Python"
reversed_slice = my_string[ - 3 : ]
print ( f"切片结果是 { reversed_slice} " )
my_tuple = ( 0 , 1 , 2 , 3 , 4 , 5 )
even_elements = my_tuple[ : : 2 ]
print ( f"每隔一个元素提取的结果是 { even_elements} " )
sequence = "abcdef"
reversed_sequence = sequence[ : : - 1 ]
print ( f"反转后的序列是 { reversed_sequence} " )
letters = [ 'a' , 'b' , 'c' , 'd' , 'e' ]
letters[ 1 : 4 ] = [ 'B' , 'C' , 'D' ]
print ( f"更新后的列表是 { letters} " )
19.列表生成式
squares = [ x** 2 for x in range ( 1 , 6 ) ]
print ( f"平方数列表是 { squares} " )
even_numbers = [ num for num in range ( 1 , 11 ) if num % 2 == 0 ]
print ( f"偶数列表是 { even_numbers} " )
words = [ "hello" , "world" , "python" ]
upper_words = [ word. upper( ) for word in words]
print ( f"大写单词列表是 { upper_words} " )
pairs = [ ( x, y) for x in [ 1 , 2 , 3 ] for y in [ 'a' , 'b' ] ]
print ( f"笛卡尔积列表是 { pairs} " )
mixed_data = [ 0 , "apple" , 1 , "banana" , 2 , None , 3 , "" ]
filtered_data = [ item for item in mixed_data if isinstance ( item, int ) and item > 0 ]
print ( f"过滤并转换后的数据是 { filtered_data} " )
20.元组定义
simple_tuple = ( 1 , 2 , 3 )
print ( f"简单元组是 { simple_tuple} " )
single_element_tuple = ( 42 , )
print ( f"单元素元组是 { single_element_tuple} " )
coordinates = ( 10 , 20 )
x, y = coordinates
print ( f"x坐标是 { x} , y坐标是 { y} " )
immutable_tuple = ( 1 , 2 , 3 )
try :
immutable_tuple[ 0 ] = 4
except TypeError as e:
print ( f"错误信息: { e} " )
student_scores = { ( 1 , "Alice" ) : 90 , ( 2 , "Bob" ) : 85 }
print ( f"Alice的成绩是 { student_scores[ ( 1 , 'Alice' ) ] } " )
21.字典定义:使用花括号 {} 定义键值对结构的字典
person = { "name" : "Alice" , "age" : 25 }
print ( f"字典内容: { person} " )
book = dict ( title= "Python编程" , author= "张三" )
print ( f"书的信息: { book} " )
shopping_list = { "fruits" : [ "apple" , "banana" ] , "vegetables" : [ "carrot" , "lettuce" ] }
print ( f"购物清单: { shopping_list} " )
empty_dict = { }
empty_dict[ "country" ] = "China"
print ( f"国家信息: { empty_dict} " )
default_values = { } . fromkeys( [ 'height' , 'width' ] , 0 )
print ( f"默认尺寸: { default_values} " )
22.字典操作:如 get(), pop(), update() 方法来操作字典中的数据
user_info = { "name" : "李四" , "email" : "lisi@example.com" }
email = user_info. get( "email" , "无邮箱信息" )
print ( f"用户邮箱: { email} " )
scores = { "math" : 90 , "english" : 85 }
math_score = scores. pop( "math" )
print ( f"数学成绩已移除: { math_score} " )
first_half = { "Q1" : 100 , "Q2" : 200 }
second_half = { "Q3" : 300 , "Q4" : 400 }
first_half. update( second_half)
print ( f"全年业绩: { first_half} " )
inventory = { "apples" : 30 , "bananas" : 45 }
inventory. clear( )
print ( f"库存清空后: { inventory} " )
settings = { "theme" : "dark" , "language" : "en" }
has_theme = "theme" in settings
print ( f"是否有主题设置: { has_theme} " )
23.文件操作:open(), read(), write() 等方法用于处理文件读写
with open ( 'example.txt' , 'r' ) as file :
content = file . read( )
print ( f"文件内容: { content} " )
with open ( 'output.txt' , 'w' ) as file :
file . write( "这是一个测试文件。" )
print ( "写入完成" )
with open ( 'output.txt' , 'a' ) as file :
file . write( "\n这是追加的内容。" )
print ( "追加完成" )
with open ( 'example.txt' , 'r' ) as file :
for line in file :
print ( line. strip( ) )
with open ( 'source.txt' , 'r' ) as src, open ( 'destination.txt' , 'w' ) as dest:
content = src. read( )
dest. write( content)
print ( "复制完成" )
24.异常处理:使用 try…except…finally 结构来捕获并处理异常
try :
with open ( 'nonexistent_file.txt' , 'r' ) as f:
content = f. read
except FileNotFoundError as e:
print ( f"错误: { e} " )
finally :
print ( "无论是否发生异常,都会执行此代码" )
try :
number = int ( "abc" )
except ValueError as e:
print ( f"错误: { e} " )
try :
result = 10 / 0
except ZeroDivisionError as e
print ( f"除零错误: { e} " )
except Exception as e:
print ( f"其他错误: { e} " )
try :
number = int ( "123" )
except ValueError:
print ( "输入不是一个有效的整数" )
else :
print ( f"成功转换为整数: { number} " )
def divide ( a, b) :
try :
return a / b
except ZeroDivisionError:
print ( "除数不能为零" )
return None
result = divide( 10 , 0 )
if result is not None :
print ( f"结果是: { result} " )
25.模块导入:import 或 from … import … 导入其他模块的功能到当前脚本中
import math
print ( f"圆周率: { math. pi} " )
from datetime
import datetime
current_time = datetime. now( )
print ( f"当前时间: { current_time} " )
import numpy as np
array = np. array( [ 1 , 2 , 3 ] )
print ( f"数组: { array} " )
from os. path import *
print ( f"当前工作目录: { getcwd( ) } " )
import importlib
json_module = importlib. import_module( 'json' )
data = json_module. dumps( { "key" : "value" } )
print ( f"JSON字符串: { data} " )
总结
最后希望你编程学习上不急不躁,按照计划有条不紊推进,把任何一件事做到极致,都是不容易的,加油,努力!相信自己!
文末福利
最后这里免费分享给大家一份Python全套学习资料,希望能帮到那些不满现状,想提升自己却又没有方向的朋友,也可以和我一起来学习交流呀。
包含编程资料、学习路线图、源代码、软件安装包等!【[点击这里] 】领取!
① Python所有方向的学习路线图,清楚各个方向要学什么东西 ② 100多节Python课程视频,涵盖必备基础、爬虫和数据分析 ③ 100多个Python实战案例,学习不再是只会理论 ④ 华为出品独家Python漫画教程,手机也能学习
可以扫描下方二维码领取【保证100%免费 】