python基础
本文最后更新于 561 天前,其中的信息可能已经有所发展或是发生改变。

输出语句

示例:

print("Hello,World")

运行结果:

image-20241211135433306

变量与数据类型

示例:

# 字符串
name = "diudiu"
# 整数
num = 666
# 浮点数
height = 3.14
# 布尔值
is_bloon = True
# 输出结果
print("name:",name)
print("num:",num)
print("height:",height)
print("is_bloon:",is_bloon)

运行结果:

image-20241211190936444

控制流:条件语句与循环

  • 缩进:Python使用缩进表示代码块(通常是4个空格)

条件语句

score = 85
if score >= 90:
   print("Grade: A")
elif score >= 75:
   print("Grade: B")
else:
   print("Grade: C")

运行结果:

image-20241211191622475

循环语句

  • Python支持forwhile两种循环。
  • range()函数:生成从1到5的整数序列(不包含上限)。
  • while循环:只要条件为真,循环体就会反复执行。

示例代码1:for循环

for i in range(1,6):
   print(i)

示例代码2:while循环

i = 1 
while i <= 5:
   print(i)
   i += 1

运行结果:

image-20241211192252157

函数

  • 函数是可以重复使用的代码块,用于实现特定功能。
  • def关键字:用于定义函数。
  • 参数:函数的输入变量,可以在调用时传递不同的值,即java中的形参。

示例代码:

#定义“吃东西”函数
def eat(food):
   print("I eat",food)
# 调用
eat("apple")
eat("cooked rice")

运行结果:

image-20241211193140096

字典

示例代码:

# 创建空字典
dic={}
# 添加
dic['name'] = 'diudiu'
dic['age'] = '22'
print(dic)
dic['country'] = 'China'
# 更新
dic['age'] = '23'
# 修改后的结果
print(dic)
print("My name is",dic['name'], "I am",dic['age'], "years old","from",dic['country'])

运行结果:

image-20241211195530233

模块

模块的引入

  • 模块定义好后,我们可以使用 import 语句来引入模块
  • 一个模块只会被导入一次,不管你执行了多少次import。这样可以防止导入模块被一遍又一遍地执行。

示例代码:

文件1:support.py

def eat(food):
   print("I eat",food)
   return

文件2:test.py

# 导入文件1 support.py
import support

support.print_eat("apple")
support.print_eat("cooked rice")

运行结果:

image-20241211202544073

from…import 语句

  • 从模块中导入一个指定的部分到当前命名空间中
  • 此方法在使用的使用,直接使用导入的函数名即可,不需要和全部引入时一样带模块名(因为我带着执行了,报错,,已老实)

文件1:support.py

# 函数1 吃
def print_eat( food ):
   print("I eat ", food)
   return

# 函数2 不吃
def print_noeat( food ):
   print("I don't eat ", food)
   return

文件2:test.py

from support import print_noeat

print_noeat("apple")
print_noeat("cooked rice")

运行结果

image-20241211204849827

搜索路径

当你导入一个模块,Python 解析器对模块位置的搜索顺序是:

  • 1、当前目录
  • 2、如果不在当前目录,Python 则搜索在 shell 变量 PYTHONPATH 下的每个目录。
  • 3、如果都找不到,Python会察看默认路径。UNIX下,默认路径一般为/usr/local/lib/python/。

模块搜索路径存储在 system 模块的 sys.path 变量中。变量里包含当前目录,PYTHONPATH和由安装过程决定的默认目录。

python基础

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