一、if语句
语法:
if condition:
indented statement(s)
如果条件为真,就执行这些缩进的语句,否则跳过这些语句
例子:
answer = input("Do you want to see a spiral? y/n:")
if answer == 'y':
print("Working...")
import turtle
t = 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 rosette
t.circle(100)
else: # Default to polygon
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))
# 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 spiral
t.forward(m*4) # Move to next corner
t.pendown() # Get ready to draw
# Draw a little rosette at each EVEN corner of the spiral
if (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 spiral
else:
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 warm
print("Carry an umbrella with you.")
elif (rainy != 'y' and cold == 'y'): # Dry, but cold
print("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 message
if 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 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
作业
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