for else语句小tips : RUNOOB python练习题36

Python中循环题目二的练习(for、while、if) 文章目录一、计算器:二、设计一个程序,完成(英雄)商品的购买(界面就是第一天打印的界面)三、健康计划四、打印如下图案:五、输入数,判断这个数是否是质数六、让用户输入一个月份,判断这个月是哪个季节?假定3到4月是春季,5到8月是夏季,9到10是秋季,11、12、1、2月是冬季七、提示用户输入用户名,然后再提示输入密码,如果用户名是“admin”并且密码是“88888”,则提示正确,否则,如果用户名不是admin还提示用户用户名不存在,如果用户名是admin则提示密码错误。八、有一些四位数,百位数字都是3,十位 阅读详情

用来练手的python练习题,原题链接: python练习实例36

题干: 求100之内的素数

求某个范围内的素数,和之前的一个例题其实是一样的,上次的同类例题链接如下: python练习实例12

在实现题目要求时,这次用了for else语句,发现更加简便,可以省去一部分的条件语句。
源代码如下:

import numpy as np
from math import sqrt
bound = np.arange(2,101,1)
result = np.array([],dtype=int)
for k in bound:
  if k > 1:  
    for i in range(2,int(sqrt(k))+1):
      # 如果k存在不是1或k本身的因数i,则k不是素数
      if k%i == 0:
        break
    else: 
      result = np.append(result, k)
print(result)

输出结果如下:
在这里插入图片描述
if else语句是比较常见的条件语句,但其实for else语句也是非常实用的。下面给出for else语句的基本测试:

第一种情况,在for循环中的条件语句,当条件满足时,break。

for i in range(10):
  if i == 7:
    print("aaa")
    break
else:
  print("okok")

输出结果如下:
在这里插入图片描述
我们发现,当循环中出现了满足条件语句的情况,循环break会直接跳出,且不会执行else语句中的命令。

那么如果循环中的所有情况都不满足条件语句,循环break之后会执行else语句中的命令,如下:

for i in range(10):
  if i == 11:
    print("aaa")
    # 其实这里有没有break是一样的,因为这个条件语句总是false,因此循环语句总是能完全遍历。
    break
else:
  print("okok")

在上述代码中我们知道,循环中的所有情况,都不会满足if条件语句的条件,因此循环跳出后会执行else语句中的print指令,输出结果如下:
在这里插入图片描述
实际我们发现,当循环中不触发break跳出循环,在循环全部完成后,总会执行else中的命令,如下:

for i in range(10):
  print("haohaohao")
else:
  print("okok")

输出结果如下:
在这里插入图片描述
总结: 当我们使用for else 语句时,如果循环完全遍历,没有通过break跳出,那么在循环结束后,就会执行else语句中的命令。反之,如果在循环的过程中,经由break跳出了循环,那么else语句就不会再执行了。因此for else语句非常适合存在性问题,例如在找素数的过程中,如果这个数存在除了1和它本身的因数,则跳出循环,这个数不是素数。反之如果不存在除了1和它本身的因数,那么就调用else语句,这个数是一个素数。

Java基础系列-《流程控制--循环结构》 前言: 张浩Java考试成绩未达到自己的目标。为了表明自己勤奋学习的决心,他决定写一百遍“好好学习,天天向上!”根据前面学习的内容我们知道System.out.println(“好好学习,天天向上!”)可以将这句话打印出来,但是现在是要打印100次,那是不是我们需要写100次呢?答案肯定是否定的,在java中我们要避免写重读的代码,我们要尽量“偷懒”让代码能重复使用。那如何才能写一次输出语句,让它运行100次呢?接下来我们就要学习流程控制中的--循环结构。 一、什么是循环结构 1.循环简单理解就是重读 阅读详情

相关推荐

华为[ENSP]—— 实验二、三层交换和ARP的工作原理

华为[ENSP]三层交换和ARP的工作原理

weixin_62594100的博客 6417

Python中的for,else问题

for循环中else的用法

weixin_61092302的博客 345

告别手动改代码!用SSC工具5分钟搞定EtherCAT从站动态模块配置(含Excel模板)

