每日Python五分钟1:变量和简单数据类型

版权声明:本文为博主原创文章,转载请标明地址。欢迎关注微信订阅号:PM实验室。 https://blog.csdn.net/plain_maple/article/details/89118644
欢迎关注微信公众号:PM实验室

1、hello world

print("hello python world!")

输出

hello python world!

2、变量

添加一个msg变量
msg = "hello python world!"
print(msg)

输出

hello python world!
修改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."
修改字符串每个单词首字母的大小写
name = "ada lovelace"
print(name.title())

输出

Ada Lovelace
修改字符串每个单词所有字母的大小写
name = "Ada Lovelace"
print(name.upper())
print(name.lower())

输出

ADA LOVELACE
ada lovelace
拼接字符串
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name)

输出

ada lovelace
使用制表符/换行符添加空白
print("\tPython")
print("Languages:\nPython\nC\nJavaScript")

输出

        Python
Languages:
Python
C
JavaScript
删除空白
favorite_language = "python "
print(favorite_language+"!")
print(favorite_language.rstrip()+"!")
print(favorite_language+"!")

输出

python  !
python!
python  !
字符串避免语法错误(特别是引号匹配)
msg = "One of Python's strengths is its diverse community."
print(msg)

输出

One of Python's strengths is its diverse community.
换个引号
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、数字

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

输出

9
-3
18
0.5
乘方
print(3**2)
print(3**3)
print(10**3)

输出

9
27
1000
混合运算
print(2+3*4)
print((2+3)*4)

输出

14
20
浮点数
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
结果包含的小数位数可能是不确定的
print(0.2+0.1)
print(3*0.1)

输出

0.30000000000000004
0.30000000000000004
使用函数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
使用str()后
age = 23
msg = "Happy " + str(age) + "rd Birthday!"
print(msg)
输出
Happy 23rd Birthday!

猜你喜欢

转载自blog.csdn.net/plain_maple/article/details/89118644