Python学习之路(2)变量与简单的数据类型

茴香豆 Lv5

在本章中,主要学习Python中可使用的各种数据,以及如何存储、使用和访问这些数据。

1.Hello-World

1
2
message = "Hello World!"
print(message)

2.变量

命名规则:

  • 变量名只能包含字母数字和下划线,且不能以数据打头。
  • 变量名不能包含空格。
  • 变量名不能与关键字或函数名相同。
  • 变量名应简短且具有描述性
  • 慎用小写字母 l 和大写字母 O,因为会被错认为数字1和0

3.字符串

Python中,单引号或双引号括起来的是字符串,这种灵活性可以使程序员在字符串中包含引号和撇号。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# var
message = "Hello Python world!"
print(message)
# change the case of string 改变大小写
name = "ada lovelace"
print(name.title()) # Title 标题格式
print(name.upper()) # upper case 大写
print(name.lower()) # lower case 小写
# merge string 合并字符串
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name)
# add whitespace \n \t 添加空白
print("\tPython")
print("languages:\n\tPython\n\tC\n\tJavaScript")
# delete block 删除空白
language = " Python "
print("-" + language + "-")
print("-" + language.rstrip() + "-") # delete the whitespace at the right
print("-" + language.lstrip() + "-") # delete the whitespace at the left
print("-" + language.strip() + "-") # delete the whitespace at the both

Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Hello Python world!
Ada Lovelace
ADA LOVELACE
ada lovelace
ada lovelace
Python
languages:
Python
C
JavaScript
- Python -
- Python-
-Python -
-Python-

4.数字

4.1整数

在Python中,整数可执行加(+)减(-)乘(*)除(/)乘方(**)整除(//)取模(%),并支持运算次序,并支持括号改变运算次序。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> 2 + 3
5
>>> 2 - 3
-1
>>> 2 * 3
6
>>> 2 / 3
0.6666666666666666
>>> 3 // 2
1
>>> 2 % 3
2
>>> 2**3
8

4.2浮点数

需要注意的是,运算结果包含的浮点数的小数位数可能是不确定的。后续会学习处理多余小数位的方式。

1
2
3
4
>>> 0.2 + 0.1
0.30000000000000004
>>> 3 * 0.1
0.30000000000000004
  • Title: Python学习之路(2)变量与简单的数据类型
  • Author: 茴香豆
  • Created at : 2022-06-30 17:44:39
  • Updated at : 2022-07-01 22:10:54
  • Link: https://hxiangdou.github.io/2022/06/30/Python_2/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
Python学习之路(2)变量与简单的数据类型