变量和数据类型
Python 是一种动态类型编程语言,这意味着在使用变量之前不需要声明变量类型。 以下是变量声明和一些常见数据类型的示例:
变量声明:
variable_name = value
常见数据类型:
- 整数(
int):age = 25 - 浮点数(
float):pi = 3.14 - 字符串(
str):name = "John" - 布尔值(
bool):is_true = True
条件语句
条件语句 Python 用于检查条件并根据评估结果执行语句。 、 和(else if) 结构 if 的 用法如下: else elif
if 陈述:
if condition:
# Execute this block if condition is True
else 陈述:
else:
# Execute this block if no preceding if statement is True
elif (else if ) 陈述:
elif condition:
# Execute this block if condition is True and no preceding if or else statement is True
循环
Python 支持两种常用的循环类型: for 循环和 while 循环,可以重复执行语句。
for 环形:
for variable in sequence:
# Execute statements for each value in the sequence
while 环形:
while condition:
# Execute statements while the condition is True
具体示例:
# Variable declaration
age = 25
name = "John"
# Conditional statement
if age >= 18:
print("You are of legal age.")
else:
print("You are not of legal age.")
# Loop
for i in range(5):
print("Hello there!")
count = 0
while count < 5:
print("Loop number:", count)
count += 1
执行时,上面的代码将检查年龄并打印相应的消息,然后 Hello there! 使用循环将消息循环五次 for,最后打印循环的值 while。

