第二章,整体为循环等基础知识,只练习了本章最后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 guess<secretNumber: print('Your guess is to low.') elif guess>secretNumber: 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