python代码结构(第四章)

2024-06-23 16:58
文章标签 python 第四章 代码 结构

本文主要是介绍python代码结构(第四章),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

第四章:代码结构
1.使用if、elif和else进行比较
disaster = True
if disaster:
print("woe!")
else:
print("whee!")
输出:
woe!

furry = True
small = True
if furry:
if small:
print("it's a cat")
else:
print("it's a beer")
else:
if small:
print("it;s a skink")
else:
print("it's a human.or a hairless bear")
输出:
it's a cat

color = "puce"
if color == "red":
print("it;s a tomato")
elif color == "green":
print("it's a green pepper")
elif color == "bee purple":
print("i don't know what it is,but only bees can see it")
else:
print("I;ve never heard of the color",color)
输出:
I;ve never heard of the color puce

some_list = []
if some_list:
print("There's something in here")
else:
print("Hey,it's empty")
输出:
Hey,it's empty



2.使用while进行循环
使用if、elif和else条件判断的列子是自顶向下执行的,但是有时候我们需要重复一些操作-循环,
python最简单的操作是while
count = 1        #首先将变量count赋值为1 
while count <= 5:            #while循环比较count的值和5的大小关系,如果count小于等于5的话继续执行
print(count)
count += 1
输出:
1
2
3
4
5


3.使用break跳出循环
如果想让循环在某一条件停止,但是不确定有哪次循环跳出,可以在无限循环中声明break语句
我们通过python的input()函数从键盘输入一行字符串,然后将字符串首字母转换成大写输出,当输入的一行仅含有字符q时,跳出循环
while True:
stuff = input("string to capitalize[type q to quit]:")
if stuff =="q":
break
print(stuff.capitaliz())
输出:
string to capitalize[type q to quit]:test
Test
string to capitalize[type q to quit]:hey,it work
Hey,it work
string to capitalize[type q to quit]:q
integer,please[q to quit]:



4.使用continue跳到循环开始
有时我们并不想结束整个循环,仅仅想跳到下一轮循环的开始。下面是编造的列子:
读入一个整数,如果它是奇数则读出它的平方数,如果是奇数则输出它的平方数,如果是偶数则跳过,同样使用q结束循环
while True:
value = input("integer,please[q to quit]:")
if value == "q":                   #如果是q则停止,跳出循环
break
    number = int(value)
    if number % 2== 0:                    #如果是偶数就跳到循环的最开始,如果是奇数就输出平方和
        continue
    print(number,"squared is",number*number)
输出:
integer,please[q to quit]:1
1 squared is 1
integer,please[q to quit]:2
integer,please[q to quit]:3
3 squared is 9
integer,please[q to quit]:q


Process finished with exit code 0


5.循环外使用else
如果while循环正常结束(没有使用break跳出),程序将进入到可选的else段,当你使用循环来遍历检查某一数据结构时,找到满足条件的解使用break跳出;
循环结束,即没有找打可行解时,将执行else部分代码
numbers = [1,3,5]     #将1,3,5赋值给numbers
position = 0          #起始的position是0
#print(numbers[position])
while position < len(numbers):     #当position小于numbers的长度时,执行循环语句
number = numbers[position]     #将numbers[0]=1最开始,赋值给number,
#print(numbers[position])
if number % 2== 0:              #number除以2余数为1,因此不输出,而是继续执行
print('found even number',number)
        break
position += 1                    #positon=position+1,此时position=0+1=1,然后又返回循环的最开始,执行while循环,直到执行到position < len(position)不成立为止
#print(position)
else:
print('no even number found')     #当position >= len(position)时,输出
输出:
no even number found


6.使用for迭代
rabbits = ['flopsy','mopsy','cottontail','peter']
current = 0
while current < len(rabbits):
print(rabbits[current])
current += 1
输出:
flopsy
mopsy
cottontail
peter

for rabbit in rabbits:
print(rabbit)
输出:
flopsy
mopsy
cottontail
peter

列表(列如rabbits)、字符串、元组、字典、集合等都是python可迭代的对象,元组或列表在一次迭代过程产生一项,而字符串迭代会产生一个字符,如下所示:
word = 'cat'
for letter in word:
print(letter)
输出:
c
a
t

对一个字典(或字典的keys()函数)进行迭代将返回字典的键,在下面的列子中,字典的键为图版游戏的牌的类型
accusation = {'room':'ballroom','weapon':'lead pipe',
              'person':'col.mustard'}
for card in accusation:  #或者是for card in accusation.key() ,将返回字典的键
print(card)
输出:
room
person
weapon

for value in accusation.values():
    print(value)    #对字典的值进行迭代。可以使用字典的value()函数,返回字典的值
输出:
ballroom
col.mustard
lead pipe

for item in accusation.items():
    print(item)      #以元组的形式返回键值对,可以使用字典的items()函数
输出:
('room', 'ballroom')
('person', 'col.mustard')
('weapon', 'lead pipe')

for card,contents in accusation.items():
    print('card', card, 'has the contents', contents)  
