Python:条件、循环及其它语句

1、print 可打印多个参数

A='hello,'
B='Mr'
C='lijunshy'
print(A,B,C)
hello, Mr lijunshy #结果

A='hello'
B='Mr'
C='lijunshy'
print(A,',',B,C)
hello , Mr lijunshy # 这样也可以

A='hello'
B='Mr'
C='lijunshy'
print(A +',',B,C)
hello, Mr lijunshy #这样的话,hello后的逗号‘,’前没有空格

print('i','am','a','boy',sep='_')
i_am_a_boy  # 自定义分隔符,用sep()

从模块导入时重命名

import module1
module1.open(...)
或使用from module import function
或使用from module import function1,function2,function3 #导入三个函数
或使用from module import *   #导入该模块的所有函数

但是若有两个模块都有同一函数怎么办?为模块或函数命名

法一:
import module1
module1.open(...)
或
import module2
module2.open(...)  #这样一个一个导入

法二:重命名
import math as lijun
lijun.sqrt(9)  # 将模块重新命名以区别

from math import sqrt as lijun
lijun(9) # 导入特定函数并为该函数命名

2、赋值使用技巧

序列解包:

x,y,z=1,2,3
print(x,y,z)
1 2 3      #

x,y=y,x
print(x,y,z)
2 1 3       # x,y=y,x这是把x和y的位置反过来

a=1,2,3
a
x,y,z=a
x
Out[13]: 1  #

序列解包使用方法例子:假设要从字典中随便获取(或删除)一个键-值对,可使用popitem,它随便获取一个键-值对并以元组的方式返回,接下来,可直接将返回的元组解包到两个变量。

A={'name':'李军帅','girlfrend':"杜晓雪"}
x,y=A.popitem()  #随便获取一个键-值对,并解包
x
Out[14]: 'girlfrend' 
y
Out[15]: '杜晓雪'
# 这让函数能够返回被打包成元组的多个值,然后通过一条赋值语句轻松访问这些值

注意:要解包的序列包含的元素个数必须要与你等号左边列出的目标个数相同,否则Python会报错

x,y,z=1,2

x,y,z=1,2,3,4  这两种都不行

当使用*时,左右两边的个数可以不一样

a,b,*lijun=[1,2,3,4,5]
lijun
Out[17]: [3, 4, 5] # 

name='li','jun','shy','du','xiao','xue'
a,*b,c= name.split()
b
['jun','shy','du','xiao'] #  *也可以用在中间

增强赋值:

x=x+1  可以写成 x +=1这称为增强赋值,适用于所有标准运算符,如:*和/等

x=2
x+=1
x*=2
x
Out[21]: 6 

a='杜'
a+='晓雪'
a*=2
a
Out[22]: '杜晓雪杜晓雪'
# 通过使用增强赋值,可让代码更紧凑、更简洁

3、if 语句和 else 语句

小例子:

name=input("what is your name?")
if name.endswith('shuai'):
    print('hello shuai')

what is your name?lijunshuai #输入lijunshuai
hello shuai                  #结果

name=input("what is your name?")
if name.endswith('shuai'):
    print('hello shuai')
else:
    print('hello,stranger')
what is your name?杜晓雪  #输入
hello,stranger            #结果

elif 语句

a=int(input('Enter a number'))
if a>0:
    print('the number is positive')
elif a<0:
    print('the number is negative')
else:
    print("the number is zero")
Enter a number12           #输入12
the number is positive     #输出结果

多个if 语句嵌套

name=input('what is your name?')
if name.endswith('Lee'):
    if name.startswith('Mr'):
        print('hello,Mr.Lee')
    elif name.startswith('Mrs'):
        print('hello,Mrs.Lee')
    else:
        print('hello,Lee')
else:
    print('hello,stranger')

what is your name?Mr.Lee  #输入Mr.Lee
hello,Mr.Lee              #结果

what is your name?Lee
hello,Lee

what is your name?Mr lee
hello,stranger

比较运算符:

‘==’ :两个等号是“等于”的意思;x==y 表明x等于y。

‘<’  : 小于。 ‘<=0’ :小于等于。

‘>’  : 大于。‘>=’  :大于等于。

‘!=’ :不等于。

‘is’ :       x is y 说明x和y是同一个对象。

‘is not’: x is  not y 说明x和y不是同一个对象。

x in y :x是y的成员。

