变量和简单数据类型
变量和数据
变量
什么是变量
python中的变量和c++语言最大的便利和区别是在定义变量时候不用声明使用类型,就声明简单的变量名即可。
message = 1
d = 4.3
string_mes = 'sasssa'
print(message)
print(d)
print(string_mes)
输出结果
1
4.3
sasssa
变量命名的注意事项
1.只能用数字,字母和下划线
2.不能用某些关键字命名变量
3.变量具名,即变量名有具体的意义,正式项目避免用a,b此类,利于项目维护。
数
python中的数即可粗略分为整数与浮点数,可以互相进行四则运算
a = 3
b = 3.1
print(a + b)
print(a / b)
print(a * b)
print(a - b)
输出结果
6.1
0.9677419354838709
9.3
-0.10000000000000009
数中的下划线
可方便计算有多少0
a = 14_0000_0000_0000
print(a)
多个变量赋值
python中可以对多个变量赋值
x, y, z = 1, 2, 3
常量
python中没有c++中用const限定符来定义一个常量,只能用全部大写来提醒使用者这是一个常量
MAX_LENGTH = 100
字符串
python中的字符串使用单引号或者双引号来定义
string = 'hello world'
print(string)
输出结果
string
python中对于字符串内置了很多函数,如lower,upper,tiltle
string = 'hello world'
print(string.lower())
print(string.upper())
print(string.title())
输出结果
hello world
HELLO WORLD
Hello World
在python中,字符串也可以使用格式化字符串,格式化字符串使用f"{}"来定义,其中{}中可以放入变量,变量会自动替换
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(f"Hello, {full_name.title()}!")
Hello, Ada Lovelace!
注释
使用#进行单行注释
#qqq
python之禅
import this
输出结果
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
通常我们只能认为:run is good
posted on 2025-12-26 17:04 122222213322 阅读(19) 评论(0) 收藏 举报
浙公网安备 33010602011771号