02 变量和类型

变量和类型

Python 完全面向对象,而不是 "静态类型"。您不需要在使用变量之前声明它们,也不需要声明它们的类型。Python 中的每个变量都是一个对象。

本教程将介绍几种基本的变量类型。

数字(Numbers)

Python 支持两种类型的数字 —— 整数 int 和浮点数 float(它还支持复数,本教程将不对此进行解释)。

要定义一个整数,请使用以下语法:

myint = 7
print(myint)

要定义浮点数,可以使用以下符号之一:

myfloat = 7.0
print(myfloat)
myfloat = float(7)
print(myfloat)

字符串(Strings)

用单引号或双引号定义字符串。

mystring = 'hello'
print(mystring)
mystring = "hello"
print(mystring)

两者之间的区别在于,使用双引号可以方便地包含撇号 '(而如果使用单引号,这些撇号将终止字符串)。

mystring = "Don't worry about apostrophes"
print(mystring)

在定义字符串时,还有一些其他的变化,使其更容易包含诸如回车、反斜线和 Unicode 字符。 这些内容超出了本教程的范围,但在 Python 文档 中有涉及。

操作

简单运算符可在数字和字符串上执行:

one = 1
two = 2
three = one + two
print(three)

hello = "hello"
world = "world"
helloworld = hello + " " + world
print(helloworld)

可以在同一行中 “同时” 对多个变量进行赋值,如下所示

a, b = 3, 4
print(a, b)

不支持在数字和字符串之间混合运算符:

# This will not work!
one = 1
two = 2
hello = "hello"

print(one + two + hello)
Traceback (most recent call last):
  File "<stdin>", line 6, in <module>
    print(one + two + hello)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

练习

本练习的目标是创建一个字符串、一个整数和一个浮点数。 字符串名为 mystring,包含单词 "hello"。 浮点数名为 myfloat,应包含数字 10.0,整数名为 myint,应包含数字 20。

# 改变以下三行
mystring = None
myfloat = None
myint = None

# 测试你的代码是否正确
if mystring == "hello":
    print("String: %s" % mystring)
if isinstance(myfloat, float) and myfloat == 10.0:
    print("Float: %f" % myfloat)
if isinstance(myint, int) and myint == 20:
    print("Integer: %d" % myint)
posted @ 2024-08-22 20:15  J_ssst  阅读(0)  评论(0编辑  收藏  举报