PyLearning | 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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值