关于程序员:Python入门系列二语法风格

2次阅读

共计 1259 个字符,预计需要花费 4 分钟才能阅读完成。

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)

本文由 mdnice 多平台公布

正文完
 0