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

一、if语句

语法:

  if 条件表达式:
      缩进的语句

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

例子:

answer = input("你想看看螺旋线吗? y/n:")
if answer == 'y':
    print("正在绘制中。。。")
    import turtle
    t = turtle.Pen()
    t.width(2)
    for x in range(100):
        t.forward(x*2)
        t.left(89)
    print("好了,我们制作完成了!")
print("程序已经退出了!")

如果你输入”y“,就绘制出螺旋线,否则直接输出”程序已经退出了!“

二、布尔表达式和布尔值

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

语法:表达式1 条件操作符 表达式2

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("你所在地区,几岁可以考驾照? "))
your_age = eval(input("你几岁了? "))
if your_age >= driving_age:
    print("你可以考驾照了!")
if your_age < driving_age:
    print("对不起,你需要在", driving_age - your_age, "年后考驾照.")

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

三、else语句

语法:

if 条件表达式:

    缩进的语句

else:

    其他缩进的语句

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

修改上例:

# OldEnough.py
driving_age = eval(input("你所在地区,几岁可以考驾照? "))
your_age = eval(input("你几岁了? "))
if your_age >= driving_age:
    print("你可以考驾照了!")
else:
    print("对不起,你需要在", driving_age - your_age, "年后考驾照.")

3.1.多边形或玫瑰花瓣

# PolygonOrRosette.py
import turtle
t = turtle.Pen()
# 要求用户输入边或者圆的数量,默认是6
number = int(turtle.numinput("边或者圆的数量",
             "在你的图形中有几条边或者几个圆?", 6))
# 询问用户是想画多边形还是花瓣
shape = turtle.textinput("你想画什么样的图形?",
                         "输入 'p' 画多边形 或者 'r' 画花瓣:")
for x in range(number):
    if shape == 'r':        # 用户选择画花瓣
        t.circle(100)
    else:                   # 默认画多边形
        t.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))
# 外部的螺旋循环从 5 到 75,共循环70次
for m in range(5,75):   
    t.left(360/sides + 5)
    t.width(m//25+1)
    t.penup()        # 外部循环不画线
    t.forward(m*4)   # 移到内部循环的下一个起始点
    t.pendown()      # 准备画内部循环制作的图形
    # 外部循环变量是偶数时画花瓣
    if (m % 2 == 0):
        for n in range(sides):
            t.circle(m/3)
            t.right(360/sides)
    # 否则画多边形
    else:
        for n in range(sides):
            t.forward(m)
            t.right(360/sides)

四、elif语句

# WhatsMyGrade.py
grade = eval(input("输入你的分数 (0-100): "))
if grade >= 90:
    print("你的成绩为 A! :) ")
elif grade >= 80:
    print("你的成绩为 B!")
elif grade >= 70:
    print("你的成绩为 C.")
elif grade >= 60:
    print("你的成绩为 D...")
else:
    print("你的成绩为 F. :( ")

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

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

运算符逻辑表达式描述实例
andx and y布尔"与" - 如果 x 为 False,x and y 返回 x 的值,否则返回 y 的计算值。(a and b) 返回 20。
orx or y布尔"或" - 如果 x 是 True,它返回 x 的值,否则它返回 y 的计算值。(a or b) 返回 10。
notnot x布尔"非" - 如果 x 为 True,返回 False 。如果 x 为 False,它返回 True。not(a and b) 返回 False
# WhatToWear.py
rainy = input("天气怎么样? 在下雨吗? (y/n)").lower()
cold = input("外面冷吗? (y/n)").lower()
if (rainy == 'y' and cold == 'y'):      # Rainy and cold, yuck!
    print("你最好穿件雨衣.")
elif (rainy == 'y' and cold != 'y'):    # Rainy, but warm
    print("那就带把伞吧.")
elif (rainy != 'y' and cold == 'y'):    # Dry, but cold
    print("外面冷,穿件夹克吧!")
elif (rainy != 'y' and cold != 'y'):    # Warm and sunny, yay!
    print("随便穿, 外面天气很好!")

六、秘密消息

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

message = input("输入一条消息,下面的程序会对它编码或者解码: ") # Get a message
message = message.upper()           # 把消息改成大写形式 :)
output = ""                         # 创建一个空字符串用于保存输出
for letter in message:              # 遍历消息的每个字符
    if letter.isupper():            # 如果字符在 (A-Z)范围内,
        value = ord(letter) + 13    # 字符的Unicode码值加13,
        letter = chr(value)         # 把码值转换为字符,
        if not letter.isupper():    # 假如字符超出了大写字符范围
            value -= 26             # 减少字符的码值,使其从 Z->A回来
            letter = chr(value)     # 
    output += letter                # 保存加密后的字符
print("Output message: ", output)   # 输出加密后的消息

作业

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 spiral
    heading = t.heading()   # remember the direction we were heading
    # Our 'inner' spiral loop,
    # draws a little rosette at each corner of the big spiral
    if (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 spiral
    else:
        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 location
    t.sety(position[1])     # go back to the big spiral's y location
    t.setheading(heading)   # point in the big spirals direction/heading
    t.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 message
    if letter.isupper():            # if the letter is in the alphabet (A-Z)
        value = ord(letter) + key   # shift the letter value up by key
        letter = chr(value)         # turn the value back into a letter
        if not letter.isupper():    # check to see if we shifted too far
            value -= 26             # if we did, wrap it back around Z->A
            letter = chr(value)     # by subtracting 26 from the letter value
    output += letter                # add the letter to our output string
print ("Output message: ", output)  # output our coded/decoded message

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值