Python 04

一. 测试题

  1. 请问一下代码会打印多少次“I love you”
while 'C':
    print("I love you")

死循环,会一直打印,因为while后面的条件永远为真
不妨试试如下程序:

while '':
    print('looping')
print('out')
while False:
    print('looping')
print('out')
while 0:
    print('looping')
print('out')
  1. 请问一下代码会打印多少次“I love you”
i = 10
while i:
    print("I love you")
    i = i - 1
#所以i = 0的时候程序就会停止

会打印十次

  1. python3中,一个语句可以分成多行书写吗?
#可以用反斜杠或者括号分解
>>> 3 > 4 and \
  1 < 2
False
>>> ( 3 > 4 and
  1 < 2)
False

二. 动动手

  1. 实现图中功能


    Python 04_第1张图片
#个人代码
num = int(input("Please input a number:"))
while num > 0:
    print(' ' * (num - 1) + '*' * num)
    num = num -1
#参考代码
temp = input("Please input a number:")
number = int(temp)
while number:
    i = number - 1
    while i:
        print(' ', end = '')
        i = i - 1
    j = number
    while j:
        print('*', end = '')
        j = j - 1
    print()
    number = number - 1
  1. 实现图中功能


    Python 04_第2张图片
#个人代码
num = int(input("Please input an integer:"))
for i in range(1, num + 1):
    print(i)
#参考代码
temp = input("Please input an integer:")
number = int(temp)
i = 1
while number:
    print(i)
    i = i + 1
    number = number - 1
  1. 修改02章中的小游戏,要求为用户提供三次机会尝试,机会用完或者用户猜中答案均退出循环
#个人代码
import random
secret = random.randint(1, 10)

guess = int(input("Guess a number:"))
guess_number = 3
if guess == secret:
    print("Awesome!")
while guess != 8 and guess_number > 0:
    guess = int(input("Guess again:"))
    if guess == secret:
        print("Awesome")
    else:
        if guess < secret:
            print("smaller!")
        else:
            print("Bigger!")
    guess_number = guess_number - 1
    
print("Game over.")
#参考代码
import random
times = 3
secret = random.randint(1, 10)

guess = 0
#这里先给guess赋值(赋一个绝对不等于secret的值)

print("Guess a number:", end = " ")
#print()默认打印完字符会自动添加一个换行符,end = " "参数告诉print()用空格代替换行

while guess != secret and times > 0:
    temp = input()
    guess = int(temp)
    times = times - 1
    if guess == secret:
        print("Awesome!")
    else:
        if guess > secret:
            print("Bigger!")
        else:
            print("Smaller!")
        if times > 0:
            print("Try again:", end = " ")
        else:
            print("Sorry, opportunities are out!")
print("Game over.")

你可能感兴趣的:(Python 04)