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

发布于:2023-01-04 ⋅ 阅读:(325) ⋅ 点赞:(0)

 

一、提要

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

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

二. 猜数字游戏

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

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

Sample Code:

import random
import math

# Taking Inputs
lower = int(input("Enter Lower bound:- "))
# Taking Inputs
upper = int(input("Enter Upper bound:- "))
# generating random number between
# the lower and upper
x = random.randint(lower, upper)
print("\n\tYou've only ",
      round(math.log(upper - lower + 1, 2)),
      " chances to guess the integer!\n")
# Initializing the number of guesses.
count = 0
# for calculation of minimum number of
# guesses depends upon range
while count < math.log(upper - lower + 1, 2):
    count += 1
    # taking guessing number as input
    guess = int(input("Guess a number:- "))
    # Condition testing
    if x == guess:
        print("Congratulations you did it in ",
              count, " try")
        # Once guessed, loop will break
        break
    elif x > guess:
        print("You guessed too small!")
    elif x < guess:
        print("You Guessed too high!")
# If Guessing is more than required guesses,
# shows this output.
if count >= math.log(upper - lower + 1, 2):
    print("\nThe number is %d" % x)
    print("\tBetter Luck Next time!")

三、 剪刀-石头-布模型

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

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

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

Sample Code:

import random

from enum import IntEnum

class Action(IntEnum):
    Rock = 0
    Paper = 1
    Scissors = 2

def get_user_selection():
    choices = [f"{action.name}[{action.value}]" for action in Action]
    choices_str = ", ".join(choices)
    selection = int(input(f"Enter a choice ({choices_str}): "))
    action = Action(selection)
    return action

def get_computer_selection():
    selection = random.randint(0, len(Action) - 1)
    action = Action(selection)
    return action
def determine_winner(user_action, computer_action):
    if user_action == computer_action:
        print(f"Both players selected {user_action.name}. It's a tie!")
    elif user_action == Action.Rock:
        if computer_action == Action.Scissors:
            print("Rock smashes scissors! You win!")
        else:
            print("Paper covers rock! You lose.")
    elif user_action == Action.Paper:
        if computer_action == Action.Rock:
            print("Paper covers rock! You win!")
        else:
            print("Scissors cuts paper! You lose.")
    elif user_action == Action.Scissors:
        if computer_action == Action.Paper:
            print("Scissors cuts paper! You win!")
        else:
            print("Rock smashes scissors! You lose.")

while True:
    try:
        user_action = get_user_selection()
    except ValueError as e:
        range_str = f"[0, {len(Action) - 1}]"
        print(f"Invalid selection. Enter a value in range {range_str}")
        continue

    computer_action = get_computer_selection()
    determine_winner(user_action, computer_action)

    play_again = input("Play again? (y/n): ")
    if play_again.lower() != "y":
        break

该游戏的另一个写法:

import random
import os
import re
os.system('cls' if os.name=='nt' else 'clear')

while (1 < 2):
    print ("\n")
    print ("Rock, Paper, Scissors - Shoot!")
    userChoice = input("Choose your weapon [R]ock], [P]aper, or [S]cissors: ")

    if not re.match("[SsRrPp]", userChoice):
        print ("Please choose a letter:")
        print ("[R]ock, [S]cissors or [P]aper.")
        continue

    # Echo the user's choice
    print ("You chose: " + userChoice)
    choices = ['R', 'P', 'S']
    opponenetChoice = random.choice(choices)
    print ("I chose: " + opponenetChoice )

    if opponenetChoice == str.upper(userChoice):
        print ("Tie! ")
        #if opponenetChoice == str("R") and str.upper(userChoice) == "P"
    elif opponenetChoice == 'R' and userChoice.upper() == 'S':
        print ("Scissors beats rock, I win! ")
        continue

    elif opponenetChoice == 'S' and userChoice.upper() == 'P':
        print ("Scissors beats paper! I win! ")
        continue
    elif opponenetChoice == 'P' and userChoice.upper() == 'R':
        print ("Paper beat rock, I win!")
        continue
    else:
        print ("You win!")

四、骰子点数生成器

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

Sample Code:

# dice.py

# ~~~ App's main code block ~~~
# ...
import random
# ...

def parse_input(input_string):
    """Return `input_string` as an integer between 1 and 6.

    Check if `input_string` is an integer number between 1 and 6.
    If so, return an integer with the same value. Otherwise, tell
    the user to enter a valid number and quit the program.
    """
    if input_string.strip() in {"1", "2", "3", "4", "5", "6"}:
        return int(input_string)
    else:
        print("Please enter a number from 1 to 6.")
        raise SystemExit(1)

def roll_dice(num_dice):
    """Return a list of integers with length `num_dice`.

    Each integer in the returned list is a random number between
    1 and 6, inclusive.
    """
    roll_results = []
    for _ in range(num_dice):
        roll = random.randint(1, 6)
        roll_results.append(roll)
    return roll_results

while True:
    num_dice_input = input("How many dice do you want to roll? [1-6] ")
    num_dice = parse_input(num_dice_input)
    roll_results = roll_dice(num_dice)
    print(roll_results)  # Remove this line after testing the app

五、二分查找算法

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

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

Sample Code:

# Python 3 program for recursive binary search.
# Modifications needed for the older Python 2 are found in comments.
 
# Returns index of x in arr if present, else -1
def binary_search(arr, low, high, x):
 
    # Check base case
    if high >= low:
        mid = (high + low) // 2
        # If element is present at the middle itself
        if arr[mid] == x:
            return mid
 
        # If element is smaller than mid, then it can only
        # be present in left subarray
        elif arr[mid] > x:
            return binary_search(arr, low, mid - 1, x)
 
        # Else the element can only be present in right subarray
        else:
            return binary_search(arr, mid + 1, high, x)
     else:
        # Element is not present in the array
        return -1
 
# Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 10
 
# Function call
result = binary_search(arr, 0, len(arr)-1, x)
 
if result != -1:
    print("Element is present at index", str(result))
else:
    print("Element is not present in array")

六、计算器生成

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

Sample Code:

# Program make a simple calculator

# This function adds two numbers
def add(x, y):
    return x + y


# This function subtracts two numbers
def subtract(x, y):
    return x - y


# This function multiplies two numbers
def multiply(x, y):
    return x * y


# This function divides two numbers
def divide(x, y):
    return x / y


print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

while True:
    # take input from the user
    choice = input("Enter choice(1/2/3/4): ")

    # check if choice is one of the four options
    if choice in ('1', '2', '3', '4'):
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))

        if choice == '1':
            print(num1, "+", num2, "=", add(num1, num2))

        elif choice == '2':
            print(num1, "-", num2, "=", subtract(num1, num2))

        elif choice == '3':
            print(num1, "*", num2, "=", multiply(num1, num2))

        elif choice == '4':
            print(num1, "/", num2, "=", divide(num1, num2))

        # check if user wants another calculation
        # break the while loop if answer is no
        next_calculation = input("Let's do next calculation? (yes/no): ")
        if next_calculation == "no":
            break

    else:
        print("Invalid Input")


网站公告

今日签到

点亮在社区的每一天
去签到