python用for和if结合判断_python基础之流程控制(if判断和while、for循环)

news/2024/7/16 6:52:54

程序执行有三种方式:顺序执行、选择执行、循环执行

一、if条件判断

1、语句

(1)简单的 if 语句

(2)if-else 语句

(3)if-elif-else 结构

(4)使用多个 elif 代码块if-elif-elif-...-else(elif可以使用多个)

(5)省略 else 代码块if-elif-elif(else可以省去)

(6)测试多个条件(简单if语句)

2、注意:

(1)if 语句可以相互嵌套;

(2)if嵌套,可以嵌套多层,但是一般嵌套两层就行了,如果嵌套多层的话不便维护代码,若需要嵌套多层,肯定可以用其它方式代替多层嵌套这种方式。

3、实例1:

#if嵌套用法

names = ["李国祥","任彦忠","毕洪态","张立佳"]

password= 123name= input("请输入您的名字:")if name innames:

passwd= int(input("请输入密码:"))if passwd ==password:print("欢迎光临!")else:print("密码错误,请重新输入!")elif name == "游客":print("欢迎加入!")else:print("请输入正确的用户名!")print("人生苦短,我学python!")

4、实例2:猜年龄

#在程序里设定好你的年龄,然后启动程序让用户猜测,用户输入后,根据他的输入提示用户输入的是否正确,如果错误,提示是猜大了还是小了

my_age = 18

guess_age = int(input("请猜测我的年龄:"))

if guess_age == my_age:

print("恭喜您才对了!奖励大大滴")

elif guess_age <= my_age:

print("猜小了,人家已经成年了")

else:

print("猜大了,我有那么老么?")

外层变量,可以被内层代码使用;

内存变量,不应被外层代码使用。

二、while循环

一般情况下,需要多次重复执行的代码,都可以用循环的方式来完成

循环不是必须要使用的,但是为了提高代码的重复使用率,所以有经验的开发者都会采用循环

实例1:1~100的累加求和

#计算1~100的累计和

i = 1

sum = 0

while i <= 100:

sum = sum + i

i += 1

print("1~100的累积和为:%d"%sum)

实例2:99乘法表

i = 1

while i <= 9:

j = 1

while j <= i:

print("%d*%d=%d\t"%(j,i,i*j),end="")

j +=1

print("")

i +=1

实例3:打印1~100之间的偶数

#输出1-100之间的所有偶数

i = 1

while i <= 100:

if i%2 == 0:

print("i==%d"%i)

i += 1

实例4:猜年龄,只有3次机会

my_age = 18

count = 0

while count < 3:

guess_age = int(input("请猜测我的年龄:"))

if guess_age == my_age:

print("恭喜您才对了!奖励大大滴")

break

elif guess_age < my_age:

print("猜小了,人家已经成年了")

else:

print("猜大了,我有那么老么?")

count += 1

else:

print("猜这么多次都没才对,你个笨蛋")

实例5:

count = 0

while True:

print("你是风儿我是沙,缠缠绵绵到天涯...",count)

count +=1

if count == 100:

print("去你妈的风和沙,你们这些脱了裤子是人,穿上裤子是鬼的臭男人..")

break

三、for循环

像while循环一样,for可以完成循环的功能。

在Python中 for循环可以遍历任何序列的项目,如一个列表、字符串、元组等等。

for循环的格式:

for 临时变量 in 列表或者字符串等:

循环满足条件时执行的代码

else:

循环不满足条件时执行的代码

实例1:遍历

name = "python"

for i in name:

print("----------------------")

print(i)

实例2:continue、break

continue的作用:用来结束本次循环,紧接着执行下一次的循环

break的作用:用来结束整个循环

for i in range(10):if i<5:continue #不往下走了,直接进入下一次loop

print("loop:", i )------------------------------------------------------------------loop:5loop:6loop:7loop:8loop:9

for i in range(10):if i>5:break #不往下走了,直接跳出整个loop

print("loop:", i )------------------------------------------------------------------loop: 0

