Python案例:猜数游戏

Python案例:猜数游戏

Every programmer has a story about how they learned to write their first program. I started learning as a child when my father was working for Digital Equipment Corporation, one of the pioneering companies of the modern computing era. I wrote my first program on a kit computer my dad had assembled in our basement. The computer consisted of nothing more than a bare motherboard connected to a keyboard without a case, and it had a bare cathode ray tube for a monitor. My initial program was a simple number guessing game, which looked something like this:

I'm thinking of a number! Try to guess the number I'm thinking of: 25
Too low! Guess again: 50
Too high! Guess again: 42
That's it! Would you like to play again? (yes/no) no
Thanks for playing!

—— 摘自《Python编程从入门到实践》

编写Python程序: number_guessing_game.py
# Number Guessing Game

choice = "yes"

while choice == "yes":
	num = int(input("I'm thinking of a number! Try to guess the number I'm thinking of: "))
	while num != 42:
		if num < 42:
			num = int(input("Too low! Guess again: "))		
		elif num > 42:
			num = int(input("Too high! Guess again: "))		
	choice = input("That's it! Would you like to play again? (yes/no) ") 

print("Thanks for playing!")
Python案例:猜数游戏_第1张图片
运行程序,结果如下:
Python案例:猜数游戏_第2张图片
推广到猜某个范围内的随机整数:
# Number Guessing Game

from random import *

choice = "yes"

while choice == "yes":
	target = randint(1,1000)
	num = int(input("I'm thinking of a number! Try to guess the number I'm thinking of: "))
	while num != target:
		if num < target:
			num = int(input("Too low! Guess again: "))		
		elif num > target:
			num = int(input("Too high! Guess again: "))		
	choice = input("That's it! Would you like to play again? (yes/no) ") 

print("Thanks for playing!")

Python案例:猜数游戏_第3张图片

运行程序,结果如下:
Python案例:猜数游戏_第4张图片

你可能感兴趣的:(Python编程)