python中的三目运算符的非 python 3目运算符_迭代


print('#')
#
#三目运算
#3>4 ? 'true' : 'false'
#报错,因为python 不支持此三目运算
a=4
b=3
#三目运算符的正确形式
result=(a+b) if a<b else (a-b)
print(result)


1


#关于运算符的优先级,大致顺序为
# 位运算符》算术运算符》关系运算符》》逻辑运算符》赋值运算符
#赋值运算符的优先级最低
username='admin'
#username='' 输出False
#username=0 输出False
if username:
    print('True')
else:
    print('False')
False
"""
if 条件1:
   成立
   if 条件2:
       成立
       ...
   else:
       ...

elif  条件:
    ....

elif  条件:
    ....

else:
    print('不成立')

"""


"""
与else语句类似,elif语句是可选的。 
但是,与else语句不同的是,else语句最多可以有一个语句,在if之后可以有任意数量的elif语句。
原文出自【易百教程】,https://www.yiibai.com/python/python_if_else.html

"""

#range(K), 产生的序列包头不包尾  0~k-1
#打印10次,生成的序列是从0开始,到9
for i in range(10):
    print(i)
#range(m,n)  --> m,m+1,..., n-1


for i in range(10):
    if i ==3:
        print('yes 3')
    else:
        print('not 3')
print('over')


not 3
not 3
not 3
yes 3
not 3
not 3
not 3
not 3
not 3
not 3
over


#for...else, 当for循环执行完毕,或者没有循环数据的时候,执行else的语句
#for...else是一个整体的代码块,如果其中有break ,则满足条件时候会全部跳出此for...else代码块
for i in range(3):
    print(i)
else:
    print('over')
print('*'*8)  
for i in range(0):
    print(i)
else:
    print('over')


0
1
2
over
********
over


#强制指定只能登录三次

for i in range(3):
    username=input('请输入用户名:')
    password=input('请输入pwd:')
    if username=='admin' and password=='admin':
        print('success')
        break
        #此break 会跳出for...else整个代码块,执行下面的代码
    else:
        print('error')
else:
    print('for循环产生的迭代序列已经用完')
    print('3次输错,锁定用户')


请输入用户名:d
请输入pwd:d
error
请输入用户名:d
请输入pwd:d
error
请输入用户名:d
请输入pwd:d
error
for循环产生的迭代序列已经用完
3次输错,锁定用户


for i in range(0,50,5):
    print(i)
#包头不包尾,没有50
#range(n)-----range(0, n)
#range(m,n)------range(start, end)
#range(m,n, step)---------range(start, end, step)


"""
while...else代码块 ,  一般常用while,省略了else



while 条件满足:
    语句1

#条件不满足时候
else:
    语句2
"""

i=2
while i>1:
    print(i)
    i-=1
else:
    print('in else')
2
in else
#打印0-10之间3的倍数
i=0
while i <11:
    if i%3==0:
        print('{} 是3的倍数'.format(i))
    else:
        print('{}不是3的倍数'.format(i))
    i+=1


0 是3的倍数
1不是3的倍数
2不是3的倍数
3 是3的倍数
4不是3的倍数
5不是3的倍数
6 是3的倍数
7不是3的倍数
8不是3的倍数
9 是3的倍数
10不是3的倍数


#利用两层while嵌套循环打印九九乘法表
row=1

while row<10:
    col=1    
    while col<=row:
        print('{}*{}={}'.format(col,row,col*row), end=' ')
        col+=1
    #每次打印完一行就打印一个换行符
    print()
    row+=1
else:
    print('while中的条件已经不成立')
    print('九九乘法表已经打完')


1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
while中的条件已经不成立
九九乘法表已经打完


import random
random.randint(1,2)
#random.randint(a,b) 是随机取【a,b】区间中的整数,可以取到两端的数值
2
a,b=2,3
print(a)
print(b)
c=d=34
print(c)
print(d)
2
3
34
34
#计算1-10之间的偶数之和
sum=0
for i in range(1,10):
    b=0
    b+=i
    print('i:',i)
    if i%2==0:
        sum+=i

print(sum)
#python中, 可以在for , while循环外取到循环内的变量值,也就是在for,while的循环中没有变量的作用域

print(b)


