一、if语句

语法:

if condition:

indented statement(s)

如果条件为真,就执行这些缩进的语句,否则跳过这些语句

例子:

answer = input("Do you want to see a spiral? y/n:")
if answer == 'y':print("Working...")import turtlet = turtle.Pen()t.width(2)for x in range(100):t.forward(x*2)t.left(89)
print("Okay, we're done!")

如果你输入”y“,就绘制出螺旋线,否则直接输出”Okay, we're done!“

二、布尔表达式和布尔值

布尔表达式,或者说条件表达式,结果为布尔值,要么True,要么False,首字母都要大写。

语法:expression1 conditional_operator expression2

2.1.比较操作符

运算符 描述 实例
== 等于 - 比较对象是否相等 (a == b) 返回 False。
!= 不等于 - 比较两个对象是否不相等 (a != b) 返回 True。
> 大于 - 返回x是否大于y (a > b) 返回 False。
< 小于 - 返回x是否小于y。所有比较运算符返回1表示真,返回0表示假。这分别与特殊的变量True和False等价。注意,这些变量名的大写。 (a < b) 返回 True。
>= 大于等于 - 返回x是否大于等于y。 (a >= b) 返回 False。
<= 小于等于 - 返回x是否小于等于y。 (a <= b) 返回 True。

2.2.你还不够大

# OldEnough.py
driving_age = eval(input("What is the legal driving age where you live? "))
your_age = eval(input("How old are you? "))
if your_age >= driving_age:print("You're old enough to drive!")
if your_age < driving_age:print("Sorry, you can drive in", driving_age - your_age, "years.")

第一个条件表达式的结果知道后,第二个条件表达式的结果肯定也知道了,不需要再次计算,所以最后的if可以用else代替,显得更加简洁。

三、else语句

语法:

if condition:

indented statement(s)

else:

other indented statement(s)

如果条件表达式为True,那么执行缩进的语句,否则执行其他缩进的语句

修改上例:

# OldEnoughOrElse.py
driving_age = eval(input("What is the legal driving age where you live? "))
your_age = eval(input("How old are you? "))
if your_age >= driving_age:print("You're old enough to drive!")
else:print("Sorry, you can drive in", driving_age - your_age, "years.")

3.1.多边形或玫瑰花瓣

# PolygonOrRosette.py
import turtle
t = turtle.Pen()
# Ask the user for the number of sides or circles, default to 6
number = int(turtle.numinput("Number of sides or circles","How many sides or circles in your shape?", 6))
# Ask the user whether they want a polygon or rosette
shape = turtle.textinput("Which shape do you want?","Enter 'p' for polygon or 'r' for rosette:")
for x in range(number):if shape == 'r':        # User selected rosettet.circle(100)else:                   # Default to polygont.forward (150)t.left(360/number)

3.2.偶数还是奇数