本文详细介绍了如何利用SSC工具和Excel模板实现EtherCAT从站动态模块配置的自动化流程。通过零代码修改的动态配置方案,大幅提升工业自动化产线的灵活性和效率,配置时间从平均4小时缩短至8分钟,错误率下降96%。文章包含Excel模板设计、实战演示和避坑指南,助力工程师快速掌握这一高效工具。

weixin_28339967的博客 580

for...else:练习

a = int(input("请输入一个数字:")) b = True for i in range(1, 11): if i % a == 0: b = False print(i) break if b==True: #else: print("不存在") #for...else:当循环中有break时,如果没有执行if 则执行...

geloushangdemao的博客 273

ubuntu18.04安装R——无法连接上 dl.google.com:80 (6.6.6.6),连接超时&&E: 无法修正错误,因为您要求某些软件包保持现状,就是它们破坏了软件包间的依赖关系。

安装R的时候,sudo apt update 的时候出现错误: 查资料要修改/etc/apt/sources.list.d/google-chrome.list 文件 原来是: deb http://dl.google.com/linux/chrome/deb/ stable main 改为: deb [arch=amd64] http://dl.google.com/linux/chrom...

许希律的博客 4360

华为云CodeHub保姆级教程:从零开始,5分钟搞定本地代码上传(含常见报错解决)

本文提供华为云CodeHub的保姆级教程,从零开始5分钟完成本地代码上传,涵盖环境准备、仓库创建、远程连接及常见报错解决。特别适合新手开发者快速掌握Git命令与云端协作流程,确保代码安全高效上传。

weixin_30443075的博客 483

while---else/for---else结构

循环中的else结构 while循环中的else结构 例子:打印素数while循环中的else结构 break /continue的用法for循环中的else结构 例子:打印素数 循环可以和else配合使用,else下方缩进的代码指的是 当循环正常结束之后要执行的代码 强调:‘正常结束’,非正常结束,其else中的代码时不会执行的。(如遇到break的情况) while循环中的else结构 例子:打印素数 # 1 请用户输入一个数,使用while计算是否为素数 # 曾称质数。一个大于

LeFran的博客 383

SA8295P芯片:为智能座舱提供高速摄像与显示解决方案

从多个摄像头、高清显示到稳定的视频传输,SA8295P芯片无疑是现代智能汽车座舱的“神经中枢”。通过支持高效的MIPI接口、强大的显示处理能力,这款芯片为车主和乘客提供了更安全、更舒适、更互动的车载体验。

weixin_43199439的博客 614

【Python基础】- for/while循环语句

本文主要介绍了Python中的循环语句,包括for循环和while循环。

m0_64336780的博客 1万+

基于STM32L4XX的环境光传感器(LTR-303ALS-01)应用程序设计

/ 状态寄存器的位[2:0]表示数据状态,例如位2为1表示新数据就绪[citation:6]#define LTR303_REG_DATA_CH0_LOW 0x8D // CH0数据低字节。#define LTR303_REG_DATA_CH0_HIGH 0x8E // CH0数据高字节。#define LTR303_REG_DATA_CH1_LOW 0x8F // CH1数据低字节。#define LTR303_REG_DATA_CH1_HIGH 0x90 // CH1数据高字节。

myron6688的博客 417

innovus:给channel加soft blockage

dbGet [dbGet top.fplan.pBlkgs.name finishfp_place_blkg_* -p].boxes就可以获得channel坐标。意思是给30um以下的channel加soft blk,至于channel的坐标,通过抓取该soft blk去获取,比较容易。工具自己加入的placement blockage命名上叫finishfp_place_blkg_*ICC2中有给channel自动加soft blockage的命令,相应的innovus也有类似的命令,我们可以使用。

m0_61544122的博客 493

蓝桥杯备赛-Two Day-题目练习 for else用法 母牛的故事

这题比较简单, 学到了for 还可以和else一同使用。好像是python才有的错误原因, 是因为公式用错了, 导致只有实例是对的, 到后边就不对了掌握了一种找错误的方法,- 找别人的代码 运行, 和自己代码对比, 就能看出自己的错误。解决问题就变得容易了。

wei_1020的博客 944

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

SQL 注入:Sqli-labs (1-65通关)、sqlmap、注入常用函数

SQL 注入:Sqli-labs (1-65通关)、sqlmap、注入常用函数

freeking101的博客 7635

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

《Python进阶系列》二:Python中的 for-else 语法

长见识!Python中的for-else 语法

