Python学习笔记——1、变量和简单数据类型

一、变量的命名和使用
1、变量名只能包含字母、数字和下划线。变量名可以字母或下划线打头,但不能以数字打头,例如,可将变量命名为message_1,但不能将其命名为1_message。
2、变量名不能包含空格,但可使用下划线来分隔其中的单词。例如,变量名greeting_message可行,但变量名greeting message会引发错误。
不要将Python关键字和函数名用作变量名,即不要使用Python保留用于特殊用途的单词,如print。
变量名应既简短又具有描述性。例如,name比n好,student_name比s_n好,name_length比length_of_persons_name好。

二、使用变量时避免命名错误

>>> message = "Hello Python"
>>> print(mesage)
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    print(mesage)
NameError: name 'mesage' is not defined

名称错误通常意味着两种情况:要么是使用变量前忘记了给它赋值,要么是输入
变量名时拼写不正确。

三、字符串操作:
1、大小写

#1.首字母大写Abc Love
>>> name = "abc lovE"
>>> print(name.title())
Abc Love

#2.全部大写ABC LOVE
>>> print(name.upper())
ABC LOVE

#3.全部小写abc love
>>> print(name.lower())
abc love

2、拼接操作

>>> first_name = "abc"
>>> last_name = "123"
>>> full_name = first_name
>>> full_name = first_name + " " + last_name
>>> print(full_name)
abc 123

3、制表符或换行符

#1.制表符\t
>>> print("Python")
Python
>>> print("\tPython")
    Python
#2.换行符\n
>>> print("Languages:\nPython\nC\nJava")
Languages:
Python
C
Java

4、删除空白

1.删除末尾空白rstrip()
>>> favorite_foot = 'meat '
>>> favorite_foot
'meat '
>>> favorite_foot.rstrip()
'meat'
>>> favorite_foot
'meat '
>>> favorite_foot = favorite_foot.rstrip()
>>> favorite_foot
'meat'
>>> 

会发现要永久删除favorite_foot变量中的空格,需要将操作后的结果存回favorite_foot变量

#2.删除开头空白lstrip()
>>> favorite_foot = ' berries '
>>> favorite_foot.lstrip()
'berries '

#3.删除开头和结尾的空格strip()
>>> favorite_foot = " I love berries "
>>> favorite_foot.strip()
'I love berries'

四、运算

>>> 2 + 1
3
>>> 3 - 1
2
>>> 2 * 2
4
>>> 3 / 2
1.5
>>> 3 ** 2
9
>>> 3 ** 3
27
>>> (2 + 3) * 2
10

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

>>> message = "Happy" + age + "rd Birthday!"
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    message = "Happy" + age + "rd Birthday!"
TypeError: must be str, not int
>>> message = "Happy" + str(age) + "rd Birthday!"
>>> print(message)
Happy11rd Birthday!

这是一个类型错误 ,意味着Python无法识别你使用的信息。在这个示例中,Python发现你使用了一个值为整数(int )的变量,像上面这样在字符串中使用整数时,需要显式地指出你希望Python将这个整数用作字符串。为此,可调用函数str() ,它让Python将非字符串值表示为字符串

猜你喜欢

转载自blog.csdn.net/github_35707894/article/details/80309667