本站消息

站长简介/公众号


站长简介:高级工程师,爱好交友,无偿辅导python和前端,技术交流,面试指导,找工作指导,瞎聊都可加我微信i88811i哈,欢迎欢迎!也欢迎加入程序员交流群,专属程序员的圈子,加我微信拉你进群.欢迎关注我的微信公众号:程序员总部,程序员的家,探索程序员的人生之路!分享IT最新技术,关注行业最新动向,让你永不落伍。了解同行们的工资,生活工作中的酸甜苦辣,谋求程序员的最终出路!

  价值13000svip视频教程,python大神匠心打造,零基础python开发工程师视频教程全套,基础+进阶+项目实战,包含课件和源码

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

python - 打印else语句而不是if而不是重复while语句

发布于2022-01-18 09:37     阅读(386)     评论(0)     点赞(28)     收藏(5)



我正在编写一个程序来查找 1 到 10 之间的数字的倍数。代码当前跳过 if 语句并立即执行 else 语句,即使输入了“接受”值也是错误消息。我还需要它重复倍数,直到它达到 100 或更高,然后它应该停止。我尝试围绕 ands 和 ors 进行更改,但没有成功,然后再次交换 if 和 while 语句,但没有成功。该程序如下所示:

check3 = False
num = int(input("Enter a number between 1 and 10: "))
if num <= 10 or num >= 1:
    while not num <= 100:
       num += num
       print(num)
    
    else:
        print("Not in range. Try again.")

解决方案


就像很多人评论的那样,有几个问题。
我将引导您完成它们,然后提供一个带注释的工作示例。

代码演练

check3 = False
num = int(input("Enter a number between 1 and 10: "))
# This condition can be rewritten without or/and to make it simpler to understand
# Check example below.
# (Also, if you were to write it like this, 
#   then the if would execute if either condition is true. 
#   Meaning it would execute if num is -50 because -50 <= 10.)
if num <= 10 or num >= 1:
    # This while will run when NOT (number less than 100)
    # So the while will only run when number is greater than 100
    # You want the opposite of this actually
    while not num <= 100:
        # If you keep adding num to itself you will not get the multiples
        # Example: num = 10
        # round 1: num = 10+10 (num is now 20)
        # round 2: num = 20+20 (num is now 40)
        # etc
        num += num
        print(num)
    # This else is indented at the same level as the while...
    # So it will actually trigger when the condition is false.
    else:
        print("Not in range. Try again.")

所以基本上当你运行你的代码时发生的事情是,由于 num 小于 100,while 将不会运行并且执行将跳转到 else。

工作示例

num = int(input("Enter a number between 1 and 10: "))
if 1 <= num <= 10:

    # it's better to set another variable because if you keep doing num+=num
    # for num = 10 you will get num = 10+10 on the first loop (so num is 20 now)
    # num = 20 + 20 on the second loop, etc...
    multiples = 0
    while not multiples >= 100:
        multiples += num
        print(multiples)

# the else needs to be indented at the same level as the if
else:
    print("Not in range. Try again.")

关于布尔逻辑的结束注释:

OR如果其中一个为真或两者都为真,则A B 为真。
只有当两者都为真时, A ANDB 才为真。

站长简介:高级工程师,爱好交友,无偿辅导python和前端,技术交流,面试指导,找工作指导,瞎聊都可加我微信i88811i哈,欢迎欢迎!也欢迎加入程序员交流群,专属程序员的圈子,加我微信拉你进群
欢迎关注我的公众号:程序员总部,关注公众号回复python,免费领取 全套python视频教程,关注公众号回复充值+你的账号,免费为您充值1000积分







所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:https://www.pythonheidong.com/blog/article/1256395/5ccc0fb287ea1add25e5/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

28 0
收藏该文
已收藏

评论内容:(最多支持255个字符)