Python入门四(条件及循环语句)

4.1 条件判断:if语句

  • Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块。
    • if 判断条件:
    • 执行语句……
    • else:
    • 执行语句……
  • 开始有缩进的概念
# 基本判断语句

age = 12
if age < 18:
    print('18岁以下不宜观看')
# if语句后面必须有 : 
# 自动缩进
# if语句写完后,要退回原有缩进继续写
# Python代码的缩进规则:具有相同缩进的代码被视为代码块

#输出结果
18岁以下不宜观看
# 输入函数 input()

score = input('请输入成绩:')
print('该学生成绩为:' + score)
print(type(score))
# 注意:input()返回结果都为字符串,如果需要变为数字则用到int()/float()

#输出结果
请输入成绩:23
该学生成绩为:23
<class 'str'>
# 两种条件判断:if-else

flag = False
name = 'python'
if name == 'python':          # 判断变量否为'python'
    flag = True               # 条件成立时设置标志为真
    print( 'welcome boss')    # 并输出欢迎信息
else:
    print(name)               # 条件不成立时输出变量名称

#输出结果
welcome boss
# 多种条件判断:if-elif-...-else

num = 5    
if num == 3:            # 判断num的值
    print('boss')       
elif num == 2:
    print('user')
elif num == 1:
    print('worker')
elif num < 0:           # 值小于零时输出
    print('error')
else:
    print('roadman')    # 条件均不成立时输出
    
#输出结果
roadman
# 单语句多条件判断:or and

num = 10
if num >= 0 and num <= 10:    
    print( 'hello')
# 判断值是否在0~10之间
# 输出结果: hello
 
num = 5
if num < 0 or num > 10:    
    print( 'hello')
else:
    print( 'undefine')
# 判断值是否在小于0或大于10
# 输出结果: undefine
 
num = 9
if (num >= 0 and num <= 5) or (num >= 10 and num <= 15):    
    print( 'hello')
else:
    print( 'undefine')
# 判断值是否在0~5或者10~15之间
# 输出结果: undefine

小作业

① 编写一个简单的判断语句代码:输入某个成绩,如果成绩分数大于或等于60分,则返回及格,小于60分,则返回不及格

② 编写猜数字小游戏的代码:输入一个数字,分别针对猜对数字、猜错数字、输入错误给予判断

#①
score = input('请输入成绩:')

if int(score) < 0 or int(score) > 100:
    print("请重新输入成绩")
elif int(score) >= 60 :
    print("及格")
else :
    print("不及格")

#输出结果
请输入成绩:89
及格
#②
num = 100
guessnum = input('请随机输入一个整数:')

if int(guessnum) != num :
    print("猜错数字")
else :
    print("猜对数字")
import random
secret=random.randint(1,100)#生成随机数
#print (secret)
time=6#猜数字的次数
guess=0#输入的数字
minNum=0#最小随机数
maxNum=100#最大随机数
print("---------欢迎来到猜数字的地方,请开始---------")
while guess!=secret and time>=0:#条件
    guess=int(input("*数字区间0-100,请输入你猜的数字:"))
    print("你输入数字是:",guess)
    if guess==secret:
        print("猜对了,真厉害")
    else:
        #当不等于的时候,还需要打印出相应的区间,让用户更容易使用
        if guess<secret:
            minNum=guess
            print("你的猜数小于正确答案")            
            print("现在的数字区间是:",minNum,"-",maxNum)
        else:
            maxNum=guess
            print("你的猜数大于正确答案")
            print("数字区间是:",minNum,"-",maxNum)
        print("太遗憾了,你猜错了,你还有",time,"次机会")
    time-=1

4.2 循环语句:for循环

  • for循环可以遍历任何序列的项目,如一个列表或者一个字符串。
  • for in中in后面跟的是一个列表
    • 通过for遍历序列、映射
    • 嵌套循环
# 想输出"hello world"5次怎么办?
for i in range(5):
    print('hello world!')
    
#输出结果
hello world!
hello world!
hello world!
hello world!
hello world!
# 通过for遍历序列、映射

lst = list(range(10))
for i in lst[::2]:
    print(i)
print('-----')
# 遍历list

age = {'Tom':18, 'Jack':19, 'Alex':17, 'Mary':20}
for name in age:
    print(name + '年龄为:%s岁' % age[name])
# 遍历字典

#输出结果
0
2
4
6
8
-----
Tom年龄为:18岁
Jack年龄为:19岁
Alex年龄为:17岁
Mary年龄为:20
# 嵌套循环

for i in range(3):
    for j in range(2):
        print(i,j)
# 循环套循环,注意:尽量不要多于3个嵌套

#输出结果
0 0
0 1
1 0
1 1
2 0
2 1

小作业

① 生成一个数值列表,用for循环打印出所有元素

② 用for循环遍历一个字符串,打印出各个字母

③ 生成一个字典,分别打印出key和value

④ 用input输入一个循环次数n,打印hello world n遍

⑤ 码一个等差数列,四个变量:首项a,项数n,公差d,求和s,这几个参数都可通过input()输入

