栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

第二章 控制流【Python编程快速上手】

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

第二章 控制流【Python编程快速上手】

  第二章,整体为循环等基础知识,只练习了本章最后2个应用,主要学习了 random、sys的导入 和 sys.exit() 的使用。
#2.10 猜数字

#ThiS is a guess the number game.
import random
secretNumber=random.randint(1,20)
print('I am thinking of a number between 1 and 20.')

#Ask the player to guess 6 times
for guessesTaken in range(1,7):
    print("Take a guess.")
    guess=int(input())

    if guesssecretNumber:
        print('Your guess is to high.')
    else:        #This condition is the correct guess!
        break

if guess==secretNumber:
    print('Good job! You guessed my number in ' + str(guessesTaken) + ' guesses!')
else:
    print('Nope. The number I was thinking of was ' + str(secretNumber))

#石头、剪刀、布

import random,sys
print('ROCK,PAPER,SCISSORS')

# These variables keep track of the number of wins, losses, and ties.
wins=0
losses=0
ties=0     #平局

#The main game loop
while True:
    print('%s Wins,%s Losses,%s Ties'  % (wins,losses,ties))
    #字符串差值的方法:%s充当一个标记,用%后边单词的分别去替代它

    # The player input loop.
    while True:
        print('Enter your move: (r)ock (p)aper (s)cissors or (q)uit:')
        playerMove=input()     #获取用户的有效输入
        if playerMove=='q':
            sys.exit()
        if playerMove=='r' or playerMove=='p' or playerMove=='s':
            break
        print('Type one of r, p, s, or q.')    #如果这个if条件也不成立,调用print,继续while循环

    # Display what the player chose:
    if playerMove == 'r':
        print('ROCK versus...')
    elif playerMove == 'p':
        print('PAPER versus...')
    elif playerMove == 's':
        print('SCISSORS versus...')

    # Display what the computer chose:
    randomNumber = random.randint(1, 3)
    if randomNumber == 1:
        computerMove = 'r'
        print('ROCK')
    elif randomNumber == 2:
        computerMove = 'p'
        print('PAPER')
    elif randomNumber == 3:
        computerMove = 's'
        print('SCISSORS')

    # Display and record the win/loss/tie:
    if playerMove == computerMove:
        print('It is a tie!')
        ties = ties + 1
    elif playerMove == 'r' and computerMove == 's':
        print('You win!')
        wins = wins + 1
    elif playerMove == 'p' and computerMove == 'r':
        print('You win!')
        wins = wins + 1
    elif playerMove == 's' and computerMove == 'p':
        print('You win!')
        wins = wins + 1
    elif playerMove == 'r' and computerMove == 'p':
        print('You lose!')
        losses = losses + 1
    elif playerMove == 'p' and computerMove == 's':
        print('You lose!')
        losses = losses + 1
    elif playerMove == 's' and computerMove == 'r':
        print('You lose!')
        losses = losses + 1
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/969208.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号