Python 变量和简单数据类型


1、hello world
print("hello python world!")

输出

hello python world!
2、变量

(1)添加一个msg变量

msg = "hello python world!"
print(msg)

输出

hello python world!

(2)修改msg再打印

msg = "hello python world!"
print(msg)
msg = "hello python crash course world!"
print(msg)

输出

hello python world!
hello python crash course world!

① 变量名只能包含字母、数字和下划线。变量名可以是字母或下划线打头,但不能以数字开头。例如:msg_1,但不可以是1_msg。
② 变量名不可以包含空格,可以使用下划线分隔单词。
③ 不要将 python 关键字和函数名用作变量名,如 print。

3、字符串

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

"This is a string"
'This is also a string'
'I told my friend, "Python is my favorite language!"'
"The language 'Python' is named after Monty Python, not the anake."
"One of Python's strengths is its diverse and supportive community."

(1)修改字符串每个单词首字母的大小写

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

输出

Ada Lovelace

(2)修改字符串每个单词所有字母的大小写

name = "Ada Lovelace"
print(name.upper())
print(name.lower())

输出

ADA LOVELACE
ada lovelace

(3) 拼接字符串

first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name)

输出

ada lovelace

(4)使用制表符/换行符添加空白

print("\tPython")
print("Languages:\nPython\nC\nJavaScript")

输出

        Python
Languages:
Python
C
JavaScript

(5)删除空白

favorite_language = "python "
print(favorite_language+"!")
print(favorite_language.rstrip()+"!")
print(favorite_language+"!")

输出

python  !
python!
python  !

(6)字符串避免语法错误(特别是引号匹配)

msg = "One of Python's strengths is its diverse community."
print(msg)

输出

One of Python's strengths is its diverse community.

(7)换个引号

msg = 'One of Python's strengths is its diverse community.'
print(msg)

输出

File "d:/vscode/hello.py", line 74
    message = 'One of Python's strengths is its diverse community.'
                             ^
SyntaxError: invalid syntax
4、数字

(1)整数

# 加减乘除
print(3+6)
print(3-6)
print(3*6)
print(3/6)

输出

9
-3
18
0.5

(2) 乘方

print(3**2)
print(3**3)
print(10**3)

输出

9
27
1000

(3)混合运算

print(2+3*4)
print((2+3)*4)

输出

14
20

(4)浮点数

print(0.1+0.1)
print(0.2+0.2)
print(2*0.1)
print(2*0.2)

输出

0.2
0.4
0.2
0.4

(5)结果包含的小数位数可能是不确定的

print(0.2+0.1)
print(3*0.1)

输出

0.30000000000000004
0.30000000000000004

(6)使用 str() 函数避免类型错误

msg = "Happy " + age + "rd Birthday!"
print(msg)

输出

Traceback (most recent call last):
    File "d:/vscode/hello.py", line 126, in <module>
    msg = "Happy " + age + "rd Birthday!"
 TypeError: can only concatenate str (not "int") to str

(7)使用str()后

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

输出

Happy 23rd Birthday!
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值