Python编程入门学习笔记——变量和简单数据类型

1、变量

1.1 变量定义与输出

message = "Hello Python world!"
print(message)

1.2 字符串

  在Python中,用引号括起的都是字符串,其中的引号可以是单引号,也可以是双引号:

"This is a string."
'This is also a string.'
  1.2.1 字符串修改方法

  title() 以首字母大写的方式显示每个单词。upper()字母转换成大写,lower()字母转换成小写。

name = "ada lovelace"
print(name.title())

  Python使用加号(+)来合并字符串。

full_name = first_name + " " + last_name

  rstrip()方法能够确保字符串末尾没有空白。要永久删除这个字符串中的空白,必须将删除操作的结果存回到变量中。使用lstrip() 和strip()剔除字符串开头的空白,或同时剔除字符串两端的空白。

favorite_language = 'python '
favorite_language = favorite_language.rstrip()

  Python 3中的print是一个函数,因此括号必不可少。在Python 2代码中,有些print 语句包含括号,有些不包含。

1.3 数字

  在Python中,可对整数执行加(+)减(-)乘(*)除(/)运算,使用两个乘号表示乘方运算。

  需要注意的是,结果包含的小数位数可能是不确定的。所有语言都存在这种问题。

>>> 0.2 + 0.1
0.30000000000000004
>>> 3 * 0.1
0.30000000000000004

  将整数作为字符串使用时调用str()函数。

age = 23
message = "Happy " + str(age) + "rd Birthday!"
print(message)

  在Python 2中,整数除法的结果只包含整数部分,小数部分被删除。Python 3中保留小数部分。

1.4 注释

  在Python中,注释用井号(# )标识。

猜你喜欢

转载自blog.csdn.net/horotororensu/article/details/78446854