⑥ 两组列表[“a”, “b”, “c”],[1,2,3],用for循环把它们组成一个字典,一一对应

#① 生成一个数值列表,用for循环打印出所有元素
lst = list(range(5))
print(lst)

for i in lst:
    print(lst[i])
    
#输出结果
[0, 1, 2, 3, 4]
0
1
2
3
4
#② 用for循环遍历一个字符串,打印出各个字母

str = "ashdq"
print(str[1])
print(type(len(str)))

for i in range(len(str)):
    print(str[i])

#输出结果
s
<class 'int'>
a
s
h
d
q
#③ 生成一个字典,分别打印出key和value

dic = dict([["name","haha"],["age",18],["sex","M"]])
print(dic,type(dic))

#打印key
for key in dic.keys():
    print(key)

#打印value   
for value in dic.values():
    print(value)
 
#输出结果
{'name': 'haha', 'age': 18, 'sex': 'M'} <class 'dict'>
name
age
sex
haha
18
M
# ④ 用input输入一个循环次数n,打印hello world n遍

n = input("请输入循环次数:")

for i in range(int(n)):
    print("hello world")

#输出结果
请输入循环次数:3
hello world
hello world
hello world
#  ⑤ 码一个等差数列,四个变量:首项a,项数n,公差d,求和s,这几个参数都可通过input()输入
a = int(input("请输入首项"))
n = int(input("请输入项数"))
d = int(input("请输入公差"))
s = a+(n-1)*d
print("和为:",s)

#输出结果
请输入首项2
请输入项数3
请输入公差4
和为: 10
#  ⑥ 两组列表["a", "b", "c"],[1,2,3],用for循环把它们组成一个字典,一一对应

lst1 = ["a", "b", "c"]
lst2 = [1,2,3]

dic1 = {}
dic2 = {}
for i in range(3):
    print(lst1[i],lst2[i])
    dic1 = dict([[lst1[i],lst2[i]]])
    dic2.update(dic1)
    dic1 = {}
    print(dic2)
   
#输出结果
a 1
{'a': 1}
b 2
{'a': 1, 'b': 2}
c 3
{'a': 1, 'b': 2, 'c': 3}

4.3 循环语句:while循环

  • 执行语句可以是单个语句或语句块
  • 判断条件可以是任何表达式,任何非零、或非空(null)的值均为true。
  • 当判断条件假false时,循环结束。
# 基本运行逻辑

count = 0
while count < 9:
    print( 'The count is:', count)
    count = count + 1
print( "Good bye!")
# 这里count<9是一个判断语句,当判断为True时,则继续运行

#输出结果
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
# 关于无限循环:如果条件判断语句永远为 true,循环将会无限的执行下去

# var = 1
# while var == 1 :  
#     num = input("Enter a number  :")
#     print( "You entered: ", num)
# print( "Good bye!")

# 该条件永远为true,循环将无限执行下去
# 一定要避免无限循环!!
# while-else语句

count = 0
while count < 5:
    print(count, " is  less than 5")
    count = count + 1
else:
    print(count, " is not less than 5")
# 逻辑和if-else一样

#输出结果
0  is  less than 5
1  is  less than 5
2  is  less than 5
3  is  less than 5
4  is  less than 5
5  is not less than 5

4.4 循环控制语句

  • break:在语句块执行过程中终止循环,并且跳出整个循环
  • continue:在语句块执行过程中跳出该次循环,执行下一次循环
  • pass:pass是空语句,是为了保持程序结构的完整性
# break语句

s = 0
n = 1
while n > 0:
    s = s + n
    n = n + 1
    if n == 20:
        break
print(s)
# break语句用来终止循环语句,即便循环条件没有False条件或者序列还没被完全递归完,也会停止执行循环语句。

s = 0
for i in range(10):
    for j in range(5):
        s = s + (i*j)
        print('第%i次计算' %(i+j))
    if s > 20:
        break
print('结果为%i' % s)
# 如果使用嵌套循环,break语句将停止执行最深层的循环,并开始执行下一行代码。

#输出结果
1900次计算
第1次计算
第2次计算
第3次计算
第4次计算
第1次计算
第2次计算
第3次计算
第4次计算
第5次计算
第2次计算
第3次计算
第4次计算
第5次计算
第6次计算
结果为30
# continue语句

s = 0
for i in range(10):
    if i%2 == 0:
        s += i
    else:
        continue
    print('第%i次计算'%(i/2))
print('结果为%i' % s)
# continue 语句用来告诉Python跳过当前循环的剩余语句,然后继续进行下一轮循环。

#输出结果0次计算
第1次计算
第2次计算
第3次计算
第4次计算
结果为20
# pass语句

for letter in 'Python':
    if letter == 'h':
        pass
        print( '当前字母 : h,但是我pass了')
    print( '当前字母 :', letter)
print( "Good bye!")
# pass是空语句,是为了保持程序结构的完整性。(不中断也不跳过)

#输出结果
当前字母 : P
当前字母 : y
当前字母 : t
当前字母 : h,但是我pass了
当前字母 : h
当前字母 : o
当前字母 : n
Good bye!
  • 6
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值