i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
20
9


#continue结束本次循环,继续回到循环开始的地方,判断条件是否满足,若满足则继续开始下一次的循环
#break会跳出循环,不再执行循环体内的代码了

#字符串的声明
#单引号,双引号,三引号
#当三引号""" """保留字符串的格式时,那么它的内存空间与单双引号的就不一样了
#字符串的运算符 
#  +拼接  * 倍数  in在...里面
name='hello'
print('h' in name )
print('sh' in name )
print('sh' not in name )

# %字符串的格式化
#  '  转义字符,  '表示单引号
print('%s说:'%s'' % ('老师','好好学习'))

#r表示保留原始字符串格式, 不会转义
print(r'%s说:'%s' % ('老师','好好学习'))


True
False
True
老师说:'好好学习'
老师说:'好好学习


name='filename.png'
#逆序输出
a=name[::-1]
print(a)

#包头不包尾
a=name[:-4:-1]
print(a)

a=name[::]
print(a)

a=name[:-4]
print(a)

#每两个取一个值(索引为0,2,4...),最后一个2表示step步长
a=name[::2]
print(a)

#倒着取,每两个取一个值(索引为-1,-3)
a=name[:-4:-2]
print(a)


gnp.emanelif
gnp
filename.png
filename
flnm.n
gp


msg='ni hao, nice to Meet You'
#首字母大写
m=msg.capitalize()
print(m)

m=msg.title()
print(m)

print(msg.istitle())
print(msg.upper())
print(msg.isupper())
print(msg.lower())
print(msg.islower())


Ni hao, nice to meet you
Ni Hao, Nice To Meet You
False
NI HAO, NICE TO MEET YOU
False
ni hao, nice to meet you
False


s1='ni hao, nice to Meet You'
position=s1.find('A')
# -1 表示没有找到
print(position)

position=s1.find('M')
print(position)

#指定起始位置find
position=s1.find('n', 2,9)
print(position)

#Str.find(str, beg=0, end=len(string))
#包头不包尾,查找范围是beg到end-1


-1
16
8


url='www//pp/123.png'
#rfind  : right find
p=url.rfind('/')
print(p)
filename=url[p+1:]
print(filename)


7
123.png


s1='ni hao, nice to Meet You'
s2=s1.replace('hao','good')
print(s2)


ni good, nice to Meet You


s1='ni hao, nice to neet You'
#str.replace(),替换字符串函数,从左到右开始查找替换,2表示替换两次
s2=s1.replace('n','N',2)
print(s2)


Ni hao, Nice to neet You


m1='上课了'
m2=m1.encode('utf-8')
print(m2, type(m2))
#<class 'bytes'>


#decode()函数是binary文件调用的函数
m=m2.decode('utf-8')
print(m, type(m))
# <class 'str'>


b'xe4xb8x8axe8xafxbexe4xbax86' <class 'bytes'>
上课了 <class 'str'>


"""
>>> a='abb.txt'
>>> a.startswith('ab')
True
>>> a.startswith('a')
True
>>> a.startswith('abb.')
True
>>> a.endswith('t')
True
>>> a.endswith('tx')
False
>>> a.endswith('xt')
True
>>> a.endswith('txt')
True
>>> a.endswith('.txt')
True
"""

name='a.jpg'
if name.endswith('jpg') or name.endswith('png'):
    print('ok')


ok


#字符串的内建函数
#大小写相关 capitalize()  tile() istitle() upper()  isupper() lower() islower()
#与查找相关 find()  rfind()  lfind() index() lindex() rindex()  replace()

#编码  str.encode()  str.decode()
# 字符串判断  str.startswith()   str.endswith()  str.isalpha()  str.isdigit()
# len(str)
s='abds'
print(s.isalpha())
print(s.isdigit())

s='132'
print(s.isalpha())
print(s.isdigit())


True
False
False
True


#join()用于拼接
'--'.join('and')
s='3454'
print(max(s))
print(min(s))
print(len(s))

s=' ook hel '
#用于去除空格
print('aaa'+s.strip()+'aaa')
print('aaa'+s.lstrip()+'aaa')
print('aaa'+s.rstrip()+'aaa')


5
3
4
aaaook helaaa
aaaook hel aaa
aaa ook helaaa
['hello', 'world', 'hello'] 2


s='hello world hello kiet'
print(s.split(' '))
#split(' ', num) , num表示切割次数, 生成num+1个字符串
print(s.split(' ',2))
#计算个数
s.count(' ')

#了解   str.expandtabs(20):将tab符号转为20个空格。 用于美化输出


['hello', 'world', 'hello', 'kiet']
['hello', 'world', 'hello kiet']
3


a='234'
print(a, id(a))
a=3333
print(a, id(a))


234 140473417092376
3333 140473417009264


"""
列表中的元素可以修改,
>>> a=['213','q','s']
>>> a[q]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'q' is not defined
>>> a[1]
'q'
>>> a[1]='d'
>>> a
['213', 'd', 's']

字符串可以重新赋值,(但是字符串属于不可变对象)

>>> a='33e'
>>> a='33'
>>> a
'33'

"""
brand=['vivp', 'ooop','hp','mac','ovde']
print(brand)
brand[-1]='apple'
print(brand)


['vivp', 'ooop', 'hp', 'mac', 'ovde']
['vivp', 'ooop', 'hp', 'mac', 'apple']


#删除列表中的指定元素
brands=['vivp', 'ooop','hp','mac','ovde']

#在遍历的同时去删除元素会报错,因为列表中的元素索引在改变
#IndexError: list index out of range
"""
i=0
for i in range(len(brands)):
    if brands[i]=='hp' or brands[i]=='mac':
        del brands[i]
print(brands)
"""

#对于str来说,他是个可迭代对象,因此for循环会迭代取出其中的每一个字符
for i in 'sdfv3f':
    print(i)
print('*'*8)
#对于list来说,他也是个可迭代对象,因此for循环会迭代取出列表中的每个元素
for i in ['sdfv3f','2','3']:
    print(i)
print('*'*8)

#对于tuple来说,他也是个可迭代对象,因此for循环会迭代取出tuple中的每个元素
for i in ('sdfv3f','2','3'):
    print(i)
print('*'*8)

#对于字典来说,他也是个可迭代对象,因此for循环会迭代取出字典中的每个键值
for i in {'key1':'en','key2':'3'}:
    print(i)


s
d
f
v
3
f
********
sdfv3f
2
3
********
sdfv3f
2
3
********
key1
key2


if 'good' in 'goods':
    print('yes')

if 'good' in ['good','23']:
    print('yes')
else:
    print('no')

if 'good' in ['goods','23']:
    print('yes')
else:
    print('no')


if 'good' in [['good'],'jack']:
    print('yes')
else:
    print('no')


yes
yes
no
no


#输入brand,然后删除
brands=['vivp', 'ooop','oop','hp','mac','ovde']
s1=input('请输入想删除的对象:')


i=0
length=len(brands)
while i<length:
    if s1 in brands[i]:
        del brands[i]
        #删除完毕后, length就-1, 同时结束本次循环,待删除元素的index表示不变

        length-=1
        continue       

    #直到没有要删除的元素时,index才可以继续+1,向前进
    i+=1

print('after del---》',brands)


请输入想删除的对象:oo
after del---》 ['vivp', 'hp', 'mac', 'ovde']


a=['a','c']
del a[1]
print(a)
#del 可以删除列表中的指定元素,修改的是原列表本身
['a']
a=['9', '5', '4', '2', '1']
b=['ab','sd']

#两个列表可以直接相加
print(a+b)


['9', '5', '4', '2', '1', 'ab', 'sd']


name=['唐山','wiki','娜姐']
#append 末尾追加   insert()指定位置追加   extend() 两个列表合并(一次性添加多个元素)
name.insert(1, '刘涛')
#list.insert(index,'') 指定下标,插入元素
print(name)

name.append('jack')
print(name)

name.extend('tom')
print(name)

name=['唐山','wiki','娜姐']
name2=['北京','南京']
name.extend(name2)
print(name)


['唐山', '刘涛', 'wiki', '娜姐']
['唐山', '刘涛', 'wiki', '娜姐', 'jack']
['唐山', '刘涛', 'wiki', '娜姐', 'jack', 't', 'o', 'm']
['唐山', 'wiki', '娜姐', '北京', '南京']