• 【pyhton案例01】:5个有趣练习


     

    一、提要

            成为 Python 大师可以在你的职业生涯中打开许多大门,并获得全球一些最好的机会。无论您对 Python 技能的评价如何,从事 Python 项目都是提高技能和建立个人资料的可靠方法。虽然 Python 书籍和 Python 教程很有帮助,但没有什么比亲自动手编写代码更重要的了。

            我们为初学者列出了几个 Python 项目,供您挑战自己并在 Python 编码方面做得更好。

    二. 猜数字游戏

            这个项目是一个有趣的游戏,它在一定的指定范围内生成一个随机数,用户在收到提示后必须猜出这个数字。每次用户的猜测错误时,他们都会收到更多提示以使其更容易 - 以降低分数为代价。

            该程序还需要功能来检查用户是否输入了实际数字,并找出两个数字之间的差异。

    Sample Code:

    1. import random
    2. import math
    3. # Taking Inputs
    4. lower = int(input("Enter Lower bound:- "))
    5. # Taking Inputs
    6. upper = int(input("Enter Upper bound:- "))
    7. # generating random number between
    8. # the lower and upper
    9. x = random.randint(lower, upper)
    10. print("\n\tYou've only ",
    11. round(math.log(upper - lower + 1, 2)),
    12. " chances to guess the integer!\n")
    13. # Initializing the number of guesses.
    14. count = 0
    15. # for calculation of minimum number of
    16. # guesses depends upon range
    17. while count < math.log(upper - lower + 1, 2):
    18. count += 1
    19. # taking guessing number as input
    20. guess = int(input("Guess a number:- "))
    21. # Condition testing
    22. if x == guess:
    23. print("Congratulations you did it in ",
    24. count, " try")
    25. # Once guessed, loop will break
    26. break
    27. elif x > guess:
    28. print("You guessed too small!")
    29. elif x < guess:
    30. print("You Guessed too high!")
    31. # If Guessing is more than required guesses,
    32. # shows this output.
    33. if count >= math.log(upper - lower + 1, 2):
    34. print("\nThe number is %d" % x)
    35. print("\tBetter Luck Next time!")

    三、 剪刀-石头-布模型

            这个石头剪刀布程序使用了许多功能,因此这是一个很好地了解这个关键概念的方法。

    • get_user_selection(): 生成人的剪刀、石头、布; 
    • get_computer_selection(): 生成电脑的剪刀、石头、布; 
    • determine_winner: 裁决一次合法性胜负.
    • 反复循环程序

            该程序要求用户在采取行动之前先采取行动。输入可以是代表石头、纸或剪刀的字符串或字母。在评估输入字符串后,由结果函数决定获胜者,并由记分员函数更新该轮的分数。

    Sample Code:

    1. import random
    2. from enum import IntEnum
    3. class Action(IntEnum):
    4. Rock = 0
    5. Paper = 1
    6. Scissors = 2
    7. def get_user_selection():
    8. choices = [f"{action.name}[{action.value}]" for action in Action]
    9. choices_str = ", ".join(choices)
    10. selection = int(input(f"Enter a choice ({choices_str}): "))
    11. action = Action(selection)
    12. return action
    13. def get_computer_selection():
    14. selection = random.randint(0, len(Action) - 1)
    15. action = Action(selection)
    16. return action
    17. def determine_winner(user_action, computer_action):
    18. if user_action == computer_action:
    19. print(f"Both players selected {user_action.name}. It's a tie!")
    20. elif user_action == Action.Rock:
    21. if computer_action == Action.Scissors:
    22. print("Rock smashes scissors! You win!")
    23. else:
    24. print("Paper covers rock! You lose.")
    25. elif user_action == Action.Paper:
    26. if computer_action == Action.Rock:
    27. print("Paper covers rock! You win!")
    28. else:
    29. print("Scissors cuts paper! You lose.")
    30. elif user_action == Action.Scissors:
    31. if computer_action == Action.Paper:
    32. print("Scissors cuts paper! You win!")
    33. else:
    34. print("Rock smashes scissors! You lose.")
    35. while True:
    36. try:
    37. user_action = get_user_selection()
    38. except ValueError as e:
    39. range_str = f"[0, {len(Action) - 1}]"
    40. print(f"Invalid selection. Enter a value in range {range_str}")
    41. continue
    42. computer_action = get_computer_selection()
    43. determine_winner(user_action, computer_action)
    44. play_again = input("Play again? (y/n): ")
    45. if play_again.lower() != "y":
    46. break

    该游戏的另一个写法:

    1. import random
    2. import os
    3. import re
    4. os.system('cls' if os.name=='nt' else 'clear')
    5. while (1 < 2):
    6. print ("\n")
    7. print ("Rock, Paper, Scissors - Shoot!")
    8. userChoice = input("Choose your weapon [R]ock], [P]aper, or [S]cissors: ")
    9. if not re.match("[SsRrPp]", userChoice):
    10. print ("Please choose a letter:")
    11. print ("[R]ock, [S]cissors or [P]aper.")
    12. continue
    13. # Echo the user's choice
    14. print ("You chose: " + userChoice)
    15. choices = ['R', 'P', 'S']
    16. opponenetChoice = random.choice(choices)
    17. print ("I chose: " + opponenetChoice )
    18. if opponenetChoice == str.upper(userChoice):
    19. print ("Tie! ")
    20. #if opponenetChoice == str("R") and str.upper(userChoice) == "P"
    21. elif opponenetChoice == 'R' and userChoice.upper() == 'S':
    22. print ("Scissors beats rock, I win! ")
    23. continue
    24. elif opponenetChoice == 'S' and userChoice.upper() == 'P':
    25. print ("Scissors beats paper! I win! ")
    26. continue
    27. elif opponenetChoice == 'P' and userChoice.upper() == 'R':
    28. print ("Paper beat rock, I win!")
    29. continue
    30. else:
    31. print ("You win!")

    四、骰子点数生成器

            这个掷骰子生成器是一个相当简单的程序,它利用随机函数来模拟掷骰子。您可以将最大值更改为任意数字,从而可以模拟许多棋盘游戏和角色扮演游戏中使用的多面体骰子。

    Sample Code:

    1. # dice.py
    2. # ~~~ App's main code block ~~~
    3. # ...
    4. import random
    5. # ...
    6. def parse_input(input_string):
    7. """Return `input_string` as an integer between 1 and 6.
    8. Check if `input_string` is an integer number between 1 and 6.
    9. If so, return an integer with the same value. Otherwise, tell
    10. the user to enter a valid number and quit the program.
    11. """
    12. if input_string.strip() in {"1", "2", "3", "4", "5", "6"}:
    13. return int(input_string)
    14. else:
    15. print("Please enter a number from 1 to 6.")
    16. raise SystemExit(1)
    17. def roll_dice(num_dice):
    18. """Return a list of integers with length `num_dice`.
    19. Each integer in the returned list is a random number between
    20. 1 and 6, inclusive.
    21. """
    22. roll_results = []
    23. for _ in range(num_dice):
    24. roll = random.randint(1, 6)
    25. roll_results.append(roll)
    26. return roll_results
    27. while True:
    28. num_dice_input = input("How many dice do you want to roll? [1-6] ")
    29. num_dice = parse_input(num_dice_input)
    30. roll_results = roll_dice(num_dice)
    31. print(roll_results) # Remove this line after testing the app

    五、二分查找算法

            二分搜索算法是一个非常重要的算法,它要求您创建一个介于 0 和上限之间的数字列表,每个后续数字之间的差为 2。

            当用户输入要搜索的随机数时,程序通过将列表分成两半来开始搜索。首先,搜索前半部分以查找所需的数字,如果找到,则拒绝另一半,反之亦然。搜索将继续,直到找到数字或子数组大小变为零。

    Sample Code:

    1. # Python 3 program for recursive binary search.
    2. # Modifications needed for the older Python 2 are found in comments.
    3. # Returns index of x in arr if present, else -1
    4. def binary_search(arr, low, high, x):
    5. # Check base case
    6. if high >= low:
    7. mid = (high + low) // 2
    8. # If element is present at the middle itself
    9. if arr[mid] == x:
    10. return mid
    11. # If element is smaller than mid, then it can only
    12. # be present in left subarray
    13. elif arr[mid] > x:
    14. return binary_search(arr, low, mid - 1, x)
    15. # Else the element can only be present in right subarray
    16. else:
    17. return binary_search(arr, mid + 1, high, x)
    18. else:
    19. # Element is not present in the array
    20. return -1
    21. # Test array
    22. arr = [ 2, 3, 4, 10, 40 ]
    23. x = 10
    24. # Function call
    25. result = binary_search(arr, 0, len(arr)-1, x)
    26. if result != -1:
    27. print("Element is present at index", str(result))
    28. else:
    29. print("Element is not present in array")

    六、计算器生成

            该项目教你设计图形界面,是熟悉 Tkinter 等库的好方法。该库允许您创建按钮来执行不同的操作并在屏幕上显示结果。

    Sample Code:

    1. # Program make a simple calculator
    2. # This function adds two numbers
    3. def add(x, y):
    4. return x + y
    5. # This function subtracts two numbers
    6. def subtract(x, y):
    7. return x - y
    8. # This function multiplies two numbers
    9. def multiply(x, y):
    10. return x * y
    11. # This function divides two numbers
    12. def divide(x, y):
    13. return x / y
    14. print("Select operation.")
    15. print("1.Add")
    16. print("2.Subtract")
    17. print("3.Multiply")
    18. print("4.Divide")
    19. while True:
    20. # take input from the user
    21. choice = input("Enter choice(1/2/3/4): ")
    22. # check if choice is one of the four options
    23. if choice in ('1', '2', '3', '4'):
    24. num1 = float(input("Enter first number: "))
    25. num2 = float(input("Enter second number: "))
    26. if choice == '1':
    27. print(num1, "+", num2, "=", add(num1, num2))
    28. elif choice == '2':
    29. print(num1, "-", num2, "=", subtract(num1, num2))
    30. elif choice == '3':
    31. print(num1, "*", num2, "=", multiply(num1, num2))
    32. elif choice == '4':
    33. print(num1, "/", num2, "=", divide(num1, num2))
    34. # check if user wants another calculation
    35. # break the while loop if answer is no
    36. next_calculation = input("Let's do next calculation? (yes/no): ")
    37. if next_calculation == "no":
    38. break
    39. else:
    40. print("Invalid Input")

  • 相关阅读:
    【数据库——MySQL(实战项目1)】(1)图书借阅系统
    使用pocsuite3模块编写poc脚本
    Map和Set
    MySQL权限与安全管理
    Python点云处理(十九)点云地面点提取——CSF布料模拟算法
    Mqtt 客户端 java API 教程
    人工智能|AI作画体验:见识AI绘画,离谱的创造力
    [ AT_agc009_c]Division into Two
    GCC详解的-Wl选项说明与测试
    智慧农业SaaS系统
  • 原文地址:https://blog.csdn.net/gongdiwudu/article/details/126511931