输出:            #元组只能被初始化一次,它的值是不能改变的,对于调用函数items()返回的每一个元组,将第一个返回值(键)赋给card,第二个返回值赋给contents
card room has the contents ballroom
card person has the contents col.mustard
card weapon has the contents lead pipe




7.循环外使用else
cheeses = []
for cheese in cheeses:  #如果cheese出现在cheeses打印出cheese
print('this shop has some lvely',cheese)
break      #并跳出循环
else:  #没有break表示没有找到奶酪,cheeses中不存在cheese则执行else
print('this is not much of a cheese shop,is it?')
输出:
this is not much of a cheese shop,is it?






















这篇关于python代码结构(第四章)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1087738

相关文章

uniapp接入微信小程序原生代码配置方案(优化版)

uniapp项目需要把微信小程序原生语法的功能代码嵌套过来,无需把原生代码转换为uniapp,可以配置拷贝的方式集成过来 1、拷贝代码包到src目录 2、vue.config.js中配置原生代码包直接拷贝到编译目录中 3、pages.json中配置分包目录,原生入口组件的路径 4、manifest.json中配置分包,使用原生组件 5、需要把原生代码包里的页面修改成组件的方

公共筛选组件(二次封装antd)支持代码提示

如果项目是基于antd组件库为基础搭建,可使用此公共筛选组件 使用到的库 npm i antdnpm i lodash-esnpm i @types/lodash-es -D /components/CommonSearch index.tsx import React from 'react';import { Button, Card, Form } from 'antd'

17.用300行代码手写初体验Spring V1.0版本

1.1.课程目标 1、了解看源码最有效的方式,先猜测后验证,不要一开始就去调试代码。 2、浓缩就是精华,用 300行最简洁的代码 提炼Spring的基本设计思想。 3、掌握Spring框架的基本脉络。 1.2.内容定位 1、 具有1年以上的SpringMVC使用经验。 2、 希望深入了解Spring源码的人群,对 Spring有一个整体的宏观感受。 3、 全程手写实现SpringM

Python 字符串占位

在Python中,可以使用字符串的格式化方法来实现字符串的占位。常见的方法有百分号操作符 % 以及 str.format() 方法 百分号操作符 % name = "张三"age = 20message = "我叫%s,今年%d岁。" % (name, age)print(message) # 我叫张三,今年20岁。 str.format() 方法 name = "张三"age

代码随想录算法训练营:12/60

非科班学习算法day12 | LeetCode150:逆波兰表达式 ,Leetcode239: 滑动窗口最大值  目录 介绍 一、基础概念补充: 1.c++字符串转为数字 1. std::stoi, std::stol, std::stoll, std::stoul, std::stoull(最常用) 2. std::stringstream 3. std::atoi, std

记录AS混淆代码模板

开启混淆得先在build.gradle文件中把 minifyEnabled false改成true,以及shrinkResources true//去除无用的resource文件 这些是写在proguard-rules.pro文件内的 指定代码的压缩级别 -optimizationpasses 5 包明不混合大小写 -dontusemixedcaseclassnames 不去忽略非公共

一道经典Python程序样例带你飞速掌握Python的字典和列表

Python中的列表(list)和字典(dict)是两种常用的数据结构,它们在数据组织和存储方面有很大的不同。 列表(List) 列表是Python中的一种有序集合,可以随时添加和删除其中的元素。列表中的元素可以是任何数据类型,包括数字、字符串、其他列表等。列表使用方括号[]表示,元素之间用逗号,分隔。 定义和使用 # 定义一个列表 fruits = ['apple', 'banana

Python应用开发——30天学习Streamlit Python包进行APP的构建(9)

st.area_chart 显示区域图。 这是围绕 st.altair_chart 的语法糖。主要区别在于该命令使用数据自身的列和指数来计算图表的 Altair 规格。因此,在许多 "只需绘制此图 "的情况下,该命令更易于使用,但可定制性较差。 如果 st.area_chart 无法正确猜测数据规格,请尝试使用 st.altair_chart 指定所需的图表。 Function signa

麻了!一觉醒来,代码全挂了。。

作为⼀名程序员,相信大家平时都有代码托管的需求。 相信有不少同学或者团队都习惯把自己的代码托管到GitHub平台上。 但是GitHub大家知道,经常在访问速度这方面并不是很快,有时候因为网络问题甚至根本连网站都打不开了,所以导致使用体验并不友好。 经常一觉醒来,居然发现我竟然看不到我自己上传的代码了。。 那在国内,除了GitHub,另外还有一个比较常用的Gitee平台也可以用于

python实现最简单循环神经网络(RNNs)

Recurrent Neural Networks(RNNs) 的模型: 上图中红色部分是输入向量。文本、单词、数据都是输入,在网络里都以向量的形式进行表示。 绿色部分是隐藏向量。是加工处理过程。 蓝色部分是输出向量。 python代码表示如下: rnn = RNN()y = rnn.step(x) # x为输入向量,y为输出向量 RNNs神经网络由神经元组成, python