第三章 控制流结构

3.1 关系和逻辑运算符
关系运算符和逻辑运算符决定了条件
条件表达式的结果是true或者是flase
3.1.1 ASCII码值
在比较字符串的时候,比较的是字符串中的ASCII码值
所以,我们需要对ascii码进行了解
1:数字作为ascii码返回相应的字符
chr(n)
2:给出字符,返回相应的ascii码
ord(ch)

3.1.2
关系运算符
python 中的关系运算符
== 相等
!= 不等于
< 小于
大于
<= 小于等于
= 大于等于
in 是子字符串(适用于字符串,列表,元组)
not in 不是子字符串(使用于列表,字符串,元组)
以上运算符也适用于列表和元组
并且比较的对象应该是相同的,不能是不同的对象

#ascii和字符之间的相互转化
print(chr(65))
print(ord('A'))
#关系运算符的举例
print("hello"=="Hello")
print("a" not in ["a","b","c"])
print(["a","b","c"]<["a","c","d"])
#3.1.4  列表的排序
list1=[2,3,"a",'c']
list1.sort()
print(list1)
#以上程序出现错误很正常,原因是因为要求比较的数必须是相同的类型
#不同类型之间不可以比较
list1=['a','c','b']
list1.sort()
print(list1)
tu=('a','c','d')
tu.sort()
print(tu)

思考:因为Python当中元组是不可以被更改的对象,而使用排序,需要对每一个进行更改
所以会出现报错
3.1.4 逻辑运算符
and or not 它们的返回值也是布尔类型true和false
3.1.5 短路求值
expression1 and expression 如果expression1不正确的话,程序就不会往下执行,返回false,如果正确的话继续往下执行 expressin2
expression1 or expression2 如果expression 正确的话,程序就不会往下执行,返回true,如果不正确的话继续往下执行expression23.1.6 布尔类型的数据
flase/true3.1.7 返回值是布尔类型的数据的表达式
str1.endswith(str2) #str1以str2结尾
str2.starswith(str2) #str1以str2开头
isinstance(item,datatype) #判断某一个对象是哪一种类型
(python中的数据类型是int float str tuple,list)目前学到的
python 中判断字符串内容的方法,返回值布尔类型
str1.isdigit() #字符串中所有的字母都是数字
str1.isalpha() #字符串中的所有字符都是字母表上的字母
str1.isalnum() #字符串中的所有字符都是字母表上的字母或者是数字
str1.islower() #所有字符是小写
str1.isupper() #所有字符是大写
str1.isspace() #仅含有空白字符(空格,制表符,回车)

str1="aaabbb"
str2="aa"
str3="bb"
print(isinstance(str1,str))#判断对象的数据类型
print(str1.startswith(str2,0,2)) #判断开头
print(str1.endswith(str3)) #判断结尾
print(str1.isdigit())
print(str1.isalpha())
print(str1.isalnum())
print(str1.isupper())
print(str1.islower())
print(str1.isspace())
#其中startswith()里面的参数可以是元组,可以进行逐一匹配

3.2 判断结构
3.2.1 if-else语句
if condition:

else

python中语句块进行缩进处理,它可以执行多条语句
缩进代表了语句块的开始和结束,使用4个空格表示语句块

#使用python当中的if-else语句实现求最大值
num1=eval(input("Enter the first number:"))
num2=eval(input("Enter the second number:"))
if num1>num2:
    largeValue=num1
else:
    largeValue=num2
print("The alrger value is:"+str(largeValue))

3.2.2 if语句
if condition:

if condition:

3.2.3 if-elif-else 多分支语句
java一样

#计算一家公司的收支
costs=eval(input("Enter total costs:"))
revenue=eval(input("Enter total revenue:"))
if costs==revenue:
    result="Break even"
else:
    if costs>revenue:
        loss=costs-revenue
        result="Loss is ${0:,.2f}".format(loss)
    else:
        profit=revenue-costs
        result="profit is ${0:,.2f}".format(profit)
print(result)
#使用if-else-elif语句来进行验证用户的输入
num1=input("Enter first number:")
num2=input("Enter second number:")
if num1.isdigit() and num2.isdigit():
    print("The sum is",str(eval(num1)+eval(num2))+".")
elif not num1.isdigit():  #如果num1不是数字
    if not num2.isdigit():
        print("Neither entry was a proper number")
    else:
        print("The first entry was not a proper number")
else:
    print("the secon entry was not a proper number")

3.2.6 True 和 False
Python中每一个对象都有一个真值与其相关联,因此可以作为条件使用
当使用数字作为条件的时候,0会被赋值为False,其他的数字会被赋值为True
用作条件的空字符串、列表、元组都是False,其他的都是True

#每一个对象都和True和False相关联
if 5:
    print("Today is too cold")
else:
    print("Have a good day")
#判断语句的练习
str1=input("Who was the first Ronald McDonald?")
if str1=="Willard Scott":
    print("You are correct")
else:
    print("Nice try")
#儿童黑话
#如果一个单词(小写字母),将它转化成为儿童黑话
str1=input("Enter word to transelate:")
if str1[0] in ['a','e','i','o','u']:
    print(str1+"way")
elif str1[0] not in ['a','e','i','o','u'] and str1 not in ['a','e','i','o','u']:
    print(str1[2:]+str1[0:2]+"ay")
else:
    print(str1)
    

3.3 while 循环
3.3.1 while循环
while 循环的格式是
while condition:
statements