x not in y :x 不是y的成员。

“==”的例子:

'杜晓雪'=='杜晓雪'
Out[52]: True  #“==”表示两个对象是否相等

'杜晓雪'=='李军帅'
Out[53]: False  #

若用一个等号呢?
'杜晓雪'='杜晓雪'
SyntaxError: can't assign to literal  不能分配给文字
# 一个等号表示赋值运算符,用于修改值

“is”的例子:

a=b=[1,2]
c=[1,2]
a==b
Out[55]: True #

a==c
Out[56]: True  #

a is b
Out[57]: True  #a和b是同一个对象

a is c
Out[58]: False  #a和c只是相等,但并非相同。

总之:“==”检查两个对象是否相等;“is”检查两个对象是否相同。

布尔运算符:

例子:

number=int(input('enter a number between 1 and 10:'))
if number<=10:
    if number >=1:
        print("great")
    else:
        print("wrong")
else:
    print("wrong")
enter a number between 1 and 10:4  #
great                              #

这样可行,但是可发现,输入两边print(‘wrong’),怎么变简单呢?如下:用and布尔运算符。

number=int(input('enter a number between 1 and 10:'))
if number<=10 and number>=1:
    print("great")
else:
    print("wrong")

4、循环

4.1 while循环

x=1
while x<=10:
    print(x)
    x +=1 # x +=1等于x=x+1
1         # 输出
2
3
4
5
6
7
8
9
10


name=""
while not name:
    name=input("please enter your name:")
print("hello,{}!".format(name))
please enter your name:         #什么也不输入
please enter your name:李军帅   #输入李军帅
hello,李军帅!
#运行该段代码,并在要求输入名字时空白直接回车,会再次看到信息出现,因为name还是空字符

4.2 for 循环

for number in range(1,10):
    print(number)

1     # 输出结果
2
3
4
5
6
7
8
9

words=['this','is','a','杜晓雪']
for word in words:
    print(word)
this  # 输出结果
is
a
杜晓雪

for 循环是把特定范围内元素遍历一遍。

综合来看,相比于while循环,for循环要紧凑的多,因此能使用for循环就不再使用while循环

4.3 跳出循环

① break

例子:想找出小于100的最大平方值,从100往下迭代,找到第一个平方值后,无需再迭代。

from math import sqrt
for m in range(99,0,-1):
    a=sqrt(m)
    if a==int(a):
        print(m)
        break
81     # 有break的结果

from math import sqrt
for m in range(99,0,-1):  # 向下迭代
    a=sqrt(m)
    if a==int(a):
        print(m)
81      # 无break的结果是把所有平方值都输出
64
49
36
25
16
9
4
1

② continue

continue不如break那么用的多,它是结束当前迭代,并跳到下一个迭代(还是本循环)的开头。

a=10
while a>0:
    a=a-1
    if a==5:
        continue   #意思是若a等于5,则返回循环,所有不会print出5
    print('当前变量值:',a)
print('拜拜')

当前变量值: 9  #输出结果
当前变量值: 8
当前变量值: 7
当前变量值: 6
当前变量值: 4
当前变量值: 3
当前变量值: 2
当前变量值: 1
当前变量值: 0
拜拜

for letter in 'Python':     
   if letter == 'h':
      continue
   print ('当前字母 :', letter)
当前字母 : P  # 结果与上类似
当前字母 : y
当前字母 : t
当前字母 : o
当前字母 : n

③ while true/false

根据用户输入的单词执行接下来的操作:

a='lijun'    #‘lijun’可以换成别的任何
while a:
    a=input('please enter a word : ')
    print("the word was:",a)

please enter a word : lijun  #输出结果
the word was: lijun

please enter a word : lll
the word was: lll

please enter a word : 
    

上边这个例子,首先要把哑值(未用的值)赋值给a。下边来尝试消除哑值:

a=input("enter your word:")
while a:
    print('the word is :',a)
a=input("enter your word:")  #若不加这一局,这一直输出the word is : lijun,永不停止

enter your word:lijun  #结果
the word is : lijun
enter your word:

但是这个例子,有两段代码重复不太好,怎么消除?用while true

while True:
    a=input('please enter a word:')
    if not a: break       #若什么也不输入,则停止循环
    print('the word is :',a)

please enter a word:ll   #输入单词后才能继续循环,出现‘please enter a word:’
the word is : ll
please enter a word:    

