1.变量
定义:
变量就是存放数据的盒子,我们通过使用变量这个盒子进而调用盒子里面的数据
命名规则:
变量名只能包含字母、数字和下划线。变量名可以字母或下划线打头,但不能以数字打头;
变量名不能包含空格,但可使用下划线来分隔其中的单词;
不要将Python关键字和函数名用作变量名;
变量名应既简短又具有描述性;
慎用小写字母l和大写字母O,因为它们可能被人错看成数字1和0.
2.基本数据类型
- 整数----int
- 小数----float
- 布尔值----True,Flase
- 字符串-----string(%s)
3.字符串
1.定义:
字符串是有数字、字母、下划线组成的一串字符。‘1223’、‘’12wej、‘123_weddww466587’’等
2.转义字符
3.长字符串
(1) ‘’’,""",可多行输入输出:
a='''hello
westos'''
print(a)
hello
westos
(2) \t,\n示例
a1= "hello\nworld"
print(a1)
a2= "hello\tworld"
print(a2)
hello
world
hello world
4.格式化字符串
(1) 连接操作符 “+”
s = 'hello'
print(s+" westos")
hello westos
(2) 三种占位符
(3)标准化输出
s = 'hello'
a = 123
print('%s %d'%(s,a))
hello 123
(4) 标准化输出 (自动匹配变量的类型)
s = 'hello'
a = 123
print(f"{s} {a}")
hello 123
s = 'hello'
a = 123
b = f'{s} {a}'
print(b)
print(f"{s} {a}")
hello 123
hello 123
(5) str.format()
示例1:
s = 'i like {},{}'
r = s.format('python',"c")
print(r)
i like python,c
示例2:
n = 'tom is {0} years old.\n {1} is older'
m = n.format("10","jerry")
print(m)
tom is 10 years old.
jerry is older
示例3:
s = 'i like {},{}'
r = s.format('python','c','java')
print(r)
i like python,c
#s.format()中的字符可以大于s中中括号数,但只读前两个,不可以小于。
字符串的搜索统计
s = "hello.westos.123 "
print(s.find('ll'))
print(s.count('l'))
print(s.split('.'))
li = s.split('.')
print("-".join(li))
2
2
['hello', 'westos', '123 ']
hello-westos-123
s.find() #字符串s中第一个’‘ll"出现的位置(依次为0,1,2,3,4…)
s.count #字符串s中’l’的数量
s.split(’.’) #将字符串s中以’.'分割的字符,分割成为一个列表
s.join()
拼接字符串,用于将序列中的元素以指定的字符连接生成一个新的字符串。
返回通过指定字符连接序列中元素后生成的新字符串。
语法 str.join(seq)即使用str的符号,将seq原序列链接
*序列必须是字符串,否则报错
seq = ['1','2','3']
print('-'.join(seq))
1-2-3
实例
实例1:
随机输入一个字符串,判断是否为回纹字符串,不管": , 空格 ",其他字符依次第一二… 与倒数第一二…相同。是为True,不是为False
s = input("please input string: ")
s = s.lower().replace(" ","").replace(",","").replace(":","")
if s == s[::-1]:
print("true")
else:
print("Flase")
please input string: ssh ada hss , :
true
#s.lower()将字符串s中的字符都转换成小写字符
s.replace(" “,”")将字符串中的空格全都,转换为“,”
s[::-1] 将字符串s倒序排列
实例2:
随即生成五道加减乘的数学题,学生计算后输入计算后的答案,正确返回True,错误返回Error,最后统计正确率:
import random
n=0
for i in range(5):
num1 = random.randint(1,10)
num2 = random.randint(1,10)
symbol = random.choice(['+','-','*'])
print(f'{num1}{symbol}{num2}= ')
result =eval(f'{num1}{symbol}{num2}')
sum = int(input ("please input your answer: "))
if sum == result:
n+=1
print("True")
else:
print("Error")
hege = (n/5 )*100
print(f'zhunquelvwei: {hege}%')
6+6=
please input your answer: 12
True
7+10=
please input your answer: 15
Error
10*10=
please input your answer: 1
Error
6+1=
please input your answer: 1
Error
8-1=
please input your answer: 1
Error
zhunquelvwei: 20.0%
#random.randint(1,10) 随即生成(1...10)的数字
random.choice(['+','-','*']) 随即在['+','-','*']选择一个
eval()计算函数
实例3:
随机输入一个ip判断是不是正确格式,正确输出IPV4,错误输出Nether:
ip = input("please input ipaddr: ")
code = 0
for x in ip.split('.'):
if not x.isdigit():
code += 1
elif not 0 <= int(x) <=255:
code += 1
elif len(x) !=1 and int(x[0]) == 0:
code += 1
if code == 0:
print("IPV4")
else:
print("Nether")
please input ipaddr: 172.02.22.22
Nether