python程序 有趣好玩
时间: 2023-06-22 21:35:04 浏览: 56
是的,Python 程序非常有趣和好玩!Python 是一种高级编程语言,易于学习和使用,被广泛应用于各种领域,例如数据分析、人工智能、Web 应用程序等。下面是一些有趣的 Python 程序示例:
1. 猜数字游戏
这是一个简单的猜数字游戏,程序会生成一个随机数,然后提示你猜测该数字,直到你猜中为止。
```python
import random
number = random.randint(1, 100)
guess = 0
while guess != number:
guess = int(input('请输入一个数字(1-100):'))
if guess > number:
print('猜大了!')
elif guess < number:
print('猜小了!')
print('恭喜你,猜对了!')
```
2. 图片转字符画
这个程序可以将一张图片转换成字符画,非常有趣。
```python
from PIL import Image
ASCII_CHARS = [' ', '.', ':', '-', '=', '+', '*', '#', '%', '@']
def resize_image(image, new_width=100):
width, height = image.size
ratio = height / width
new_height = int(new_width * ratio)
return image.resize((new_width, new_height))
def image_to_ascii(image):
pixels = list(image.getdata())
ascii_pixels = [ASCII_CHARS[int(pixel / 25)] for pixel in pixels]
return ''.join(ascii_pixels)
def main():
image_path = input('请输入图片路径:')
image = Image.open(image_path)
image = resize_image(image)
ascii_text = image_to_ascii(image)
print(ascii_text)
if __name__ == '__main__':
main()
```
3. 文字游戏
这个程序可以让你玩一个文字游戏,你需要猜测一个单词,程序会告诉你猜测的单词是否正确,并显示已猜测的字母。
```python
import random
WORDS = ['apple', 'banana', 'orange', 'watermelon', 'pear', 'grape']
def select_word(words):
return random.choice(words)
def play_game(word):
guessed = False
guessed_letters = []
tries = 6
while not guessed and tries > 0:
guess = input('猜一个字母或单词:').lower()
if len(guess) == 1 and guess.isalpha():
if guess in guessed_letters:
print('你已经猜过这个字母了!')
elif guess in word:
print('你猜对了这个字母!')
guessed_letters.append(guess)
else:
print('你猜错了这个字母!')
tries -= 1
guessed_letters.append(guess)
elif len(guess) == len(word) and guess.isalpha():
if guess == word:
print('你猜对了这个单词!')
guessed = True
else:
print('你猜错了这个单词!')
tries -= 1
else:
print('无效的猜测!')
print(' '.join(letter if letter in guessed_letters else '_' for letter in word))
print('你还有{}次机会。'.format(tries))
if guessed:
print('恭喜你,你赢了!')
else:
print('很遗憾,你输了!')
def main():
word = select_word(WORDS)
play_game(word)
if __name__ == '__main__':
main()
```
希望这些程序能够让你感受到 Python 的趣味和魅力!