# RosettesAndPolygons.py - a spiral of polygons AND rosettes!
import turtle
t = turtle.Pen()
# Ask the user for the number of sides, default to 4
sides = int(turtle.numinput("Number of sides","How many sides in your spiral?", 4))
# Our outer spiral loop for polygons and rosettes, from size 5 to 75
for m in range(5,75):   t.left(360/sides + 5)t.width(m//25+1)t.penup()        # Don't draw lines on spiralt.forward(m*4)   # Move to next cornert.pendown()      # Get ready to draw# Draw a little rosette at each EVEN corner of the spiralif (m % 2 == 0):for n in range(sides):t.circle(m/3)t.right(360/sides)# OR, draw a little polygon at each ODD corner of the spiralelse:for n in range(sides):t.forward(m)t.right(360/sides)

四、elif语句

# WhatsMyGrade.py
grade = eval(input("Enter your number grade (0-100): "))
if grade >= 90:print("You got an A! :) ")
elif grade >= 80:print("You got a B!")
elif grade >= 70:print("You got a C.")
elif grade >= 60:print("You got a D...")
else:print("You got an F. :( ")

五、复杂条件-------if、and、or和not

以下假设变量 a 为 10, b为 20:

运算符 逻辑表达式 描述 实例
and x and y 布尔"与" - 如果 x 为 False,x and y 返回 x 的值,否则返回 y 的计算值。 (a and b) 返回 20。
or x or y 布尔"或" - 如果 x 是 True,它返回 x 的值,否则它返回 y 的计算值。 (a or b) 返回 10。
not not x 布尔"非" - 如果 x 为 True,返回 False 。如果 x 为 False,它返回 True。 not(a and b) 返回 False
# WhatToWear.py
rainy = input("How's the weather? Is it raining? (y/n)").lower()
cold = input("Is it cold outside? (y/n)").lower()
if (rainy == 'y' and cold == 'y'):      # Rainy and cold, yuck!print("You'd better wear a raincoat.")
elif (rainy == 'y' and cold != 'y'):    # Rainy, but warmprint("Carry an umbrella with you.")
elif (rainy != 'y' and cold == 'y'):    # Dry, but coldprint("Put on a jacket, it's cold out!")
elif (rainy != 'y' and cold != 'y'):    # Warm and sunny, yay!print("Wear whatever you want, it's beautiful outside!")

六、秘密消息

对称式加密,即加密和解密的密钥是相同的

message = input("Enter a message to encode or decode: ") # Get a message
message = message.upper()           # Make it all UPPERCASE :)
output = ""                         # Create an empty string to hold output
for letter in message:              # Loop through each letter of the messageif letter.isupper():            # If the letter is in the alphabet (A-Z),value = ord(letter) + 13    # shift the letter value up by 13,letter = chr(value)         # turn the value back into a letter,if not letter.isupper():    # and check to see if we shifted too farvalue -= 26             # If we did, wrap it back around Z->Aletter = chr(value)     # by subtracting 26 from the letter valueoutput += letter                # Add the letter to our output string
print("Output message: ", output)   # Output our coded/decoded message

作业

1.彩色玫瑰花瓣和螺旋线

修改# RosettesAndPolygons.py,达到如下效果:

# RosettesAndSpirals.py - a spiral of shapes AND rosettes!
import turtle
t=turtle.Pen()
t.penup()
t.speed(0)
turtle.bgcolor('black')
# Ask the user for the number of sides, default to 4, min 2, max 6
sides = int(turtle.numinput("Number of sides","How many sides in your spiral?", 4,2,6))
colors=['red', 'yellow', 'blue', 'green', 'purple', 'orange']
# Our outer spiral loop
for m in range(1,60):t.forward(m*4)t.width(m//25+1)position = t.position() # remember this corner of the spiralheading = t.heading()   # remember the direction we were heading# Our 'inner' spiral loop,# draws a little rosette at each corner of the big spiralif (m % 2 == 0):for n in range(sides):t.pendown()t.pencolor(colors[n%sides])t.circle(m/4)t.right(360/sides - 2)t.penup()# OR, draws a little spiral at each corner of the big spiralelse:for n in range(3,m):t.pendown()t.pencolor(colors[n%sides])t.forward(n)t.right(360/sides - 2)t.penup()t.setx(position[0])     # go back to the big spiral's x locationt.sety(position[1])     # go back to the big spiral's y locationt.setheading(heading)   # point in the big spirals direction/headingt.left(360/sides + 4)   # move to the next point on the big spiral

2.用户定义的密钥

修改EncoderDecoder.py,允许用户输入他们自己的密钥值,从1到25,例如:5,那么加密时密钥为5,解密时用相反的密钥21(26-5=21)。

message = input("Enter a message to encode or decode: ") # get a message
key = eval(input("Enter a key value from 1-25: ")) # get a key
message = message.upper()           # make it all UPPERCASE :)
output = ""                         # create an empty string to hold output
for letter in message:              # loop through each letter of the messageif letter.isupper():            # if the letter is in the alphabet (A-Z)value = ord(letter) + key   # shift the letter value up by keyletter = chr(value)         # turn the value back into a letterif not letter.isupper():    # check to see if we shifted too farvalue -= 26             # if we did, wrap it back around Z->Aletter = chr(value)     # by subtracting 26 from the letter valueoutput += letter                # add the letter to our output string
print ("Output message: ", output)  # output our coded/decoded message

5-条件(如果是这样该怎么办?)相关推荐

  1. C++ 笔记(32)— 预处理、文件包含include、宏替换define、条件包含ifndef、define

    C/C++预处理器在源代码编译之前对其进行一些文本性质的操作. 它的主要任务包括删除注释 . 插入 #include 指令包含的文件的内容 . 定义和替换由 #defme 指令定义的符号以及确定代码的 ...

  2. Go 知识点(11) — goroutine 泄露、设置子协程退出条件

    1. 问题现象 如果在开发过程中不考虑 goroutine 在什么时候能退出和控制 goroutine 生命期,就会造成 goroutine 失控或者泄露的情况 ,看示例代码: func consum ...

  3. NLP --- 条件随机场CRF详解 重点 特征函数 转移矩阵

    20210517 http://www.tensorinfinity.com/paper_170.html 上一节我们介绍了CRF的背景,本节开始进入CRF的正式的定义,简单来说条件随机场就是定义在隐 ...

  4. 【机器学习】【条件随机场CRF-3】条件随机场的参数化形式详解 + 画出对应的状态路径图 + 给出对应的矩阵表示...

    1.条件随机场概念 CRF,Conditional Random Field,是给定一组输入随机变量条件下另一组输出随机变量的条件概率分布模式,其特点是假设输出随机变量构成马尔可夫随机场. 条件随机场 ...

  5. 条件随机场(CRF) - 4 - 学习方法和预测算法(维特比算法)

    声明: 1,本篇为个人对<2012.李航.统计学习方法.pdf>的学习总结,不得用作商用,欢迎转载,但请注明出处(即:本帖地址). 2,由于本人在学习初始时有很多数学知识都已忘记,所以为了 ...

  6. CRF(条件随机场)与Viterbi(维特比)算法原理详解

    摘自:https://mp.weixin.qq.com/s/GXbFxlExDtjtQe-OPwfokA https://www.cnblogs.com/zhibei/p/9391014.html C ...

  7. 条件随机场(CRF) - 1 - 简介

    声明: 1,本篇为个人对<2012.李航.统计学习方法.pdf>的学习总结,不得用作商用,欢迎转载,但请注明出处(即:本帖地址). 2,由于本人在学习初始时有很多数学知识都已忘记,所以为了 ...

  8. 条件随机场(CRF) - 2 - 定义和形式

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/xueyingxue001/article/details/51498968 声明: 1,本篇为个人对 ...

  9. 分层条件关系网络在视频问答VideoQA中的应用:CVPR2020论文解析

    分层条件关系网络在视频问答VideoQA中的应用:CVPR2020论文解析 Hierarchical Conditional Relation Networks for Video Question ...

  10. 2021年大数据Hive(五):Hive的内置函数(数学、字符串、日期、条件、转换、行转列)

    全网最详细的Hive文章系列,强烈建议收藏加关注! 后面更新文章都会列出历史文章目录,帮助大家回顾知识重点. 目录 系列历史文章 前言 Hive的内置函数 一.数学函数 1. 取整函数: round ...

最新文章

  1. 2022-2028年中国养老保险行业深度调研及投资前景预测报告
  2. Redis概述和基础
  3. Gradient Descent和Back propagation在做什么?
  4. 全领域涨点 | Evolving Attention在CV与NLP领域全面涨点
  5. 这个冬天,将是共享单车最艰难的时刻
  6. 实例使用pyhanlp创建中文词云
  7. html5可以用flash,HTML5网页可以直接看视频,不用flash吗,另外WP7为何不支持flash。。。HTML5网页...
  8. 【英语学习】【Level 07】U03 Amazing wonders L1 My hometown
  9. vue图片滚动抽奖_Vue项目开发-仿蘑菇街电商APP
  10. python list中分段_python将list中的元素拼接为一个str
  11. 如何防止softmax函数上溢出(overflow)和下溢出(underflow)
  12. php缓存技术基础知识
  13. 2017.8.12在线笔试编程真题总结
  14. opencv-python库的安装
  15. 线性变换与矩阵的一一映射
  16. linux alsa工具,浅析alsa-utils工具aplay, mplayer
  17. Stata:回归结果中不报告行业虚拟变量的系数
  18. 巧用Excel笔画排序,实现计算汉字笔画数
  19. 戒浮戒躁!一个“假程序员”的心里话
  20. AI:人工智能技术层企业简介(更新中)

热门文章

  1. maven build后Downloading maven-metadata.xml
  2. 【ElasticSearch】Es 源码之 GatewayMetaState 源码解读
  3. 【Java】Java调用shell脚本
  4. 【Spark】大数据+AI mettup【视频笔记】
  5. Maven : maven工程libraries没有maven dependencies
  6. Linux : DHCP 服务
  7. 【Antlr】unknown attribute text for rule stat in $stat.text
  8. linux下Zlib的安装与使用
  9. Eclipse报错:this compilation unit is not on the build path of a java project
  10. extjs 月份选择控件_Ext DateField控件 - 只选择年月