一起加油~ 7035

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

python学习:for-else

背景:写求素数时代码时,看到有用到for else 实验一 for i in range(0,10): print(i) if i==3: break else: print("hello") 结果 实验二: for i in range(0,10): print(i) else: print("hello") 结论 如果for循环正常结束,else中语句执行。如果是break的,则不执行 ...

smlie_A的博客 738

学习-Python循环结构之for…else…之寻找水仙花数

第1关:学习-Python循环结构之for…else…之寻找水仙花数 """ 任务:给定一个整数 n,判断 n 以内的正数是否含有水仙花数,n 通过 input 获取; 如果有,输出“有水仙花数”,如果没有,则输出“没有水仙花数”。 """ # 请在下面的Begin-End之间按照注释中给出的提示编写正确的代码 ########## Begin ########## # 使用for-else判断 n 以内的正数是否含有水仙花数 # // " 表示整数除法,返回不大于结果的一个最大的整数 n = in.

weixin_52184490的博客 4373

python中的for循环搭配else

经常会看到for循环和else一起搭配的情形,这不是你的代码缩进不对,而是本身就有这种语法结构。 for i in rane(100): ... else: ... for i in range(n): if s.index(s[i])!=t.index(t[i]): return False else: return True 计算100以内的素数之和: sum=0 for n in range(2,100): for i in range(2,n):

ly17809212771的博客 3530

python中 for...else【详细讲解】

一、语法 for 临时变量 in 序列: 重复执行的代码 ...... else: 循环正常结束后要执行的代码 所谓else指的是循环正常结束后要执行的代码,即如果是bresk终止循环的情况。else下方缩进的代码将不执行。 二、示例 代码如下: str1 = 'Python自学网' for i in str1: print(i) else: print('循环正常结束之后要执行的else的代码') 执行结果: 三、退出循环的方式 下面..

weixin_48728769的博客 5万+

python完整for循环for_else

for num in [1, 2, 3]: print(num) if num == 2: break else: """ 当for循环全部执行完成后,会执行else代码; 如果循环内部使用break打断循环,else代码不会被执行 """ print("会执行吗") print("循环结束") ...

m0_58535137的博客 131

python循环语句while求和1-100_python循环语句(for/while)

一、for循环用于遍历python的容器1.遍历字符串:for i in “abc” 2.遍历列表list:for i in [1,2,3] 3.遍历元组tuple: for i in (1,2,3) 4.遍历字典dict: for i in {"name":"张三","age":20,"sex":"男"} 二、while循环循环重复判断条件,如果为true就执行,如果为false就退出循环idx...

weixin_39605296的博客 3458

第十九if else for 循环题目训练.

Document

qq_43112705的博客 233

python for...else的使用

有时我们需要判断程序是正常退出循环(遍历完成),还是中途退出,据此来进行下面的不同操作。可能会加一个判断,比如下面的代码: a = [1, 2, 3, 4] flag = True for i in range(len(a)): if a[i] == 2: flag = False break if flag: print('yes') else: print('no') 用for...

mrzrx的博客 1223

【Python入门教程】第55篇 循环进阶之for…else语句

for…else 循环语句可以在循环正常完成后执行一段额外的代码。

Tony.Dong的专栏 953

python中for和else的用法_Python循环结构中else用法(入门必读)

Python 的循环都可以定义 else 代码块,当循环条件为 False 时,程序会执行 else 代码块。如下代码示范了为 while 循环定义 else 代码块:count_i = 0 while count_i < 5: print('count_i小于5: ', count_i) count_i += 1 else: print('count_i大...

weixin_39629989的博客 1482

关于if..else..及for循环的简单小练习(一)

作为程序化结构设计语言,C语言的三种语句结构:循环结构,顺序结构,选择结构 就显得尤其的重要。 在简单的学习过循环结构后,我们应该对几种循环语句有了简单的了解和运用了,接下来,我们就做几道简单编程题练习一下。 1、写一个函数返回参数二进制中 1 的个数 比如: 15 0000 1111 4 个 1 程序原型: int coun...

叶梓梓的博客分享 3430
上一篇: RUNOOB python练习题 35 python print各色字体及背景
下一篇: RUNOOB python练习题37 对一个序列的数进行排序
Cy_coding
博客等级 码龄7年 49粉丝 88原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址