Python入门系列(二)语法风格

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 = 5y = "Hello 公众号 @生活处处有BUG,创作不易,点个关注呗"

变量不需要用任何特定类型声明,甚至可以在设置后更改类型。

x = 4       # x is of type intx = "Sally" # x is now of type strprint(x)

如果要指定变量的数据类型,可以通过转换来完成。

x = str(3)    # x will be '3'y = int(3)    # y will be 3z = float(3)  # z will be 3.0

可以使用type()函数获取变量的数据类型。

x = 5y = "John"print(type(x))print(type(y))

可以使用单引号或双引号声明字符串变量

x = "John"# is the same asx = 'John'

变量名区分大小写。

a = 4A = "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 = fruitsprint(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)
发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章