实例:建立一个用户登录系统,用户输入用户名和密码,如果正确就可以进入系统。

d = {'杜晓雪':'1234'}        #数据库字典,所有用户的用户名密码存储在此
name = input("请输入您的用户名:")
if name in d:
    password = input("请输入您的密码:")
    if d[name] == password:
        print('进入系统')
    else:
        print('您输入的密码错误,请重新输入')
else:
    print('您输入的用户名不正确,请重新输入')

请输入您的用户名:杜晓雪  # 若名字和密码都对,则进入系统
请输入您的密码1234
进入系统

请输入您的用户名:李军    #  名字错了,要求重新输入名字
您输入的用户名不正确,请重新输入

请输入您的用户名:杜晓雪  #  密码错了要求重新输入密码
请输入您的密码:12
您输入的密码错误,请重新输入

上例不能自动提示再输入一次,而是只是提示出错,不返回输入的地方。如果用户输入的用户名和密码都正确,那自然是没有问题的。但是如果有一个输入不正确,那系统只会显示“您输入的用户名不正确,请重新输入”或“您输入的密码错误,请重新输入”。也就是说,如果出现错误,没有返回到原来的地方请求继续输入

d = {'杜晓雪':'1234'} 
while True:
    name = input('请输入您的用户名:')
    if name in d:
        break
    else:
        print('您输入的用户名不存在,请重新输入')
        continue

while True:
    password = input('请输入您的密码:')
    if d[name] == password:
        print('进入系统')
        break
    else:
        print('您输入的密码不正确,请重新输入')
        continue
请输入您的用户名:lijun          # 这样的结果符合我们平常所见#
您输入的用户名不存在,请重新输入

请输入您的用户名:杜晓雪

请输入您的密码:12
您输入的密码不正确,请重新输入

请输入您的密码:123
您输入的密码不正确,请重新输入

请输入您的密码:1234
进入系统

采用while true语句的核心思想是如果出现错误的话,可以继续循环。

while True 语句中一定要有结束该循环的break语句,否则会一直循环下去的。

当然,我们遇见过如果密码错误的话,提示您还有几次输入密码的机会。可以这样实现:

d = {'杜晓雪':'1234','李军帅':'2312'}  
while True:
    name = input('请输入您的用户名:')
    if name in d:
        break
    else:
        print('您输入的用户名不存在,请重新输入')
        continue
count=10
while count:
    password=input('请输入密码:')
    if d[name]==password:
        print('通过')
        break
    else:
        count-=1
        print('您输入密码不正确,还有{}次机会'.format(count))
        continue
d = {'杜晓雪':'1234','李军帅':'2312'}  
while True:
    name = input('请输入您的用户名:')
    if name in d:
        break
    else:
        print('您输入的用户名不存在,请重新输入')
        continue
count=10
while count:
    password=input('请输入密码:')
    if d[name]==password:
        print('通过')
        break
    else:
        count-=1
        print('您输入密码不正确,还有{}次机会'.format(count))
        continue
d = {'杜晓雪':'1234','李军帅':'2312'}  
while True:
    name = input('请输入您的用户名:')
    if name in d:
        break
    else:
        print('您输入的用户名不存在,请重新输入')
        continue
count=10
while count:
    password=input('请输入密码:')
    if d[name]==password:
        print('通过')
        break
    else:
        count-=1
        print('您输入密码不正确,还有{}次机会'.format(count))
        continue
d = {'杜晓雪':'1234','李军帅':'2312'}  
while True:
    name = input('请输入您的用户名:')
    if name in d:
        break
    else:
        print('您输入的用户名不存在,请重新输入')
        continue
count=10
while count:
    password=input('请输入密码:')
    if d[name]==password:
        print('通过')
        break
    else:
        count-=1
        print('您输入密码不正确,还有{}次机会'.format(count))
        continue
请输入您的用户名:李军帅   # 

请输入密码:11
您输入密码不正确,还有9次机会

请输入密码:

④ 循环中的else语句

from math import sqrt
for m in range(99,81,-1):
    a=sqrt(m)
    if a==int(a):
        print(m)
        break
else:                #  else必须放在最左边,如果和if对齐,则相当于对if a==int(a)的else
        print('没找到')
 
没找到  # 结果

猜你喜欢

转载自blog.csdn.net/Hellolijunshy/article/details/82344546