Рубрики
Без рубрики

6 Проектов на Python для начинающих

6 простых проектов на Python для начинающих, которые помогут вам начать с кодирования на python

Автор оригинала: Zerq’sProgramz.

Python может быть отличным языком программирования. Вы можете сделать почти все, что захотите. Если вы новичок и не знаете, что делать, вот несколько проектов для начинающих, которые вы можете сделать.

1-Базовый калькулятор

Это, безусловно, самый простой проект в списке. Вы просите пользователя ввести свой первый номер, затем оператора, затем второй номер. Как только они все это выложат, программа должна вычислить, чего хочет пользователь.

Вещи, которые вы должны знать, чтобы сделать этот проект:

  • переменные
  • плыть
  • базовая математика
  • если/еще если/еще
# The user's inputs for the numbers and the operators
num1 = float(input('Enter your first number: '))
Operator = input('Enter operator: ')
num2 = float(input('Enter your second number: '))

# if Operator is (+ | - | * | /) then  print out number 1 (+ | - | * | /) number 2
if Operator == '+':
    print(num1 + num2)
elif Operator == '-':
    print(num1 - num2)
elif Operator == '/':
    print(num1 / num2)
elif Operator == '*':
    print(num1 * num2)

# if the user didn't put an operator
else:
    print('Not a valid operator')

2-Угадайте число

Эта игра является основной. Программа выбирает случайное число. вы можете настроить, насколько высокими или низкими могут быть числа (например: 0-50 или 1-10.) Все зависит от вас.

Вещи, которые вы должны знать, чтобы сделать этот проект:

  • модуль python random
  • в то время как петли
  • если/еще если/еще
  • целые числа
# Python Random Module
import random

# Number of Variables
attempts = 0

# Choose a random number
number = random.randint(1, 20)
print("I am thinking of a number between 1 and 20.")

# While the player's guesses is less then 6
while attempts < 6:
    guess = input("Take a guess: ")
    guess = int(guess)

    attempts += 1

    # If the player's guess is too low
    if guess < number:
        print("Higher")

    # If the player's guess is too high
    if guess > number:
        print("Lower")
        
    # If the player won, stop the loop
    if guess == number:
        break

# If the player won
if guess == number:
    attempts = str(attempts)
    print(f"Good job! You guessed my number in {attempts} guesses!")

# If the player lost
if guess != number:
    number = str(number)
    print(f"Nope. The number I was thinking of was {number}")

3-Камень, Ножницы, Бумага

Для меня это была самая простая игра, программа случайным образом выбирает камень, бумагу или ножницы. Затем игрок вводит свой выбор. Затем… Ну, ты же знаешь правила.

Вещи, которые вы должны знать, чтобы сделать этот проект:

  • модуль python random
  • переменные
  • если/еще если/еще
  • функции
  • списки
# Python Random Module
import random

# Intro
print("Rock, Paper, Scissors...")

# Function
def try_again():
  # Random Choice (Rock, Paper, or Scissors)
    R_P_S = ["Rock", "Paper", "Scissors"]
    computer = random.choice(R_P_S)

  # Player's choice
    player = input("your choice: ").lower().capitalize()

  # If the program chose rock
    if computer == "Rock":
    	# If the player chose rock
        if player == "Rock":
            print(f"I chose {computer}, you chose {player}\nit's a tie!")
        # If the player chose paper
        elif player == "Paper":
            print(f"I chose {computer}, you chose {player}\nYou win!")
        # If the player chose scissors
        elif player == "Scissors":
            print(f"I chose {computer}, you chose {player}\nI win!")

  # If the program chose paper
    elif computer == "Paper":
    	# If the player chose rock
        if player == "Rock":
            print(f"I chose {computer}, you chose {player}\nI win!")
        # If the player chose paper
        elif player == "Paper":
            print(f"I chose {computer}, you chose {player}\nIt's a tie!")
        # If the player chose scissors
        elif player == "Scissors":
            print(f"I chose {computer}, you chose {player}\nYou win!")

  # If the program chose scissors
    elif computer == "Scissors":
    	# If the player chose rock
        if player == "Rock":
            print(f"I chose {computer}, you chose {player}\nYou win!")
        # If the player chose paper
        elif player == "Paper":
            print(f"I chose {computer}, you chose {player}\nI win!")
        # If the player chose scissors
        elif player == "Scissors":
            print(f"I chose {computer}, you chose {player}\nIt's a tie") 

  # If the player wants to play again
    play_again = input("Do you want to play again? yes or no: ").lower().capitalize()
    # If the player says yes, go back to the function
    if play_again == "Yes":
        try_again()
    # If the player says no, say goodbye
    elif play_again == "No":
        print("Goodbye")

# End of function
try_again()

4-Бросьте Кости