loop:1loop:2loop:3loop:4loop:5

#pass,continue,break

#continue跳过本次循环进入下一次循环

count = 0

while count <= 5 :

count += 1

if count == 3:

continue

print("Loop", count)

#breck跳出循环体

count = 0

while count <= 5 :

count += 1

if count == 3:

break

print("Loop", count)

# pass用来占位的%s,%d,{}

count = 0

while count <= 5 :

count += 1

if count == 3:

pass

print("Loop", count)

实例3:猜拳游戏

#猜拳游戏

import random

win = 0

lose = 0

ping = 0

while True:

print('=====欢迎来猜拳=====')

print('胜:{} 败:{} 平:{}'.format(win, lose, ping))

print('1.石头 2.剪刀 3.布 4.退出')

computer = random.choice(['石头','剪刀','布'])

hum = input('==>:')

#赢

if (hum == '1' and computer == '剪刀') or (hum == '2' and computer =='布') or (hum == '3' and computer == '石头'):

print('挺牛逼!')

win += 1

#输

elif hum == '3' and computer == '剪刀' or hum == '1' and computer =='布' or hum == '2' and computer == '石头':

print('菜鸡!')

lose += 1

#平

elif hum == '2' and computer == '剪刀' or hum == '3' and computer =='布' or hum == '1' and computer == '石头':

print('不要走,决战到天亮')

ping += 1

elif hum == '4':

break

else:

print('别瞎输入!!')

print()

print()

print()

print()

实例4:用户登录验证

第一种方法:

#输入用户名和密码,认证成功后显示欢迎信息,输错三次后锁定

user_info = {'任彦忠':'123','ryz':'123','renyz':'ryz'}

count=0while count < 3:

user_name= input("请输入您的用户名:").strip()if user_name inuser_info.keys():

twice_count=countwhile twice_count < 3:

pass_word= input("请输入您的密码:").strip()if pass_word ==user_info.get(user_name):print("欢迎登陆")

exit()else:print("密码错误,请重新输入")

twice_count+= 1count=twice_countelse:print('请输入正确的用户名!')

count+= 1

continue

else:print("您已经输错三次了,请稍后重试")

第二种方法:

count = 1 # 定义循环的次数,初始值为1

user = 'test'

pwd = '123'

while True:

# 当循环的次数等于4时,结束循环。count的值经过自加1操作后将会依次走1,2,3这三个数的变化,这就是3次了。

if count == 4:

print('Too many times!') # 当超过3次了,提示用户超过尝试登陆次数过多了。

break

username = input('Please enter your username:').strip() # 去除用户输入时字符串两边的空格

password = input('Please enter your password:').strip() # 去除用户输入的字符串两边的空格

# 如果用户输入的内容有值时进行以下判断

if username or password:

# 当判断用户名和密码都正确时结束循环。

if username == user and password == pwd:

print('Login successfully!')

exit() # 当用户名和密码匹配成功时退出程序

# 当判断用户名或密码不正确时走else下的条件。

else:

print('Login failed,you have %s more chances' % (3 - count))

# 如果用户输入的值为None时,则执行以下打印操作。

else:

print('Please enter your user name and password before landing')

continue # 当用户输入为空时,跳出本次循环,继续执行如下。

# 让每一次循环都进行自加1操作。

count += 1

实例五:多级菜单

#三级菜单,可依次选择进入各子菜单

data ={"北京":{"昌平":{"沙河":{"oldboy","test"},"天通苑":{"链家地产","我爱我家"}

},"朝阳":{"望京":{"奔驰","陌陌"},"国贸":{"CICC","HP"},"东真门":{"Advent","飞信"},

},"海淀":{"运维":{"计算机","IP"},"云计算":{"python","java"},"工程师":{"技术大牛","管理"},

},

},"山东":{"德州":{"1","2"},"青岛":{"3","4"},"济南":{},

},"山西":{"太原":{},"大同":{},"晋中":{},

},

}

exit_flag=Falsewhile notexit_flag:for i indata:print(i)