#假设有一笔年利率是4%的存款,下面的程序会见算出多久之后你才能成为一个百万富翁
numberOfYears=0
balance=eval(input("Enter initial deposit:"))
while balance<1000000:
    balance+=balance*0.04
    numberOfYears+=1;
print("In",numberOfYears,"years you will have a million dollars")

3.3.2 break语句
break 语句可以使得循环提前结束

#break 语句的使用
list1=[]
print("(Enter -1 to terminate entering numbers)")
while True:
    num=eval(input("Enter a nonnegative number:"))
    if num==-1:
        break
    else:
        list1.append(num)
print(list1)

3.3.3 continue语句
continue语句可以让当前循环终止,进行下一次循环

#循环语句里面的continue语句的使用
#判断一个列表中的数字可以被11整除
list1=["one",23,17.5,"two",33,22.1,242,"three"]
i=0
foundFlag=False
while i<len(list1):
    x=list1[i]
    i+=1
    if not isinstance(x,int):
        continue
    else:
        if x%11==0:
            foundFlag=True
            print(x,"is the first int that is divisiable by 11")
            break
if not foundFlag:
    print("There is not in the list that is divisiable by 11")
        
#放射性衰变问题
initate=100
i=0;
while initate>1:
    i+=28
    initate-=initate*0.5
print("The decay time is\n"+str(i)+"years")
    
#汽车贷款的问题
pricipal=15000
balance=15000
payMonth=290
month=0
while (balance>=pricipal/2):
    balance=(1.005*balance)-payMonth
    month+=1
print("Loan will be half paid off after {0:n}".format(month))

Loan will be half paid off after 33
print("ok")
ok
#年金问题
monthMoney=0 
month=0
while monthMoney<=3000:
    monthMoney=1.0025*monthMoney+100
    month+=1
print("after {0:n} months".format(month))
after 29 months
#年金问题
money=10000
month=0
while money>600:
    money=1.003*money-600
    month+=1
print("after {0:n},and money is {1:.2f}$ month".format(month,money))
after 17,and money is 73.91$ month

3.4 for循环
我们可以使用for 循环遍历一系列的值
它的一般的形式是:
for var in sequence:
statement
其中sequence可以是等差数列,字符串,列表,元组或者四文件对象。
变量var会依次被赋予序列的每一个值
3.4.1 等差数列的循环遍历
range(m,n)
产生的值是m…n-1

#人口增长
pop=300000
print("{0:10} {1}".format("Year","Population"))
for year in  range(2014,2019):
    print("{0:<10d} {1:,d}".format(year,round(pop)))
    pop+=pop*0.03
Year       Population
2014       300,000
2015       309,000
2016       318,270
2017       327,818
2018       337,653

3.4.2 range函数的步长值
当我们不想以步长1来依次增加的话,可以指定步长,例如:range(1,10,2)
1,3,5,7
而且还可以使用递减的序列,此时要求步长是负数,并且初始值大于结束值
range(6,0,-1)
3.4.4 字符串的字符遍历循环
会遍历字符串中的每一个字符

#字符串的逆序输出
word=input("Enter the word:")
reverseWord=""
for ch in word:
    reverseWord=ch+reverseWord
print(reverseWord)
Enter the word:zeus
suez

3.4.5 遍历列表或元组当中的元素

#遍历列表或者是元组中的元素
months=["January","February","March","April","May","June",
          "July","Augut","September","October","December"]
for month in months:
    if 'r' in month.lower():
        print(month)
        
        
January
February
March
April
September
October
December
#月份的缩写
months=["January","February","March","April","May","June",
          "July","Augut","September","October","December"]
for i in range(len(months)):
    months[i]=months[i][0:3]
    print(months[i])
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Dec

3.4.6 文本文件的行遍历
将会按行来读取每一行数据

firstName=input("Enter a first name:")
file=open("F:\\桌面\\1.txt","r")
foundFlag=False
for line in file:
    if line.startswith(firstName):
        foundFlag=True
        print(line.rstrip())#去掉右边的空白符好
file.close()
if not foundFlag:
    print("No such name:"+firstName)
Enter a first name:caojuan
caojuan

3.4.8 使用文本文件创建列表
有两种方式,分别针对纯文本和纯数字的文本
1:针对纯文本的方式
file=open(“filename”,“model”);
list1=[line.rstrip() for line in file]
file.close()
2:针对纯数字对的方式
file-open(“filename”,“model”)
list1=[eval(line) for line in file]
file.close()

tuple1=(1,2,3)
list1=list(tuple1)
list1[1]=4
print(list1)
[1, 4, 3]

excise:

#移除用户输入的电话号码当中的横线
str1=input("Enter a telephone number:")
for ch in str1:  #循环遍历
    if(ch=='-'):
        continue
    else:
        print(ch,end="")
Enter a telephone number:982-876-5432
9828765432
#求1+1/2+1/3+1/4+1/5.....1/100的和
sum=0
for i in range(1,101):
    sum+=1/i
print("The sum 1+1/2+1/3+....+1/100 is {0:.5f}".format(sum))
The sum 1+1/2+1/3+....+1/100 is 5.18738
#字典序,接受一个单词,判断它里面的字符是否是按照字典的顺序排序的
str1=input("Enter the word:")
flag=True
for i in range(len(str1)):
    for j in range(i+1,len(str1)):
        if(str1[i]>str1[j]):
            flag=False
            break
if(flag):
    print("Letters are alphabetical order.")
else:
    print("Letters are not alphabetical order.")

    
Enter the word:tang
Letters are not alphabetical order.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值