python中的变量、字符串、数、注释

目录

一、变量

二、字符串

三、数

四、注释


一、变量

变量是可以赋给值的标签(变量指向特定的值)

message="I really miss you."
print(message)
I really miss you.

message为变量,每个变量都指向一个值,指向的值为文本"I really miss you."添加变量后,python解释器会把变量message与文本"I really miss you."关联起来,再把message关联的值打印到屏幕上。

message="I really miss you."
print(message)
message="But I deeply love you!"
print(message)
I really miss you.
But I deeply love you!

变量的值可随时修改,python将始终记录变量的最新值。

变量的命名规则:只能由字母、下划线(代替空格)、数字(不能开头)组成;简短又具有描述性;尽量不要出现i和o(易与1和0混淆);不要将python关键字、内置函数用作变量名(关键词作变量名将引发错误,内置函数作变量名将覆盖函数行为)

message="I really miss you."
print(mesage)

Traceback (most recent call last):
  File "F:\python_work\simple_message.py", line 2, in <module>
    print(mesage)
NameError: name 'mesage' is not defined

traceback是一条记录,指出程序运行时,再什么地方陷入困境。第1行:在哪里存在错误,第2行:列出具体代码,第三行:指出什么错误

名称错误NameError主要原因:1.使用变量前忘记给变量赋值。2.输入变量名时拼写不正确

二、字符串

字符串是一系列字符,字符串要用引号引起来,包括 " " 和 ' ' 。

"This is a string."                                        'This is also a string.'

'I told my friend,"This is a string"'

1.字符串大小写的处理

title():字符串中每个单词首字母大写(将Ada、ADA、ada视为同一个人,并表示为Ada) 

upper():将字符串改为全部大写

lower():将字符串改为全部小写(无法依靠用户提供正确的大小写,全部改为小写存储)

print(name.title() 方法是python对数据可执行的操作

.让python对变量name执行方法title()指定的操作

title():方法后都跟着一对圆括号(),因为方法通常需额外的信息来完成其工作,这种信息在()提供,函数title()不需要额外信息,故圆括号内为空

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

Ada Lovelace

name='ada lovelace'
print(name.upper())

ADA LOVELACE

name='ada lovelace'
print(name.lower())

ada lovelace

2.字符串中使用变量(f字符串

在前引号"/'前加上字母f,要插入的变量放入花括号{ }内            f为format(设置格式)的简写python通过把{ }中的变量替换为其值来设置字符串的格式         f字符串为3.6版本以上才可行

first_name='Ana'
last_name='lovelace'
full_name=f"{first_name} {last_name}"
print (full_name)

Ana lovelace

用f字符串 利用与变量关联的信息来创建完整的消息

first_name='Ana'
last_name='lovelace'
full_name=f"{first_name} {last_name}"
print (f"Hello! {full_name.title()}") 

Hello! Ana Lovelace

python识别到 print() 会显示()里的内容                                                                                          ()里可以只有变量名,可利用f字符串添加其他内容再用{}引入变量,可有数学运算,可有字符串

用f字符串 创建消息再把整条消息赋给变量

first_name='Ana'
last_name='lovelace'
full_name=f"{first_name} {last_name}"
message=f"Hello! {full_name.title()}"
print(message)

Hello! Ana Lovelace

3.在字符串中添加制表符或换行符来增添空白

制表符 \t(使输出的内容前有4个空白格)      空白泛指任何非打印字符,如空格、制表符和换行符

换行符 \n(使输出的内容换行)                      \t\n可同时使用,目的:更容易阅读

print("python")
print("\t python")
print("message:\npython\n\tlike\n\t\tme")

python
	 python
message:
python
	like
		me

4.删除字符串中多余的空白(剥除函数)

剔除字符串末尾的空白   方法rstrip()   

剔除字符串开头的空白   方法lstrip()

剔除字符串两端的空白   方法strip()  

要永久删除这个字符串中的空白,必须将删除操作的结果关联到变量

>>> favorite_language='  python'
>>> favorite_language.lstrip()
'python'
>>> favorite_language
'  python'
>>>
>>> favorite_language=' python '
>>> favorite_language=favorite_language.strip()
>>> favorite_language
'python'

5.字符串中易出现的语法错误

要正确使用单引号、双引号,若单引号中包含撇号,python会把第一个单引号和撇号之间视为字符串,python的语法高亮功能可识别一些语法错误

message="One of the python's strength id diverse community."
print(message)
One of the python's strength id diverse community.

message='One of the python's strength id diverse community.'
print(message)
  File "F:\python_work\apostrophe.py", line 1
    message='One of the python's strength id diverse community.'
                               ^
SyntaxError: invalid syntax

三、数

1.整数

可对整数进行加(+)、减(-)、乘(*)、除(/) 的运算,乘方(**) 还支持运算次序,可使用圆括号()修改运算次序                                                

>>> 6+2
8
>>> 6-2
4
>>> 6*2
12
>>> 6**2
36
>>> 6/2
3.0
>>> 6+2.0
8.0

>>> universe_age=14_000_000_000
>>> print(universe_age)
14000000000

>>> x,y,z=0,0,0

>>> MAX_CONNECTIONS=500

 2.浮点数

浮点数:带小数点的数,任意两个数相除时、一个是整数另一个是浮点数,结果都是浮点数

3.数中的下划线

为阅读方便,常在较大的数中添加下划线,但python不会打印下划线,因为存储这种数时会忽略

4.同时给多个变量赋值

有助于缩短程序,将一系列数赋给一组变量,需用逗号将变量、值分隔开,只要变量和值个数相同,python就能正确的将其关联。

5.常量

类似于变量,用全大写将某个变量视为常量,其值始终不变 。

print(3+5)
print(10-2)
print(4*2)
print(16/2)

8
8
8
8.0

四、注释

当程序变大变复杂时,可通过注释(在首行添加#),用自然语言对程序添加说明,python中注释用#说明,#后的内容会被python解释器自动忽略。

#向大家问好
print('hello,lovely python people!')

hello,lovely python people!

漂亮的代码

>>> import this

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!

关键字:false; ture; import; break; except; and; continue; for; in; if; while; or; raise; class; finally; is; return; await; else; pass;  lambda; try; as; def; from; nonlocal; assert; del; global;  not; with; async; elif; yield

内置函数:abs()   all()     any()     ascii()     bin()     bool()     breakpoint()     bytearray()     bytes()     callable()     chr()     classmethod()     compile()     complex()      delattr()       dict()     dir()     divmod()     enumerate()     eval()     exec()      filter()     float()     format()  frozonset()     getattr()      globals()     hasattr()     harsh()     help()     hex()     id()     input()  int()     isinstance()     issubclass()     iter()     len()    list()     locals()     map()     max()  memoryview()     min()     next()     object()     oct()     open()     ord()    pow()    print()     property()     range()     repr()     reversed()    round()     set()     setattr()      slice()     sorted()     staticmethod()     str()     sum()     tuple()     type()    vars()     zip()     _import_()

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值