Программа, которая действует как виртуальная игральная кость. Вы можете заставить пользователя выбрать, сколько кубиков он хочет бросить (сложнее), или вы можете выбрать все, что хотите, и заставить пользователя принять это (проще)

Вещи, которые вы должны знать, чтобы сделать этот проект:

  • модуль python random
  • модуль воспроизведения звука python (чтобы он больше походил на виртуальную игру в кости, чем на какую-то программу, которая выплевывает случайные числа)
  • переменные
  • если/еще если/еще
  • цикл while
  • функции
# Python Random & Playsound Modules
import random
from playsound import playsound

# Function
def again():
  # Variables
    dices = 0
    roll_again = print()
    while dices == 0:
    	# User's choice of how many dices they want to roll
        chosen_dices = int(input("How many dices do you want to roll? (from 1 to 5): "))
        # If the user choose a number between 1 and 5, break out of the loop
        if chosen_dices > 0 and chosen_dices < 6:
            break
  
    # If the user choose (any number) dice(s), generate a random number from 1 to 6 and continue until we meet the user's needs
    if chosen_dices == 1:
        playsound('Dice shake.mp3')
        playsound("Dice roll.mp3")  
        while dices < 1 :
            rolls = random.randint(1, 6)
            print(rolls)
            dices +=1

    elif chosen_dices == 2:
        playsound('Dice shake.mp3')
        playsound("Dice roll.mp3")  
        while dices < 2 :
            rolls = random.randint(1, 6)
            print(rolls)
            dices +=1

    elif chosen_dices == 3:
        playsound('Dice shake.mp3')
        playsound("Dice roll.mp3")  
        while dices < 3 :
            rolls = random.randint(1, 6)          
            print(rolls)
            dices +=1

    elif chosen_dices == 4:
        playsound('Dice shake.mp3')
        playsound("Dice roll.mp3") 
        while dices < 4 :
            rolls = random.randint(1, 6)
            print(rolls)
            dices +=1

    elif chosen_dices == 5:
        playsound('Dice shake.mp3')
        playsound("Dice roll.mp3")  
        while dices < 5 :
            rolls = random.randint(1, 6)     
            print(rolls)
            dices +=1
  
    # Asking the user if he wants to roll again
    print("Do you want to roll again?")
    while roll_again != "Yes" or roll_again != "No":
        roll_again = input("Yes | No: ").lower().capitalize()
        # If yes, then go back to the function
        if roll_again == "Yes":
            again()
            break
        # If no, then say goodbye and exit
        if roll_again == "No":
            print("Goodbye")
            break
# End of function
again()

5-Преобразователь Температуры

Полезная программа, которая поможет вам конвертировать температуру.

Вещи, которые вы должны знать, чтобы сделать этот проект:

  • математический модуль python
  • модуль времени python (я добавил его, чтобы у пользователя было время для чтения)
  • переменные
  • поплавки
  • промежуточная математика
  • знание о температуре (вы можете погуглить его)
# Python Math & Time Modules
import math
import time

# Intro
print("Welcome to the Temperature Conventer. Type C for Celsuis, F for Fahreinheit and K for Kelvin")

# Function
def again():
    try_again = print()
    # Letting the user choose the temperature and convert it to another temperature else
    User_Temperature = input("your temperature | C | F | K | ").upper()
    convert_Temperature = input("The temperature you want to convert to | C | F | K | ").upper()
  
    # If the user's intial temperature (C, F, or K) convert it to what the user wants to convert to (C, F, or K) and give him the equation
    if User_Temperature == "C":
        if convert_Temperature == "F":
            degree = float(input("enter the degree: "))
            result = (degree * 9/5) + 32
            print(f"{result}°F \nThe equation: ({degree} × 9/5) + 32 = {result}")
        elif convert_Temperature == "K":
            degree = float(input("enter the degree: "))
            result = degree + 273.15
            print(f"{result}°K \nThe equation: {degree} + 273.15 = {result}")
        elif convert_Temperature == "C":
            print("This is the same type of temperature")
            time.sleep(1)
            again()
        else:
            print("Type a temperature")
            time.sleep(1)
            again()

    elif User_Temperature == "F":
        if convert_Temperature == "C":
            degree = float(input("enter the degree: "))
            result = (degree - 32) * 5/9
            print(f"{result}°F \nThe equation: ({degree} - 32) × 5/9 = {result}")
        elif convert_Temperature == "K":
            degree = float(input("enter the degree: "))
            result = (degree - 32) * 5/9 + 273.15
            print(f"{result}°K \nThe equation: ({degree} - 32) × 5/9 + 273.15 = {result}")
        elif convert_Temperature == "F":
            print("This is the same type of temperature")
            time.sleep(1)
            again()
        else:
            print("Type a temperature")
            time.sleep(1)
            again()

    elif User_Temperature == "K":
        if convert_Temperature == "C":
            degree = float(input("enter the degree: "))
            result = degree - 273.15
            print(f"{result}°F \nThe equation: {degree} - 273.15 = {result}")
        elif convert_Temperature == "F":
            degree = float(input("enter the degree: "))
            result = (degree - 273.15) * 9/5 + 32
            print(f"{result}°K \nThe equation: ({degree} - 273.15) × 9/5 + 32 = {result}")
        elif convert_Temperature == "K":
            print("This is the same type of temperature")
            time.sleep(1)
            again()
        else:
            print("Type a temperature")
            time.sleep(1)
            again()

    else:
        print("Type a temperature")
        time.sleep(1)
        again()

  # Aking if the user wants to convert again
    while try_again != "Yes" and try_again != "No":
        print("\nDo you want to try again?")
        try_again = input("Yes | No | ").lower().capitalize()
        if try_again == "Yes":
            again()
            break
        elif try_again == "No":
            print("Goodbye")
            break

