Python入门系列(二)语法风格
2024-10-20 08:01:21
python缩进
Python使用缩进来表示代码块,例如
if 5 > 2:
print("Five is greater than two!")
如果跳过缩进,Python将给您一个错误。
# 下边的写法将会报错
if 5 > 2:
print("Five is greater than two!")
您必须在同一代码块中使用相同数量的空格,否则Python将给您一个错误
# 下边的写法将会报错
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
注释
注释以#开头,Python将把行的其余部分呈现为注释:
#This is a comment.
print("Hello 公众号 @生活处处有BUG,创作不易,点个关注呗!")
或者,也可以使用多行字符串。
"""
公众号
@生活处处有BUG
创作不易,点个关注
"""
print("Hello, World!")
Python变量
在Python中,变量是在为其赋值时创建的。
x = 5
y = "Hello 公众号 @生活处处有BUG,创作不易,点个关注呗"
变量不需要用任何特定类型声明,甚至可以在设置后更改类型。
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
如果要指定变量的数据类型,可以通过转换来完成。
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
可以使用type()函数获取变量的数据类型。
x = 5
y = "John"
print(type(x))
print(type(y))
可以使用单引号或双引号声明字符串变量
x = "John"
# is the same as
x = 'John'
变量名区分大小写。
a = 4
A = "Sally"
#A will not overwrite a
Python允许您在一行中为多个变量赋值
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
如果列表、元组等中有一组值,Python允许您将值提取到变量中。这叫做拆包。
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
在print()函数中,输出多个变量,用逗号分隔
x = "Hello"
y = "公众号 @生活处处有BUG"
z = "创作不易,点个关注呗"
print(x, y, z)
您还可以使用+运算符输出多个变量。
x = "Hello "
y = "公众号 @生活处处有BUG "
z = "创作不易,点个关注呗"
print(x + y + z)
函数内部和外部的所有人都可以使用全局变量。
x = "H公众号 @生活处处有BUGello"
def myfunc():
print("Hello " + x)
myfunc()
要在函数中创建全局变量,可以使用global关键字。
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
最新文章
- Notes: Principles of fMRI 1 (Coursera)
- 关于页面 reflow 和 repaint
- HDU5032 -- Always Cook Mushroom 树状数组 14年北京网络赛
- 笔记本开通手机WiFI热点
- Dynamic Programming - leetcode [动态规划]
- 如何在Visio 2007中画接口和实现类的关系图
- Elastic Stack
- Asp.net实现下拉框和列表框的连动
- Ethereum(1)—— 基本介绍
- 使用telnet进行Dubbo接口测试
- Springboot使用alibaba的fastJson,@JSONField不起作用的问题
- Mac os x 系统的发展史
- jQuery中event.target和this的区别
- 分布式一致性hash算法
- lesson
- SharePoint 2013 处理videoplayerpage.aspx下的个人图片显示有误问题
- 【linux】如何退出shell终端
- FreePascal - CodeTyphon交叉编译,在一个操作系统生成各个操作系统可以运行的程序!
- Comparable 与 Comparator的区别
- 如何在linux设置回收站 - 防止失误操作造成数据清空
热门文章
- 30.Mysql主从复制、读写分离
- Java递归实现评论多级回复
- VS Code 调教日记(2022.6.26更新)
- Cf #782 (Div. 2)
- Detecting Rumors from Microblogs with Recurrent Neural Networks(IJCAI-16)
- SpringCloudGateway微服务网关实战与源码分析 - 中
- 【有用的SQL】查Greenplum的数据字典
- 【前端面试】Vue面试题总结(持续更新中)
- DNS原理与配置
- NOI / 1.4编程基础之逻辑表达式与条件分支讲解-02:输出绝对值