#1 变量与数据类型
Hello python
print("hello python")
输出语句
massage = "Hello python world"
print(massage)
声名变量massage 并输出massage
massage = "Hello python world"
print(massage)
massage = "Hello again!"
print(massage)
变量覆盖,输出结果为
Hello python world
Hello again!
Python变量的命名规则
1、只能包含字母、数字和下划线,不能以数字开头;
2、不要将Python关键字和函数名作为变量名。
避免使用大写字母
字符串
用引号引起来的都是字符串,引号可以是双引号,也可以是单引号。
vote="this is a string"
print(vote)
vote='this is a string'
print(vote)
输出结果:
this is a string
this is a string
[Finished in 159ms]
字符串的操作
字母大小写
.title() 首字母大写
.upper() 全部大写
.lower()全部小写
name="alan william"
print(name)
print(name.title()) # Capitalize the first letter
print(name.upper()) # Capitalize the letter
print(name.lower()) # Lowercase letters
运行结果:
alan william
Alan William
ALAN WILLIAM
alan william
合并字符串 ’ +’
#Merge string
first_name="alan"
last_name="william"
full_name=first_name+" "+last_name
print(full_name)
制表符\t 和 换行符\n
print("\ttpython")
print("I\nlove\npython")
运行结果:
tpython
I
love
python
删除空白
尾空白.rstrip()
头空白…lstrip()
两端空白…strip()
disgusting_word="python "
print(disgusting_word)
print(disgusting_word.rstrip)#临时改变#
#永久改变#
disgusting_word=disgusting_word.rstrip()
print(disgusting_word)
运行结果
python
python
python
关于print
在ptyhon2中可以按以下格式
print"Hello Python world!"
运行结果:
Hello Python world!
数字
整数
整数的基本运算
常见整数运算问题
5/2=2而不是2.5
但5.0/2=2.5以及5/2.0=2.5
2/3=0
注意:python中的整数和浮点数的区分是由数字本身决定,而不存在int或float
浮点
str()
将任何非字符串变为字符串
示例一
age=23
massage="Happy "+str(age)+"rd Birthday!"
print(massage)
运行结果:
Happy 23rd Birthday!
示例二
num=24.0
str_num=str(num)
print(num)
print(str_num)
a=num/2
b=str_num/2 #这一步,因为str_num是一个字符串,所以它不能与2进行除法运算,故会报错
print(a+b)
报错结果:
24.0Traceback (most recent call last):
24.0
File "D:\Dev\Python\WorkSpace\practice1.py", line 6, in <module>
b=str_num/2
TypeError: unsupported operand type(s) for /: 'str' and 'int'
[Finished in 175ms]