choice= input("选择进入1>>:")if choice indata:while notexit_flag:for i2 indata[choice]:print("\t",i2)

choice2= input("选择进入2>>:")if choice2 indata[choice]:while notexit_flag:for i3 indata[choice][choice2]:print("\t\t",i3)

choice3= input("选择进入3>>:")if choice3 indata[choice][choice2]:for i4 indata[choice][choice2][choice3]:print("\t\t\t",i4)

choice4= input("最后一层,按b返回>>:")if choice4 == "b":pass

elif choice4 == "q":

exit_flag=Trueif choice3 == "b":break

elif choice3 == "q":

exit_flag=Trueif choice2 == "b":break

elif choice2 == "q":

exit_flag= True


http://www.niftyadmin.cn/n/2419661.html

相关文章

/usr/lib64/libstdc .so.6: version `GLIBCXX_3.4.14‘ not found (required by node)

在linux上安装node环境好了后&#xff0c;想运行node试一下&#xff0c;报错 /usr/lib64/libstdc .so.6: version GLIBCXX_3.4.14’ not found (required by node) 在安装node的时候出现报错&#xff0c;提示/usr/lib64/libstdc.so.6: version GLIBCXX_3.4.14’ not found &am…

散列表查找失败平均查找长度_《算法图解》学习记录5--散列表

散列表&#xff08; hash table&#xff09;  学习散列表——最有用的基本数据结构之一。散列表用途广泛&#xff0c;本章将介绍其常见的用途。 学习散列表的内部机制&#xff1a;实现、冲突和散列函数。这将帮助你理解如何分析散列表的性能。散列表是一种包含额外逻辑的数…

Cannot read properties of undefined (reading ‘extraneous‘) npm install时

项目为了上基线&#xff0c;把本地项目编译之后的node_modules文件和dist文件都删掉了&#xff0c;然后上完基线之后&#xff0c;重新编译本地项目代码&#xff0c;结果初始化项目失败&#xff0c;提示无法读取未定义的“外部”属性&#xff0c;原因就是上一次编译的项目包没有…

新闻管理系统_东莞应急管理代表队在全省应急管理系统篮球友谊赛中勇夺冠军...

11月29日由广东省应急管理厅主办的全省应急管理系统篮球友谊赛决赛在广州越秀区顺利开赛。经过激烈角逐&#xff0c;最终&#xff0c;东莞应急管理代表队以77分获得本次比赛的第一名。省应急管理厅党组书记、厅长王中丙&#xff0c;党组成员、副厅长高涌涛观摩了此次比赛并分别…

linux上安装mongodb(详解)

1.cd …/ cd usr/ 从网页上直接下载mongodb压缩包 wget http://fastdl.mongodb.org/linux/mongodb-linux-i686-1.8.1.tgz如果下载以后是这样的&#xff0c;把&#xff1f;后面的删掉就可以了 2.解压压缩包 tar zxvf mongodb-linux-i686-1.8.1.tgz3.创建mongod文件夹及其子文…

js 获取浏览器定位_前端基础夯实之浏览器相关

V8引擎机制V8如何执行一段JS代码预解析检查语法错误但不生成AST生成AST经过词法/语法分析&#xff0c;生成抽象语法树生成字节码基线编译器(Ignition)将AST转换成字节码生成机器码优化编译器(Turbofan)将字节码转换成优化过的机器码&#xff0c;此外在逐行执行字节码的过程中&a…

react项目打包css引用路径错误

使用create-react-app所创建的react项目在build打包之后出现静态资源引用路径有误问题。 解决&#xff1a; 在package.json下面增加"homepage": "."

图的字典表示python_[宜配屋]听图阁

Python字典是另一种可变容器模型&#xff0c;且可存储任意类型对象&#xff0c;如字符串、数字、元组等其他容器模型。一、创建字典字典由键和对应值成对组成。字典也被称作关联数组或哈希表。基本语法如下&#xff1a;dict {Alice: 2341, Beth: 9102, Cecil: 3258}也可如此创…