again()

6-Палач

Это, безусловно, может занять больше времени, в зависимости от того, сколько слов вы вставите. Программа выбирает случайное слово из списка, затем программа распечатывает несколько букв и просит пользователя ввести недостающие буквы. После 6 попыток игрок проигрывает. Я добавлю только 1 слово, чтобы вы поняли идею, и сценарий не будет длинным.

Вещи, которые вам нужно знать, чтобы сделать этот проект:

  • модуль python random
  • функции
  • списки
  • переменные
  • если/еще если/еще
# Python Random Module
import random

# Intro
print("Welcome to Hangman! I will choose a word and you have to guess its letters. You only have 6 attempts.")

# Function
def try_again():
  # Random chooser
    words = ["ignore"]
    word_choice = random.choice(words)
    
    # Variables
    attempts = 0
    a = False
    b = False
    c = False
    d = False
    e = False
    f = False
    g = False
    h = False
    i = False
    j = False
    k = False
    l = False
    m = False
    n = False
    o = False
    p = False
    q = False
    r = False
    s = False
    t = False
    u = False
    v = False
    w = False
    x = False
    y = False
    z = False

  # If the program chose a word, print it out with missing letters. If the user gets the letters correct, change its variable to True and print it out. Once all the letters are found, the player won
    if word_choice == "ignore":
        print("__ __ n o __ e")
        guess = input("type the missing letter: ")
        while attempts < 6:
            if guess == "i":
                i=True
                if g == True and r == True:
                    print("i g n o r e")
                    win = input(f"you won, you took {attempts} attempt(s), Do you want to play again? Yes or No: ").lower().capitalize()
                    if win == "Yes":
                        try_again()
                        break
                    elif win == "No":
                        print("Goodbye")
                        break
                elif r == True:
                    print("i __ n o r e")
                    guess = input("\ntype the missing letter: ")
                elif g == True:
                    print("i g n o __ e")
                    guess = input("\ntype the missing letter: ")
                else:
                    print("i __ n o __ e")
                    guess = input("\ntype the missing letter: ")
            elif guess == "g":
                g = True
                if i == True and r == True:
                    print("i g n o r e")
                    win = input(f"you won, you took {attempts} attempt(s), Do you want to play again? Yes or No: ").lower().capitalize()
                    if win == "Yes":
                        try_again()
                        break
                    elif win == "No":
                        print("Goodbye")
                        break
                elif r == True:
                    print("__ g n o r e")
                    guess = input("\ntype the missing letter: ")
                elif i == True:
                    print("i g n o __ e")
                    guess = input("\ntype the missing letter: ")
                else:
                    print("__ g n o __ e")
                    guess = input("\ntype the missing letter: ")
            elif guess == "r":
                r = True
                if i == True and g == True:
                    print("i g n o r e")
                    win = input(f"you won, you took {attempts} attempt(s), Do you want to play again? Yes or No: ").lower().capitalize()
                    if win == "Yes":
                        try_again()
                        break
                    elif win == "No":
                        print("Goodbye")
                        break
                elif g == True:
                    print("__ g n o r e")
                    guess = input("\ntype the missing letter: ")
                elif i == True:
                    print("i __ n o r e")
                else:
                    print("__ __ n o r e")
                    guess = input("\ntype the missing letter: ")
            else:
                print("Try Again")
                attempts += 1
                guess = input("\ntype the missing letter: ")
    		
            # If all of the player's attempts lost, game over
            if not attempts < 6:
            	game_over = input("Game Over. Do you want to play again? Yes or No: ").lower().capitalize()
                if game_over == "Yes":
                	try_again()
                elif game_over == "No":
                    print("Goodbye")

# End of function
try_again()

Я надеюсь, что это поможет вам, пожалуйста, прокомментируйте свои программы, чтобы все это увидели.