Proyek otomatisasi python dengan kode sumber

Saat ini, kami mengalami adopsi Kecerdasan Buatan (AI), Pembelajaran Mesin (ML), dan Ilmu Data yang terus berkembang di sebagian besar sektor bisnis. Salah satu kesamaan utama yang dimiliki kolom ini adalah bahwa mereka menggunakan bahasa pemrograman Python dengan satu atau lain cara

Menjadi ahli Python dapat membuka banyak pintu dalam karier Anda, memungkinkan Anda mendapatkan beberapa peluang kerja terbaik di planet ini. Terlepas dari kemampuan Python Anda saat ini, mengetahui bagaimana membangun proyek Python adalah cara yang pasti untuk meningkatkan keterampilan Anda dan membangun portofolio Anda

Dan meskipun buku Python dan tutorial Python sangat membantu, tidak ada yang lebih baik daripada mengotori tangan Anda dengan beberapa pengkodean aktual dan mencoba ide proyek Python

Dalam artikel ini, kami telah mencantumkan 30 proyek Python yang menarik, mulai dari proyek Python sederhana untuk pemula hingga ide proyek Python menengah dan lanjutan, yang dapat Anda gunakan untuk menantang diri sendiri atau meningkatkan keterampilan pemrograman Python Anda

Proyek Python untuk Pemula

1. Generator Libs Gila

Ini adalah salah satu proyek Python pemula yang paling menyenangkan, belum lagi memungkinkan Anda berlatih cara menggunakan string, variabel, dan penggabungan

Mad Libs Generator mengumpulkan dan memanipulasi data masukan pengguna sebagai kata sifat, kata ganti, dan kata kerja. Program mengambil data ini dan menyusunnya untuk membangun sebuah cerita

Kode sumber

'''
Mad Libs Generator
-------------------------------------------------------------
'''

# Questions for the user to answer

noun = input('Choose a noun: ')

p_noun = input('Choose a plural noun: ')

noun2 = input('Choose a noun: ')

place = input('Name a place: ')

adjective = input('Choose an adjective (Describing word): ')

noun3 = input('Choose a noun: ')

# Print a story from the user input

print('------------------------------------------')

print('Be kind to your', noun, '- footed', p_noun)

print('For a duck may be somebody\'s', noun2, ',')

print('Be kind to your', p_noun, 'in', place)

print('Where the weather is always', adjective, '. \n')

print('You may think that is this the', noun3, ',')

print('Well it is.')

print('------------------------------------------')

2. Menebak Angka

Proyek Python pemula ini adalah permainan menyenangkan yang menghasilkan angka acak (dalam rentang tertentu) yang harus ditebak pengguna setelah menerima petunjuk. Untuk setiap tebakan salah yang dilakukan pengguna, mereka menerima petunjuk tambahan, tetapi dengan mengorbankan skor akhir mereka

Program ini adalah cara yang bagus untuk bereksperimen dengan pustaka standar Python, karena program ini menggunakan modul acak Python untuk menghasilkan angka acak. Anda juga bisa mendapatkan beberapa praktik langsung dengan pernyataan bersyarat, pemformatan cetak, dan fungsi yang ditentukan pengguna

Kode sumber

'''
Number Guessing Game
-------------------------------------------------------------
'''

import random

attempts_list = []


def show_score():
  if not attempts_list:
      print('There is currently no high score, it\'s yours for the taking!')

  else:
      print(f'The current high score is {min(attempts_list)} attempts')


def start_game():
   attempts = 0
   rand_num = random.randint(1, 10)
   print('Hello traveler! Welcome to the game of guesses!')
   player_name = input('What is your name? ')
   wanna_play = input(
       f'Hi, {player_name}, would you like to play the guessing game?'
       '(Enter Yes/No): ')

   if wanna_play.lower() != 'yes':
      print('That\'s cool, Thanks!')
      exit()
   else:
       show_score()

   while wanna_play.lower() == 'yes':
       try:
           guess = int(input('Pick a number between 1 and 10: '))
           if guess < 1 or guess > 10:
               raise ValueError(
                   'Please guess a number within the given range')

           attempts += 1
           attempts_list.append(attempts)

           if guess == rand_num:
               print('Nice! You got it!')
               print(f'It took you {attempts} attempts')
               wanna_play = input(
                   'Would you like to play again? (Enter Yes/No): ')
               if wanna_play.lower() != 'yes':
                   print('That\'s cool, have a good one!')
                   break
               else:
                   attempts = 0
                   rand_num = random.randint(1, 10)
                   show_score()
                   continue
           else:
               if guess > rand_num:
                   print('It\'s lower')
               elif guess < rand_num:
                   print('It\'s higher')

       except ValueError as err:
           print('Oh no!, that is not a valid value. Try again...')
           print(err)


if __name__ == '__main__':
   start_game()

_

3. Batu gunting kertas

Program Rock Paper Scissors ini mensimulasikan permainan yang populer secara universal dengan fungsi dan pernyataan bersyarat. Jadi, cara apa yang lebih baik untuk mendapatkan konsep kritis ini?

Sebagai salah satu dari banyak proyek pengkodean Python yang mengimpor pustaka tambahan, program ini menggunakan modul acak, os, dan re dari pustaka standar

Lihatlah kode di bawah ini, dan Anda akan melihat bahwa ide proyek Python ini meminta pengguna untuk melakukan langkah pertama dengan meneruskan karakter untuk mewakili batu, kertas, atau gunting. Setelah mengevaluasi string input, logika kondisional memeriksa pemenang

Kode sumber

'''
Rock Paper Scissors
-------------------------------------------------------------
'''


import random
import os
import re


def check_play_status():
  valid_responses = ['yes', 'no']
  while True:
      try:
          response = input('Do you wish to play again? (Yes or No): ')
          if response.lower() not in valid_responses:
              raise ValueError('Yes or No only')

          if response.lower() == 'yes':
              return True
          else:
              os.system('cls' if os.name == 'nt' else 'clear')
              print('Thanks for playing!')
              exit()

      except ValueError as err:
          print(err)


def play_rps():
   play = True
   while play:
       os.system('cls' if os.name == 'nt' else 'clear')
       print('')
       print('Rock, Paper, Scissors - Shoot!')

       user_choice = input('Choose your weapon'
                           ' [R]ock], [P]aper, or [S]cissors: ')

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

       print(f'You chose: {user_choice}')

       choices = ['R', 'P', 'S']
       opp_choice = random.choice(choices)

       print(f'I chose: {opp_choice}')

       if opp_choice == user_choice.upper():
           print('Tie!')
           play = check_play_status()
       elif opp_choice == 'R' and user_choice.upper() == 'S':
           print('Rock beats scissors, I win!')
           play = check_play_status()
       elif opp_choice == 'S' and user_choice.upper() == 'P':
           print('Scissors beats paper! I win!')
           play = check_play_status()
       elif opp_choice == 'P' and user_choice.upper() == 'R':
           print('Paper beats rock, I win!')
           play = check_play_status()
       else:
           print('You win!\n')
           play = check_play_status()


if __name__ == '__main__':
   play_rps()

4. Generator Gulungan Dadu

Sebagai salah satu proyek Python yang paling cocok untuk pemula dengan kode, program ini mensimulasikan pengguliran satu atau dua dadu. Ini juga cara yang bagus untuk memperkuat pemahaman Anda tentang fungsi, loop, dan pernyataan bersyarat yang ditentukan pengguna

Sebagai salah satu proyek mudah Python, ini adalah program yang cukup sederhana yang menggunakan modul acak Python untuk mereplikasi sifat acak dari lemparan dadu. Anda juga akan melihat bahwa kami menggunakan modul os untuk membersihkan layar setelah Anda melempar dadu

Perhatikan bahwa Anda dapat mengubah nilai dadu maksimum ke angka berapa pun, memungkinkan Anda untuk mensimulasikan dadu polihedral yang sering digunakan di banyak permainan papan dan permainan peran

Kode sumber

'''
Dice Roll Generator
-------------------------------------------------------------
'''


import random
import os


def num_die():
  while True:
      try:
          num_dice = input('Number of dice: ')
          valid_responses = ['1', 'one', 'two', '2']
          if num_dice not in valid_responses:
              raise ValueError('1 or 2 only')
          else:
              return num_dice
      except ValueError as err:
          print(err)


def roll_dice():
   min_val = 1
   max_val = 6
   roll_again = 'y'

   while roll_again.lower() == 'yes' or roll_again.lower() == 'y':
       os.system('cls' if os.name == 'nt' else 'clear')
       amount = num_die()

       if amount == '2' or amount == 'two':
           print('Rolling the dice...')
           dice_1 = random.randint(min_val, max_val)
           dice_2 = random.randint(min_val, max_val)

           print('The values are:')
           print('Dice One: ', dice_1)
           print('Dice Two: ', dice_2)
           print('Total: ', dice_1 + dice_2)

           roll_again = input('Roll Again? ')
       else:
           print('Rolling the die...')
           dice_1 = random.randint(min_val, max_val)
           print(f'The value is: {dice_1}')

           roll_again = input('Roll Again? ')


if __name__ == '__main__':
   roll_dice()

5. Permainan Hangman

Ini adalah ide proyek Python yang menyenangkan untuk meniru permainan tebak kata, Hangman. Kami telah menggunakan daftar kata yang telah ditentukan sebelumnya untuk aspek tebakan, tetapi jangan ragu untuk memperbaikinya dengan menggunakan API kamus pihak ketiga

Proyek Python ini menggunakan loop, fungsi, dan pemformatan string untuk mencetak progres algojo. Ini juga memungkinkan Anda bereksperimen dengan modul acak, waktu, dan os perpustakaan standar

Secara khusus, kami telah menggunakan modul acak untuk memilih kata yang akan ditebak, modul os untuk membersihkan layar, dan modul waktu. fungsi sleep() untuk memperkenalkan jeda untuk meningkatkan alur game

Kode sumber

'''
Hangman Game
-------------------------------------------------------------
'''


import random
import time
import os


def play_again():
  question = 'Do You want to play again? y = yes, n = no \n'
  play_game = input(question)
  while play_game.lower() not in ['y', 'n']:
      play_game = input(question)

  if play_game.lower() == 'y':
      return True
  else:
      return False


def hangman(word):
  display = '_' * len(word)
  count = 0
  limit = 5
  letters = list(word)
  guessed = []
  while count < limit:
      guess = input(f'Hangman Word: {display} Enter your guess: \n').strip()
      while len(guess) == 0 or len(guess) > 1:
          print('Invalid input. Enter a single letter\n')
          guess = input(
              f'Hangman Word: {display} Enter your guess: \n').strip()

      if guess in guessed:
          print('Oops! You already tried that guess, try again!\n')
          continue

      if guess in letters:
          letters.remove(guess)
          index = word.find(guess)
          display = display[:index] + guess + display[index + 1:]

      else:
          guessed.append(guess)
          count += 1
          if count == 1:
              time.sleep(1)
              print('   _____ \n'
                    '  |      \n'
                    '  |      \n'
                    '  |      \n'
                    '  |      \n'
                    '  |      \n'
                    '  |      \n'
                    '__|__\n')
              print(f'Wrong guess: {limit - count} guesses remaining\n')

          elif count == 2:
              time.sleep(1)
              print('   _____ \n'
                    '  |     | \n'
                    '  |     | \n'
                    '  |      \n'
                    '  |      \n'
                    '  |      \n'
                    '  |      \n'
                    '__|__\n')
              print(f'Wrong guess: {limit - count} guesses remaining\n')

          elif count == 3:
              time.sleep(1)
              print('   _____ \n'
                    '  |     | \n'
                    '  |     | \n'
                    '  |     | \n'
                    '  |      \n'
                    '  |      \n'
                    '  |      \n'
                    '__|__\n')
              print(f'Wrong guess: {limit - count} guesses remaining\n')

          elif count == 4:
              time.sleep(1)
              print('   _____ \n'
                    '  |     | \n'
                    '  |     | \n'
                    '  |     | \n'
                    '  |     O \n'
                    '  |      \n'
                    '  |      \n'
                    '__|__\n')
              print(f'Wrong guess: {limit - count} guesses remaining\n')

          elif count == 5:
              time.sleep(1)
              print('   _____ \n'
                    '  |     | \n'
                    '  |     | \n'
                    '  |     | \n'
                    '  |     O \n'
                    '  |    /|\ \n'
                    '  |    / \ \n'
                    '__|__\n')
              print('Wrong guess. You\'ve been hanged!!!\n')
              print(f'The word was: {word}')

      if display == word:
          print(f'Congrats! You have guessed the word \'{word}\' correctly!')
          break


def play_hangman():
   print('\nWelcome to Hangman\n')
   name = input('Enter your name: ')
   print(f'Hello {name}! Best of Luck!')
   time.sleep(1)
   print('The game is about to start!\nLet\'s play Hangman!')
   time.sleep(1)
   os.system('cls' if os.name == 'nt' else 'clear')

   words_to_guess = [
       'january', 'border', 'image', 'film', 'promise', 'kids',
       'lungs', 'doll', 'rhyme', 'damage', 'plants', 'hello', 'world'
   ]
   play = True
   while play:
       word = random.choice(words_to_guess)
       hangman(word)
       play = play_again()

   print('Thanks For Playing! We expect you back again!')
   exit()


if __name__ == '__main__':
  play_hangman()

_

6. Pemeriksa Kekuatan Kata Sandi

Proyek Python ini memungkinkan Anda memeriksa apakah kata sandi Anda cukup kuat

Ini dilakukan dengan memeriksa jumlah huruf, angka, karakter khusus, dan karakter spasi dalam kata sandi yang diberikan dan menghasilkan skor berdasarkan hasil ini. Jadi, ini adalah cara bagus lainnya untuk mempelajari tentang pernyataan bersyarat, fungsi, dan pemformatan string

Kami juga menggunakan modul string dan getpass dari pustaka standar Python. Hal ini memungkinkan kita untuk mengakses rangkaian lengkap karakter string untuk dibandingkan dengan komposisi karakter kata sandi kita, sedangkan. fungsi getpass() memungkinkan kita menyembunyikan kata sandi saat kita memasukkannya

Kode sumber

'''
Password Strength Checker
-------------------------------------------------------------
'''


import string
import getpass


def check_password_strength():
   password = getpass.getpass('Enter the password: ')
   strength = 0
   remarks = ''
   lower_count = upper_count = num_count = wspace_count = special_count = 0

   for char in list(password):
       if char in string.ascii_lowercase:
           lower_count += 1
       elif char in string.ascii_uppercase:
           upper_count += 1
       elif char in string.digits:
           num_count += 1
       elif char == ' ':
           wspace_count += 1
       else:
           special_count += 1

   if lower_count >= 1:
       strength += 1
   if upper_count >= 1:
       strength += 1
   if num_count >= 1:
       strength += 1
   if wspace_count >= 1:
       strength += 1
   if special_count >= 1:
       strength += 1

   if strength == 1:
       remarks = ('That\'s a very bad password.'
           ' Change it as soon as possible.')
   elif strength == 2:
       remarks = ('That\'s a weak password.'
           ' You should consider using a tougher password.')
   elif strength == 3:
       remarks = 'Your password is okay, but it can be improved.'
   elif strength == 4:
       remarks = ('Your password is hard to guess.'
           ' But you could make it even more secure.')
   elif strength == 5:
       remarks = ('Now that\'s one hell of a strong password!!!'
           ' Hackers don\'t have a chance guessing that password!')

   print('Your password has:-')
   print(f'{lower_count} lowercase letters')
   print(f'{upper_count} uppercase letters')
   print(f'{num_count} digits')
   print(f'{wspace_count} whitespaces')
   print(f'{special_count} special characters')
   print(f'Password Score: {strength / 5}')
   print(f'Remarks: {remarks}')


def check_pwd(another_pw=False):
   valid = False
   if another_pw:
       choice = input(
           'Do you want to check another password\'s strength (y/n) : ')
   else:
       choice = input(
           'Do you want to check your password\'s strength (y/n) : ')

   while not valid:
       if choice.lower() == 'y':
           return True
       elif choice.lower() == 'n':
           print('Exiting...')
           return False
       else:
           print('Invalid input...please try again. \n')


if __name__ == '__main__':
   print('===== Welcome to Password Strength Checker =====')
   check_pw = check_pwd()
   while check_pw:
       check_password_strength()
       check_pw = check_pwd(True)

7. Angka ke Kata

Ide proyek Python ini mengonversi bilangan bulat yang disediakan melalui input pengguna menjadi kata-kata yang setara. Program ini diatur untuk mendukung angka dengan maksimal 12 digit, tetapi silakan memodifikasi program untuk menangani angka yang lebih besar (petunjuk. membutuhkan pernyataan kondisional dan loop)

Sebagai contoh proyek Python dasar yang mudah dipahami, program sederhana namun efektif ini dapat memperluas keterampilan Anda dengan loop, input pengguna, dan pernyataan bersyarat, belum lagi tupel dan daftar Python

Anda juga dapat bereksperimen dengan beberapa operasi matematika yang mungkin baru bagi Anda, seperti operator modulo (%) untuk mengembalikan sisa dari pembagian bilangan bulat

Kode sumber

'''
Numbers To Words
-------------------------------------------------------------
'''


ones = (
   'Zero', 'One', 'Two', 'Three', 'Four',
   'Five', 'Six', 'Seven', 'Eight', 'Nine'
   )

twos = (
   'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen',
    'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'
   )

tens = (
   'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty',
    'Seventy', 'Eighty', 'Ninety', 'Hundred'
   )

suffixes = (
   '', 'Thousand', 'Million', 'Billion'
   )

def fetch_words(number, index):
   if number == '0': return 'Zero'

   number = number.zfill(3)
   hundreds_digit = int(number[0])
   tens_digit = int(number[1])
   ones_digit = int(number[2])

   words = '' if number[0] == '0' else ones[hundreds_digit]
  
   if words != '':
       words += ' Hundred '

   if tens_digit > 1:
       words += tens[tens_digit - 2]
       words += ' '
       words += ones[ones_digit]
   elif(tens_digit == 1):
       words += twos[((tens_digit + ones_digit) % 10) - 1]
   elif(tens_digit == 0):
       words += ones[ones_digit]

   if(words.endswith('Zero')):
       words = words[:-len('Zero')]
   else:
       words += ' '

   if len(words) != 0:
       words += suffixes[index]
      
   return words


def convert_to_words(number):
   length = len(str(number))
   if length > 12:
       return 'This program supports a maximum of 12 digit numbers.'

   count = length // 3 if length % 3 == 0 else length // 3 + 1
   copy = count
   words = []

   for i in range(length - 1, -1, -3):
       words.append(fetch_words(
           str(number)[0 if i - 2 < 0 else i - 2 : i + 1], copy - count))
      
       count -= 1

   final_words = ''
   for s in reversed(words):
       final_words += (s + ' ')

   return final_words

if __name__ == '__main__':
   number = int(input('Enter any number: '))
   print('%d in words is: %s' %(number, convert_to_words(number)))
_

8. Tic-Tac-Toe

Tic-Tac-Toe adalah permainan dua pemain klasik yang melibatkan kotak sembilan persegi. Setiap pemain secara bergantian menandai ruang mereka dengan O atau X, dan pemain mana pun yang berhasil menandai tiga Os atau X secara diagonal, horizontal, atau vertikal menang. Setiap pemain juga harus memblokir lawan mereka saat mencoba membuat rantai mereka

Ini adalah salah satu proyek Python paling menyenangkan yang juga unik untuk pemula karena menggunakan pemrograman berorientasi objek untuk membuat kelas baru bernama TicTacToe. Kami menggunakan ini untuk merepresentasikan fitur game melalui atribut dan metode kelas

Pelajari metode ini dengan saksama untuk melihat bagaimana kita dapat menggunakan pemrograman berorientasi objek untuk mengemas dengan rapi berbagai perilaku yang diperlukan untuk mensimulasikan game ini

Beberapa aspek baru dari ide proyek Python untuk pemula ini termasuk loop bersarang untuk memeriksa kolom, baris, dan diagonal grid untuk status pemenang, bersama dengan tipe data kumpulan Python, yang digunakan untuk memuat nilai unik. Program ini juga menggunakan modul acak Python untuk memilih pemain acak untuk memulai permainan, tetapi ini lebih familiar bagi Anda sekarang

Kode sumber

'''
Tic Tac Toe
-------------------------------------------------------------
'''


import random


class TicTacToe:

   def __init__(self):
       self.board = []

   def create_board(self):
       for i in range(3):
           row = []
           for j in range(3):
               row.append('-')
           self.board.append(row)

   def get_random_first_player(self):
       return random.randint(0, 1)

   def fix_spot(self, row, col, player):
       self.board[row][col] = player

   def has_player_won(self, player):
       n = len(self.board)
       board_values = set()

       # check rows
       for i in range(n):
           for j in range(n):
               board_values.add(self.board[i][j])

           if board_values == {player}:
               return True
           else:
               board_values.clear()

       # check cols
       for i in range(n):
           for j in range(n):
               board_values.add(self.board[j][i])

           if board_values == {player}:
               return True
           else:
               board_values.clear()

       # check diagonals
       for i in range(n):
           board_values.add(self.board[i][i])
       if board_values == {player}:
           return True
       else:
           board_values.clear()
      
       board_values.add(self.board[0][2])
       board_values.add(self.board[1][1])
       board_values.add(self.board[2][0])
       if board_values == {player}:
           return True
       else:
           return False

   def is_board_filled(self):
       for row in self.board:
           for item in row:
               if item == '-':
                   return False
       return True

   def swap_player_turn(self, player):
       return 'X' if player == 'O' else 'O'

   def show_board(self):
       for row in self.board:
           for item in row:
               print(item, end=' ')
           print()

   def start(self):
       self.create_board()
       player = 'X' if self.get_random_first_player() == 1 else 'O'
       game_over = False

       while not game_over:
           try:
               self.show_board()
               print(f'\nPlayer {player} turn')

               row, col = list(
                   map(int, input(
                       'Enter row & column numbers to fix spot: ').split()))
               print()

               if col is None:
                   raise ValueError(
                       'not enough values to unpack (expected 2, got 1)')

               self.fix_spot(row - 1, col - 1, player)

               game_over = self.has_player_won(player)
               if game_over:
                   print(f'Player {player} wins the game!')
                   continue

               game_over = self.is_board_filled()
               if game_over:
                   print('Match Draw!')
                   continue

               player = self.swap_player_turn(player)

           except ValueError as err:
               print(err)

       print()
       self.show_board()


if __name__ == '__main__':
  tic_tac_toe = TicTacToe()
  tic_tac_toe.start()

9. Kalkulator

Sebagai salah satu proyek Python yang mudah, program ini membuat aplikasi kalkulator dasar dengan fungsi penjumlahan, pengurangan, perkalian, dan pembagian

Ini adalah salah satu proyek latihan Python yang bagus untuk mempelajari cara menggunakan loop, fungsi, pernyataan kondisional, input pengguna, dan pemformatan string. Kami juga menggunakan modul Python os untuk membersihkan layar setelah pengguna menyelesaikan tindakan kalkulasinya

Kode sampel

'''
Calculator
-------------------------------------------------------------
'''


import os


def addition():
   os.system('cls' if os.name == 'nt' else 'clear')
   print('Addition')

   continue_calc = 'y'

   num_1 = float(input('Enter a number: '))
   num_2 = float(input('Enter another number: '))
   ans = num_1 + num_2
   values_entered = 2
   print(f'Current result: {ans}')

   while continue_calc.lower() == 'y':
       continue_calc = (input('Enter more (y/n): '))
       while continue_calc.lower() not in ['y', 'n']:
           print('Please enter \'y\' or \'n\'')
           continue_calc = (input('Enter more (y/n): '))

       if continue_calc.lower() == 'n':
           break
       num = float(input('Enter another number: '))
       ans += num
       print(f'Current result: {ans}')
       values_entered += 1
   return [ans, values_entered]


def subtraction():
   os.system('cls' if os.name == 'nt' else 'clear')
   print('Subtraction')

   continue_calc = 'y'

   num_1 = float(input('Enter a number: '))
   num_2 = float(input('Enter another number: '))
   ans = num_1 - num_2
   values_entered = 2
   print(f'Current result: {ans}')

   while continue_calc.lower() == 'y':
       continue_calc = (input('Enter more (y/n): '))
       while continue_calc.lower() not in ['y', 'n']:
           print('Please enter \'y\' or \'n\'')
           continue_calc = (input('Enter more (y/n): '))

       if continue_calc.lower() == 'n':
           break
       num = float(input('Enter another number: '))
       ans -= num
       print(f'Current result: {ans}')
       values_entered += 1
   return [ans, values_entered]


def multiplication():
   os.system('cls' if os.name == 'nt' else 'clear')
   print('Multiplication')

   continue_calc = 'y'

   num_1 = float(input('Enter a number: '))
   num_2 = float(input('Enter another number: '))
   ans = num_1 * num_2
   values_entered = 2
   print(f'Current result: {ans}')

   while continue_calc.lower() == 'y':
       continue_calc = (input('Enter more (y/n): '))
       while continue_calc.lower() not in ['y', 'n']:
           print('Please enter \'y\' or \'n\'')
           continue_calc = (input('Enter more (y/n): '))

       if continue_calc.lower() == 'n':
           break
       num = float(input('Enter another number: '))
       ans *= num
       print(f'Current result: {ans}')
       values_entered += 1
   return [ans, values_entered]


def division():
   os.system('cls' if os.name == 'nt' else 'clear')
   print('Division')

   continue_calc = 'y'

   num_1 = float(input('Enter a number: '))
   num_2 = float(input('Enter another number: '))
   while num_2 == 0.0:
       print('Please enter a second number > 0')
       num_2 = float(input('Enter another number: '))

   ans = num_1 / num_2
   values_entered = 2
   print(f'Current result: {ans}')

   while continue_calc.lower() == 'y':
       continue_calc = (input('Enter more (y/n): '))
       while continue_calc.lower() not in ['y', 'n']:
           print('Please enter \'y\' or \'n\'')
           continue_calc = (input('Enter more (y/n): '))

       if continue_calc.lower() == 'n':
           break
       num = float(input('Enter another number: '))
       while num == 0.0:
           print('Please enter a number > 0')
           num = float(input('Enter another number: '))
       ans /= num
       print(f'Current result: {ans}')
       values_entered += 1
   return [ans, values_entered]


def calculator():
   quit = False
   while not quit:
       results = []
       print('Simple Calculator in Python!')
       print('Enter \'a\' for addition')
       print('Enter \'s\' for substraction')
       print('Enter \'m\' for multiplication')
       print('Enter \'d\' for division')
       print('Enter \'q\' to quit')

       choice = input('Selection: ')

       if choice == 'q':
           quit = True
           continue

       if choice == 'a':
           results = addition()
           print('Ans = ', results[0], ' total inputs: ', results[1])
       elif choice == 's':
           results = subtraction()
           print('Ans = ', results[0], ' total inputs: ', results[1])
       elif choice == 'm':
           results = multiplication()
           print('Ans = ', results[0], ' total inputs: ', results[1])
       elif choice == 'd':
           results = division()
           print('Ans = ', results[0], ' total inputs: ', results[1])
       else:
           print('Sorry, invalid character')


if __name__ == '__main__':
   calculator()
_

10. Jam dan Timer Hitung Mundur

Ide proyek Python ini menyenangkan. Di sini, kami telah membuat penghitung waktu mundur yang menanyakan beberapa detik kepada pengguna melalui input pengguna, dan kemudian menghitung mundur, detik demi detik, hingga menampilkan pesan

Kami telah menggunakan modul waktu Python. fungsi sleep() untuk menjeda selama interval 1 detik. Kami menggabungkan ini dengan beberapa pemformatan string yang bagus untuk menghasilkan tampilan hitung mundur

Kode sumber

'''
Countdown Timer
-------------------------------------------------------------
'''


import time


def countdown(user_time):
   while user_time >= 0:
       mins, secs = divmod(user_time, 60)
       timer = '{:02d}:{:02d}'.format(mins, secs)
       print(timer, end='\r')
       time.sleep(1)
       user_time -= 1
   print('Lift off!')


if __name__ == '__main__':
   user_time = int(input("Enter a time in seconds: "))
   countdown(user_time)
_

11. Algoritma Pencarian Biner

Ini adalah ritus peralihan untuk semua pembuat kode yang bercita-cita tinggi untuk menangani Pencarian Biner di salah satu proyek pemrograman Python mereka di beberapa titik

Proyek Python untuk pencarian biner ini mengambil daftar yang diurutkan (array), lalu terus membandingkan nilai pencarian dengan bagian tengah array

Bergantung pada apakah nilai pencarian kurang dari atau lebih besar dari nilai tengah, daftar dibagi (strategi bagi dan taklukkan) untuk mengurangi ruang pencarian, yang berfokus pada nilai pencarian yang diberikan. Pembagian terus-menerus ini menghasilkan kompleksitas waktu logaritmik

Jika Anda melihat kode di bawah, Anda akan melihat bahwa kami telah menerapkan dua solusi. loop bersyarat dan rekursi. Kedua pendekatan itu elegan, jadi jangan ragu untuk bereksperimen dengan masing-masing pendekatan

Jika Anda baru mengenal rekursi, ini adalah pengantar yang bagus karena menunjukkan bagaimana kami 'mengurangi' ukuran masalah dengan setiap panggilan rekursif, yaitu dengan membagi daftar ke satu sisi elemen tengah saat ini

Kami juga telah mendefinisikan kasus dasar rekursif sebagai titik saat elemen tengah sama dengan elemen penelusuran. Dalam hal ini, rekursi akan berhenti dan mengembalikan nilai True ke atas melalui tumpukan panggilan

Kode sumber

'''
Number Guessing Game
-------------------------------------------------------------
'''

import random

attempts_list = []


def show_score():
  if not attempts_list:
      print('There is currently no high score, it\'s yours for the taking!')

  else:
      print(f'The current high score is {min(attempts_list)} attempts')


def start_game():
   attempts = 0
   rand_num = random.randint(1, 10)
   print('Hello traveler! Welcome to the game of guesses!')
   player_name = input('What is your name? ')
   wanna_play = input(
       f'Hi, {player_name}, would you like to play the guessing game?'
       '(Enter Yes/No): ')

   if wanna_play.lower() != 'yes':
      print('That\'s cool, Thanks!')
      exit()
   else:
       show_score()

   while wanna_play.lower() == 'yes':
       try:
           guess = int(input('Pick a number between 1 and 10: '))
           if guess < 1 or guess > 10:
               raise ValueError(
                   'Please guess a number within the given range')

           attempts += 1
           attempts_list.append(attempts)

           if guess == rand_num:
               print('Nice! You got it!')
               print(f'It took you {attempts} attempts')
               wanna_play = input(
                   'Would you like to play again? (Enter Yes/No): ')
               if wanna_play.lower() != 'yes':
                   print('That\'s cool, have a good one!')
                   break
               else:
                   attempts = 0
                   rand_num = random.randint(1, 10)
                   show_score()
                   continue
           else:
               if guess > rand_num:
                   print('It\'s lower')
               elif guess < rand_num:
                   print('It\'s higher')

       except ValueError as err:
           print('Oh no!, that is not a valid value. Try again...')
           print(err)


if __name__ == '__main__':
   start_game()

_0

12. Menggabungkan Algoritma Sortir

Merge Sort adalah tantangan pengkodean populer lainnya yang dihadapi oleh calon pembuat kode saat mencari hal yang dapat dilakukan dengan Python

Strategi bagi-dan-taklukkan ini menggunakan pembagian untuk memisahkan daftar angka menjadi bagian yang sama, dan ini kemudian diurutkan secara rekursif sebelum digabungkan kembali untuk menghasilkan daftar yang diurutkan

Jika Anda baru saja menyelesaikan contoh Pencarian Biner, Anda mungkin melihat beberapa kesamaan dengan pembagian dan pengurangan ukuran masalah. Anda benar, yang berarti Anda mungkin menyadari bahwa kita perlu menggunakan rekursi

Implementasi Merge Sort Python ini menggunakan rekursi untuk menangani proses pembagian dan penaklukan. Pengurangan ukuran masalah secara terus-menerus memungkinkan masalah diselesaikan ketika kasus dasar rekursif tercapai, yaitu ketika ukuran masalah adalah satu elemen atau kurang.

Intinya, program Python ini terus membagi daftar secara rekursif hingga mencapai kasus dasar. Pada titik ini mulai menyortir bagian yang lebih kecil dari masalah, menghasilkan larik terurut yang lebih kecil yang digabungkan kembali untuk akhirnya menghasilkan larik terurut sepenuhnya. Jika Anda terbiasa dengan notasi Big O, Anda akan penasaran untuk mengetahui bahwa Merge Sort memiliki Big O dari (n logn)

Kode sumber

'''
Number Guessing Game
-------------------------------------------------------------
'''

import random

attempts_list = []


def show_score():
  if not attempts_list:
      print('There is currently no high score, it\'s yours for the taking!')

  else:
      print(f'The current high score is {min(attempts_list)} attempts')


def start_game():
   attempts = 0
   rand_num = random.randint(1, 10)
   print('Hello traveler! Welcome to the game of guesses!')
   player_name = input('What is your name? ')
   wanna_play = input(
       f'Hi, {player_name}, would you like to play the guessing game?'
       '(Enter Yes/No): ')

   if wanna_play.lower() != 'yes':
      print('That\'s cool, Thanks!')
      exit()
   else:
       show_score()

   while wanna_play.lower() == 'yes':
       try:
           guess = int(input('Pick a number between 1 and 10: '))
           if guess < 1 or guess > 10:
               raise ValueError(
                   'Please guess a number within the given range')

           attempts += 1
           attempts_list.append(attempts)

           if guess == rand_num:
               print('Nice! You got it!')
               print(f'It took you {attempts} attempts')
               wanna_play = input(
                   'Would you like to play again? (Enter Yes/No): ')
               if wanna_play.lower() != 'yes':
                   print('That\'s cool, have a good one!')
                   break
               else:
                   attempts = 0
                   rand_num = random.randint(1, 10)
                   show_score()
                   continue
           else:
               if guess > rand_num:
                   print('It\'s lower')
               elif guess < rand_num:
                   print('It\'s higher')

       except ValueError as err:
           print('Oh no!, that is not a valid value. Try again...')
           print(err)


if __name__ == '__main__':
   start_game()

_1

13. Pembuat Kata Sandi

Ini adalah proyek Python yang menarik yang menggunakan modul rahasia dan string untuk menghasilkan kata sandi yang kuat dan aman, seperti yang Anda bisa dengan pengelola kata sandi populer

Modul string mendapatkan semua kemungkinan huruf, angka, dan karakter khusus, sedangkan modul rahasia memungkinkan kita mendapatkan kata sandi yang aman secara kriptografis

Kode untuk proyek ini relatif sederhana karena menggunakan loop untuk terus menghasilkan kata sandi hingga berisi setidaknya satu karakter khusus dan dua digit. Anda tentu saja dapat memodifikasi ini agar sesuai dengan aturan kata sandi super kuat Anda sendiri

Kode sumber

'''
Number Guessing Game
-------------------------------------------------------------
'''

import random

attempts_list = []


def show_score():
  if not attempts_list:
      print('There is currently no high score, it\'s yours for the taking!')

  else:
      print(f'The current high score is {min(attempts_list)} attempts')


def start_game():
   attempts = 0
   rand_num = random.randint(1, 10)
   print('Hello traveler! Welcome to the game of guesses!')
   player_name = input('What is your name? ')
   wanna_play = input(
       f'Hi, {player_name}, would you like to play the guessing game?'
       '(Enter Yes/No): ')

   if wanna_play.lower() != 'yes':
      print('That\'s cool, Thanks!')
      exit()
   else:
       show_score()

   while wanna_play.lower() == 'yes':
       try:
           guess = int(input('Pick a number between 1 and 10: '))
           if guess < 1 or guess > 10:
               raise ValueError(
                   'Please guess a number within the given range')

           attempts += 1
           attempts_list.append(attempts)

           if guess == rand_num:
               print('Nice! You got it!')
               print(f'It took you {attempts} attempts')
               wanna_play = input(
                   'Would you like to play again? (Enter Yes/No): ')
               if wanna_play.lower() != 'yes':
                   print('That\'s cool, have a good one!')
                   break
               else:
                   attempts = 0
                   rand_num = random.randint(1, 10)
                   show_score()
                   continue
           else:
               if guess > rand_num:
                   print('It\'s lower')
               elif guess < rand_num:
                   print('It\'s higher')

       except ValueError as err:
           print('Oh no!, that is not a valid value. Try again...')
           print(err)


if __name__ == '__main__':
   start_game()

_2

14. Konverter mata uang

Ini adalah salah satu dari beberapa ide proyek Python yang mengharuskan kita memasang pustaka Python baru, dalam hal ini, modul permintaan. Ini tidak disertakan dengan pustaka standar Python, jadi gunakan perintah pip yang ditunjukkan dalam kode sumber untuk menginstalnya di sistem Anda

Dengan modul permintaan, kami dapat membuat permintaan HTTP ke API Fixer, memungkinkan kami untuk mengonversi satu mata uang ke mata uang lainnya. Anda mungkin akan melihat bahwa kami menggunakan API pihak ke-3, jadi Anda harus mendaftar untuk mendapatkan kunci API gratis. Anda kemudian dapat memasukkan kunci API Anda ke dalam bidang yang ditampilkan dalam kode sumber, dan Anda siap untuk pergi

Proyek ini memungkinkan Anda untuk mendapatkan lebih banyak latihan dengan loop dan input pengguna, tetapi ini diperluas dengan permintaan HTTP untuk mengambil data API dalam format JSON

Jika Anda tidak terbiasa dengan JSON, ini sangat mirip dengan kamus Python, artinya kita dapat mengakses key-value pair untuk mengambil data yang kita cari. Dalam hal ini, kami mencari hasil konversi mata uang dari panggilan API

Lihatlah dokumen di situs Fixer API untuk detail lebih lanjut tentang berbagai data yang dapat Anda ambil

Kode sumber

'''
Number Guessing Game
-------------------------------------------------------------
'''

import random

attempts_list = []


def show_score():
  if not attempts_list:
      print('There is currently no high score, it\'s yours for the taking!')

  else:
      print(f'The current high score is {min(attempts_list)} attempts')


def start_game():
   attempts = 0
   rand_num = random.randint(1, 10)
   print('Hello traveler! Welcome to the game of guesses!')
   player_name = input('What is your name? ')
   wanna_play = input(
       f'Hi, {player_name}, would you like to play the guessing game?'
       '(Enter Yes/No): ')

   if wanna_play.lower() != 'yes':
      print('That\'s cool, Thanks!')
      exit()
   else:
       show_score()

   while wanna_play.lower() == 'yes':
       try:
           guess = int(input('Pick a number between 1 and 10: '))
           if guess < 1 or guess > 10:
               raise ValueError(
                   'Please guess a number within the given range')

           attempts += 1
           attempts_list.append(attempts)

           if guess == rand_num:
               print('Nice! You got it!')
               print(f'It took you {attempts} attempts')
               wanna_play = input(
                   'Would you like to play again? (Enter Yes/No): ')
               if wanna_play.lower() != 'yes':
                   print('That\'s cool, have a good one!')
                   break
               else:
                   attempts = 0
                   rand_num = random.randint(1, 10)
                   show_score()
                   continue
           else:
               if guess > rand_num:
                   print('It\'s lower')
               elif guess < rand_num:
                   print('It\'s higher')

       except ValueError as err:
           print('Oh no!, that is not a valid value. Try again...')
           print(err)


if __name__ == '__main__':
   start_game()

_3

15. Pengiriman Surat Ulang Tahun Otomatis

Proyek Python ini menggunakan modul smtplib, EmailMessage, dan datetime standar, selain panda dan openpyxl (ini harus diinstal pip, seperti yang ditunjukkan di bawah) untuk mengirim email ulang tahun otomatis

Program ini membaca dari lembar excel yang berisi semua detail teman Anda (lihat format lembar excel dalam kode sumber di bawah). Kemudian mengirimi mereka email jika hari ini adalah hari besar mereka, sebelum membuat catatan di spreadsheet Anda untuk mengatakan bahwa mereka telah menerima email mereka

Kami telah menggunakan modul smtplib dan EmailMessage untuk membuat koneksi SSL ke akun dan pesan email kami. Kami kemudian menggunakan kerangka data panda untuk menyimpan data gaya spreadsheet dalam program Python (keterampilan penting bagi ilmuwan data). Terakhir, kami menggunakan pemformatan tanggal dengan modul datetime. fungsi strftime()

Jadi, banyak keterampilan baru yang harus dikuasai

Catatan penting. sejak Mei 2022, Google telah memperketat pembatasan pada 'aplikasi kurang aman' yang mengakses Gmail. Anda harus mengikuti beberapa langkah tambahan untuk menggunakan kode ini dengan akun Gmail Anda. Tapi jangan khawatir, itu mudah dilakukan, dan kami telah mendaftarkannya untuk Anda

  • Buka halaman 'kelola akun' untuk akun google Anda
  • Klik Keamanan
  • Aktifkan 2FA (gunakan metode mana pun yang Anda suka)
  • Klik 'Kata Sandi Aplikasi'
  • Klik 'Pilih Aplikasi' dan pilih 'Mail'
  • Klik 'Pilih Perangkat' dan pilih 'Lainnya (nama khusus)', masukkan 'Aplikasi Ulang Tahun Python'
  • Klik 'Hasilkan' lalu simpan kata sandi ini

Anda sekarang dapat menggunakan kata sandi aplikasi ini dalam kode di bawah ini untuk mengakses akun Gmail Anda tanpa kesulitan

Kode sumber

'''
Number Guessing Game
-------------------------------------------------------------
'''

import random

attempts_list = []


def show_score():
  if not attempts_list:
      print('There is currently no high score, it\'s yours for the taking!')

  else:
      print(f'The current high score is {min(attempts_list)} attempts')


def start_game():
   attempts = 0
   rand_num = random.randint(1, 10)
   print('Hello traveler! Welcome to the game of guesses!')
   player_name = input('What is your name? ')
   wanna_play = input(
       f'Hi, {player_name}, would you like to play the guessing game?'
       '(Enter Yes/No): ')

   if wanna_play.lower() != 'yes':
      print('That\'s cool, Thanks!')
      exit()
   else:
       show_score()

   while wanna_play.lower() == 'yes':
       try:
           guess = int(input('Pick a number between 1 and 10: '))
           if guess < 1 or guess > 10:
               raise ValueError(
                   'Please guess a number within the given range')

           attempts += 1
           attempts_list.append(attempts)

           if guess == rand_num:
               print('Nice! You got it!')
               print(f'It took you {attempts} attempts')
               wanna_play = input(
                   'Would you like to play again? (Enter Yes/No): ')
               if wanna_play.lower() != 'yes':
                   print('That\'s cool, have a good one!')
                   break
               else:
                   attempts = 0
                   rand_num = random.randint(1, 10)
                   show_score()
                   continue
           else:
               if guess > rand_num:
                   print('It\'s lower')
               elif guess < rand_num:
                   print('It\'s higher')

       except ValueError as err:
           print('Oh no!, that is not a valid value. Try again...')
           print(err)


if __name__ == '__main__':
   start_game()

_4

16. Antre

Proyek Python ini membuat kelas baru untuk mengimplementasikan Queue. Ini adalah struktur data umum dalam ilmu komputer saat Anda perlu menangani skenario First-In-First-Out (FIFO), seperti antrean pesan, tugas CPU, dll.

Kodenya mudah dan menawarkan lebih banyak latihan dengan pemrograman berorientasi objek. Uji antrean untuk mengetahui cara kerjanya, lalu Anda akan siap menggunakan struktur data ini di proyek Anda yang lain

Kode sumber

'''
Number Guessing Game
-------------------------------------------------------------
'''

import random

attempts_list = []


def show_score():
  if not attempts_list:
      print('There is currently no high score, it\'s yours for the taking!')

  else:
      print(f'The current high score is {min(attempts_list)} attempts')


def start_game():
   attempts = 0
   rand_num = random.randint(1, 10)
   print('Hello traveler! Welcome to the game of guesses!')
   player_name = input('What is your name? ')
   wanna_play = input(
       f'Hi, {player_name}, would you like to play the guessing game?'
       '(Enter Yes/No): ')

   if wanna_play.lower() != 'yes':
      print('That\'s cool, Thanks!')
      exit()
   else:
       show_score()

   while wanna_play.lower() == 'yes':
       try:
           guess = int(input('Pick a number between 1 and 10: '))
           if guess < 1 or guess > 10:
               raise ValueError(
                   'Please guess a number within the given range')

           attempts += 1
           attempts_list.append(attempts)

           if guess == rand_num:
               print('Nice! You got it!')
               print(f'It took you {attempts} attempts')
               wanna_play = input(
                   'Would you like to play again? (Enter Yes/No): ')
               if wanna_play.lower() != 'yes':
                   print('That\'s cool, have a good one!')
                   break
               else:
                   attempts = 0
                   rand_num = random.randint(1, 10)
                   show_score()
                   continue
           else:
               if guess > rand_num:
                   print('It\'s lower')
               elif guess < rand_num:
                   print('It\'s higher')

       except ValueError as err:
           print('Oh no!, that is not a valid value. Try again...')
           print(err)


if __name__ == '__main__':
   start_game()

_5

17. Segitiga Pascal

Proyek Python ini mencetak Segitiga Pascal dengan menggunakan pernyataan bersyarat dan loop. Itu juga menggunakan modul matematika perpustakaan standar dan fungsi faktorial untuk mengevaluasi persamaan 'jumlah kombinasi' yang digunakan untuk menghasilkan nilai dalam segitiga

Bereksperimenlah dengan nomor benih untuk segitiga untuk memeriksa bagaimana persamaan 'kombinasi' digunakan untuk menghasilkan nilai yang berurutan dalam segitiga.  

Kode sumber

'''
Number Guessing Game
-------------------------------------------------------------
'''

import random

attempts_list = []


def show_score():
  if not attempts_list:
      print('There is currently no high score, it\'s yours for the taking!')

  else:
      print(f'The current high score is {min(attempts_list)} attempts')


def start_game():
   attempts = 0
   rand_num = random.randint(1, 10)
   print('Hello traveler! Welcome to the game of guesses!')
   player_name = input('What is your name? ')
   wanna_play = input(
       f'Hi, {player_name}, would you like to play the guessing game?'
       '(Enter Yes/No): ')

   if wanna_play.lower() != 'yes':
      print('That\'s cool, Thanks!')
      exit()
   else:
       show_score()

   while wanna_play.lower() == 'yes':
       try:
           guess = int(input('Pick a number between 1 and 10: '))
           if guess < 1 or guess > 10:
               raise ValueError(
                   'Please guess a number within the given range')

           attempts += 1
           attempts_list.append(attempts)

           if guess == rand_num:
               print('Nice! You got it!')
               print(f'It took you {attempts} attempts')
               wanna_play = input(
                   'Would you like to play again? (Enter Yes/No): ')
               if wanna_play.lower() != 'yes':
                   print('That\'s cool, have a good one!')
                   break
               else:
                   attempts = 0
                   rand_num = random.randint(1, 10)
                   show_score()
                   continue
           else:
               if guess > rand_num:
                   print('It\'s lower')
               elif guess < rand_num:
                   print('It\'s higher')

       except ValueError as err:
           print('Oh no!, that is not a valid value. Try again...')
           print(err)


if __name__ == '__main__':
   start_game()

_6

18. Selikuran

Sebagai salah satu proyek Python paling keren, ini akan menarik bagi siapa saja yang menyukai permainan kartu, karena kami akan meniru Blackjack. Ini adalah permainan kartu yang sangat populer dengan aturan yang relatif sederhana. yang paling penting adalah Anda membutuhkan 21 untuk menang, atau Anda membutuhkan skor lebih tinggi dari dealer tanpa bangkrut

Ini adalah proyek terbesar dalam daftar sejauh ini. Ini menggabungkan sebagian besar keterampilan yang telah kita bahas dalam proyek sebelumnya, termasuk membuat kelas, loop, pernyataan bersyarat, mengimpor modul, menerima masukan pengguna, dan pemformatan string

Luangkan waktu Anda untuk bekerja melalui bagian yang berbeda dari kode ini, dan hubungkan dengan proyek sebelumnya untuk melihat bagaimana teknik yang berbeda bekerja sama. Tidak ada yang belum pernah Anda lihat sebelumnya;

Dan kita harus mengatakan, cobalah untuk tidak menghabiskan sepanjang hari bermain dengannya. Tapi kami sangat mengerti jika Anda melakukannya

Kode sumber

'''
Number Guessing Game
-------------------------------------------------------------
'''

import random

attempts_list = []


def show_score():
  if not attempts_list:
      print('There is currently no high score, it\'s yours for the taking!')

  else:
      print(f'The current high score is {min(attempts_list)} attempts')


def start_game():
   attempts = 0
   rand_num = random.randint(1, 10)
   print('Hello traveler! Welcome to the game of guesses!')
   player_name = input('What is your name? ')
   wanna_play = input(
       f'Hi, {player_name}, would you like to play the guessing game?'
       '(Enter Yes/No): ')

   if wanna_play.lower() != 'yes':
      print('That\'s cool, Thanks!')
      exit()
   else:
       show_score()

   while wanna_play.lower() == 'yes':
       try:
           guess = int(input('Pick a number between 1 and 10: '))
           if guess < 1 or guess > 10:
               raise ValueError(
                   'Please guess a number within the given range')

           attempts += 1
           attempts_list.append(attempts)

           if guess == rand_num:
               print('Nice! You got it!')
               print(f'It took you {attempts} attempts')
               wanna_play = input(
                   'Would you like to play again? (Enter Yes/No): ')
               if wanna_play.lower() != 'yes':
                   print('That\'s cool, have a good one!')
                   break
               else:
                   attempts = 0
                   rand_num = random.randint(1, 10)
                   show_score()
                   continue
           else:
               if guess > rand_num:
                   print('It\'s lower')
               elif guess < rand_num:
                   print('It\'s higher')

       except ValueError as err:
           print('Oh no!, that is not a valid value. Try again...')
           print(err)


if __name__ == '__main__':
   start_game()

_7

19. Bot Reddit

Proyek Python ini membuat bot reddit otomatis dengan beberapa modul baru, yaitu praw dan enchant (lihat perintah pip install)

Ini adalah konsep yang cukup sederhana karena program memeriksa setiap komentar di subreddit yang dipilih, dan kemudian membalas setiap komentar yang berisi 'frasa pemicu' yang telah ditentukan sebelumnya. Untuk melakukan ini, kami menggunakan modul praw untuk berinteraksi dengan reddit, dan enchant untuk menghasilkan kata-kata yang mirip dengan komentar, memungkinkan kami membuat balasan yang sesuai

Ide ini sangat berguna jika Anda mencari proyek Python untuk mempelajari cara menjawab pertanyaan di subreddit Anda sendiri. Anda hanya perlu memperluas kode ini untuk menyertakan tanggapan otomatis untuk pertanyaan yang telah ditentukan sebelumnya (Anda mungkin telah memperhatikan bahwa kode ini digunakan oleh orang lain di reddit. ).  

Catatan penting. Anda harus memeriksa untuk mendapatkan client_id, client_secret, username, password, dan user_agent. Anda memerlukan informasi ini untuk memberi komentar ke reddit melalui antarmuka API

Kode sumber

'''
Number Guessing Game
-------------------------------------------------------------
'''

import random

attempts_list = []


def show_score():
  if not attempts_list:
      print('There is currently no high score, it\'s yours for the taking!')

  else:
      print(f'The current high score is {min(attempts_list)} attempts')


def start_game():
   attempts = 0
   rand_num = random.randint(1, 10)
   print('Hello traveler! Welcome to the game of guesses!')
   player_name = input('What is your name? ')
   wanna_play = input(
       f'Hi, {player_name}, would you like to play the guessing game?'
       '(Enter Yes/No): ')

   if wanna_play.lower() != 'yes':
      print('That\'s cool, Thanks!')
      exit()
   else:
       show_score()

   while wanna_play.lower() == 'yes':
       try:
           guess = int(input('Pick a number between 1 and 10: '))
           if guess < 1 or guess > 10:
               raise ValueError(
                   'Please guess a number within the given range')

           attempts += 1
           attempts_list.append(attempts)

           if guess == rand_num:
               print('Nice! You got it!')
               print(f'It took you {attempts} attempts')
               wanna_play = input(
                   'Would you like to play again? (Enter Yes/No): ')
               if wanna_play.lower() != 'yes':
                   print('That\'s cool, have a good one!')
                   break
               else:
                   attempts = 0
                   rand_num = random.randint(1, 10)
                   show_score()
                   continue
           else:
               if guess > rand_num:
                   print('It\'s lower')
               elif guess < rand_num:
                   print('It\'s higher')

       except ValueError as err:
           print('Oh no!, that is not a valid value. Try again...')
           print(err)


if __name__ == '__main__':
   start_game()

_8

20. Generator Fibonacci

Angka Fibonacci mungkin merupakan beberapa angka terpenting dalam hidup kita karena sering muncul di alam

Kode Python di bawah menghasilkan angka Fibonacci hingga panjang tertentu menggunakan rekursi (ya, lebih banyak rekursi. ). Untuk menghentikan waktu komputasi yang tidak terkendali, kami telah menerapkan memoisasi ke nilai cache saat kami menghitungnya

Anda akan melihat bahwa untuk algoritme rekursif ini, kasus dasar disetel untuk memeriksa apakah nilai deret Fibonacci yang diberikan sudah disimpan dalam cache. Jika demikian, ini mengembalikan ini (yang merupakan operasi kompleksitas waktu konstan), yang menghemat banyak waktu perhitungan

Kode sumber

'''
Number Guessing Game
-------------------------------------------------------------
'''

import random

attempts_list = []


def show_score():
  if not attempts_list:
      print('There is currently no high score, it\'s yours for the taking!')

  else:
      print(f'The current high score is {min(attempts_list)} attempts')


def start_game():
   attempts = 0
   rand_num = random.randint(1, 10)
   print('Hello traveler! Welcome to the game of guesses!')
   player_name = input('What is your name? ')
   wanna_play = input(
       f'Hi, {player_name}, would you like to play the guessing game?'
       '(Enter Yes/No): ')

   if wanna_play.lower() != 'yes':
      print('That\'s cool, Thanks!')
      exit()
   else:
       show_score()

   while wanna_play.lower() == 'yes':
       try:
           guess = int(input('Pick a number between 1 and 10: '))
           if guess < 1 or guess > 10:
               raise ValueError(
                   'Please guess a number within the given range')

           attempts += 1
           attempts_list.append(attempts)

           if guess == rand_num:
               print('Nice! You got it!')
               print(f'It took you {attempts} attempts')
               wanna_play = input(
                   'Would you like to play again? (Enter Yes/No): ')
               if wanna_play.lower() != 'yes':
                   print('That\'s cool, have a good one!')
                   break
               else:
                   attempts = 0
                   rand_num = random.randint(1, 10)
                   show_score()
                   continue
           else:
               if guess > rand_num:
                   print('It\'s lower')
               elif guess < rand_num:
                   print('It\'s higher')

       except ValueError as err:
           print('Oh no!, that is not a valid value. Try again...')
           print(err)


if __name__ == '__main__':
   start_game()

_9

Ide Proyek Python Tingkat Lanjut

21. Obrolan

Proyek Python ini menggunakan modul chatterbot (lihat instruksi pemasangan pip di bawah) untuk melatih chatbot otomatis untuk menjawab pertanyaan apa pun yang Anda ajukan. Aku tahu;

Anda akan melihat bahwa program ini adalah salah satu proyek Python yang relatif kecil dalam daftar ini, tetapi jangan ragu untuk menjelajahi dokumentasi ChatterBot bersama dengan bidang chatbot AI yang lebih luas jika Anda ingin mempelajari lebih lanjut atau memperluas fitur kode.

Catatan penting. ChatterBot tidak lagi dipelihara secara aktif. Ini berarti Anda perlu melakukan sedikit perubahan pada pemberian tag. py terletak di direktori 'Lib/site-packages/chatterbot' dari folder instalasi Python Anda

Jangan khawatir; .  

Kode sumber

'''
Rock Paper Scissors
-------------------------------------------------------------
'''


import random
import os
import re


def check_play_status():
  valid_responses = ['yes', 'no']
  while True:
      try:
          response = input('Do you wish to play again? (Yes or No): ')
          if response.lower() not in valid_responses:
              raise ValueError('Yes or No only')

          if response.lower() == 'yes':
              return True
          else:
              os.system('cls' if os.name == 'nt' else 'clear')
              print('Thanks for playing!')
              exit()

      except ValueError as err:
          print(err)


def play_rps():
   play = True
   while play:
       os.system('cls' if os.name == 'nt' else 'clear')
       print('')
       print('Rock, Paper, Scissors - Shoot!')

       user_choice = input('Choose your weapon'
                           ' [R]ock], [P]aper, or [S]cissors: ')

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

       print(f'You chose: {user_choice}')

       choices = ['R', 'P', 'S']
       opp_choice = random.choice(choices)

       print(f'I chose: {opp_choice}')

       if opp_choice == user_choice.upper():
           print('Tie!')
           play = check_play_status()
       elif opp_choice == 'R' and user_choice.upper() == 'S':
           print('Rock beats scissors, I win!')
           play = check_play_status()
       elif opp_choice == 'S' and user_choice.upper() == 'P':
           print('Scissors beats paper! I win!')
           play = check_play_status()
       elif opp_choice == 'P' and user_choice.upper() == 'R':
           print('Paper beats rock, I win!')
           play = check_play_status()
       else:
           print('You win!\n')
           play = check_play_status()


if __name__ == '__main__':
   play_rps()
0

Ubah penandaan. py

Temukan cuplikan kode pertama yang merupakan bagian dari metode __init__ untuk kelas PosLemmaTagger. Ganti this dengan pernyataan if/else

Catatan. contoh ini adalah untuk perpustakaan bahasa Inggris yang kami gunakan dalam contoh kami, tetapi jangan ragu untuk mengubahnya ke bahasa lain jika Anda mau

'''
Rock Paper Scissors
-------------------------------------------------------------
'''


import random
import os
import re


def check_play_status():
  valid_responses = ['yes', 'no']
  while True:
      try:
          response = input('Do you wish to play again? (Yes or No): ')
          if response.lower() not in valid_responses:
              raise ValueError('Yes or No only')

          if response.lower() == 'yes':
              return True
          else:
              os.system('cls' if os.name == 'nt' else 'clear')
              print('Thanks for playing!')
              exit()

      except ValueError as err:
          print(err)


def play_rps():
   play = True
   while play:
       os.system('cls' if os.name == 'nt' else 'clear')
       print('')
       print('Rock, Paper, Scissors - Shoot!')

       user_choice = input('Choose your weapon'
                           ' [R]ock], [P]aper, or [S]cissors: ')

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

       print(f'You chose: {user_choice}')

       choices = ['R', 'P', 'S']
       opp_choice = random.choice(choices)

       print(f'I chose: {opp_choice}')

       if opp_choice == user_choice.upper():
           print('Tie!')
           play = check_play_status()
       elif opp_choice == 'R' and user_choice.upper() == 'S':
           print('Rock beats scissors, I win!')
           play = check_play_status()
       elif opp_choice == 'S' and user_choice.upper() == 'P':
           print('Scissors beats paper! I win!')
           play = check_play_status()
       elif opp_choice == 'P' and user_choice.upper() == 'R':
           print('Paper beats rock, I win!')
           play = check_play_status()
       else:
           print('You win!\n')
           play = check_play_status()


if __name__ == '__main__':
   play_rps()
1

22. Teks pidato

Proyek Python ini menggunakan berbagai pustaka baru untuk mengonversi artikel yang sudah ada menjadi file mp3 yang dapat dimainkan. Anda harus menginstal nltk (perangkat bahasa alami), koran3k, dan gtts (lihat petunjuk pemasangan pip)

Anda akan melihat bahwa programnya sederhana, karena kami cukup mengirimkan URL untuk artikel yang akan dikonversi, lalu biarkan fungsi yang telah kami tentukan menangani konversi teks-ke-ucapan dengan modul kami yang baru dipasang

Jadi, pertimbangkan untuk mencoba ini lain kali jika Anda ingin mengubah artikel menjadi podcast yang dapat dimainkan karena ini pasti salah satu kode Python yang keren untuk disalin.  

Kode sumber

'''
Rock Paper Scissors
-------------------------------------------------------------
'''


import random
import os
import re


def check_play_status():
  valid_responses = ['yes', 'no']
  while True:
      try:
          response = input('Do you wish to play again? (Yes or No): ')
          if response.lower() not in valid_responses:
              raise ValueError('Yes or No only')

          if response.lower() == 'yes':
              return True
          else:
              os.system('cls' if os.name == 'nt' else 'clear')
              print('Thanks for playing!')
              exit()

      except ValueError as err:
          print(err)


def play_rps():
   play = True
   while play:
       os.system('cls' if os.name == 'nt' else 'clear')
       print('')
       print('Rock, Paper, Scissors - Shoot!')

       user_choice = input('Choose your weapon'
                           ' [R]ock], [P]aper, or [S]cissors: ')

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

       print(f'You chose: {user_choice}')

       choices = ['R', 'P', 'S']
       opp_choice = random.choice(choices)

       print(f'I chose: {opp_choice}')

       if opp_choice == user_choice.upper():
           print('Tie!')
           play = check_play_status()
       elif opp_choice == 'R' and user_choice.upper() == 'S':
           print('Rock beats scissors, I win!')
           play = check_play_status()
       elif opp_choice == 'S' and user_choice.upper() == 'P':
           print('Scissors beats paper! I win!')
           play = check_play_status()
       elif opp_choice == 'P' and user_choice.upper() == 'R':
           print('Paper beats rock, I win!')
           play = check_play_status()
       else:
           print('You win!\n')
           play = check_play_status()


if __name__ == '__main__':
   play_rps()
2

23. Sistem Manajemen Perpustakaan

Sebagai salah satu proyek Python yang lebih maju, program ini menggunakan pemrograman berorientasi objek untuk mensimulasikan sistem manajemen perpustakaan

Dalam contoh ini, kami membuat kelas Perpustakaan dan Siswa, yang dapat kami gunakan untuk membuat sistem perpustakaan kami dan penggunanya. Kami kemudian menerapkan antarmuka pengguna sederhana yang meminta pengguna untuk memilih dari serangkaian tindakan perpustakaan standar, seperti meminjam atau mengembalikan buku.  

Ini adalah contoh sederhana namun kuat tentang bagaimana Anda dapat membangun sistem dunia nyata melalui Python dan pemrograman berorientasi objek. Jangan ragu untuk memperluas kelas untuk menyertakan fitur berguna lainnya, seperti ID buku unik, banyak salinan dari buku yang sama, tanggal pengembalian, biaya pengembalian buku yang terlambat, atau fitur lain yang menurut Anda harus dimiliki perpustakaan

Kode sumber

'''
Rock Paper Scissors
-------------------------------------------------------------
'''


import random
import os
import re


def check_play_status():
  valid_responses = ['yes', 'no']
  while True:
      try:
          response = input('Do you wish to play again? (Yes or No): ')
          if response.lower() not in valid_responses:
              raise ValueError('Yes or No only')

          if response.lower() == 'yes':
              return True
          else:
              os.system('cls' if os.name == 'nt' else 'clear')
              print('Thanks for playing!')
              exit()

      except ValueError as err:
          print(err)


def play_rps():
   play = True
   while play:
       os.system('cls' if os.name == 'nt' else 'clear')
       print('')
       print('Rock, Paper, Scissors - Shoot!')

       user_choice = input('Choose your weapon'
                           ' [R]ock], [P]aper, or [S]cissors: ')

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

       print(f'You chose: {user_choice}')

       choices = ['R', 'P', 'S']
       opp_choice = random.choice(choices)

       print(f'I chose: {opp_choice}')

       if opp_choice == user_choice.upper():
           print('Tie!')
           play = check_play_status()
       elif opp_choice == 'R' and user_choice.upper() == 'S':
           print('Rock beats scissors, I win!')
           play = check_play_status()
       elif opp_choice == 'S' and user_choice.upper() == 'P':
           print('Scissors beats paper! I win!')
           play = check_play_status()
       elif opp_choice == 'P' and user_choice.upper() == 'R':
           print('Paper beats rock, I win!')
           play = check_play_status()
       else:
           print('You win!\n')
           play = check_play_status()


if __name__ == '__main__':
   play_rps()
_3

24. Permainan Arkade Pong

Ini adalah proyek yang sangat menyenangkan dan menarik karena kami telah menggunakan modul kura-kura Python untuk meniru game arcade klasik Pong

Kami telah menggunakan berbagai metode dari modul turtle untuk membuat komponen permainan kami dan mendeteksi benturan bola dengan dayung pemain. Kami juga telah menetapkan rentang keybinding untuk mengatur kontrol pengguna untuk dayung pemain kiri dan kanan. Jangan ragu untuk bereksperimen dengan pengaturan game untuk lebih memahami cara kerja setiap pengaturan dan memengaruhi game secara keseluruhan

Di luar fungsi grafik penyu yang baru diperkenalkan ini, kami telah menggunakan pemformatan string untuk menampilkan papan skor saat ini dan fungsi yang ditentukan pengguna untuk menjaga kode kami tetap rapi. Ini adalah konsep yang harus Anda ketahui pada tahap ini

Kode sumber

'''
Rock Paper Scissors
-------------------------------------------------------------
'''


import random
import os
import re


def check_play_status():
  valid_responses = ['yes', 'no']
  while True:
      try:
          response = input('Do you wish to play again? (Yes or No): ')
          if response.lower() not in valid_responses:
              raise ValueError('Yes or No only')

          if response.lower() == 'yes':
              return True
          else:
              os.system('cls' if os.name == 'nt' else 'clear')
              print('Thanks for playing!')
              exit()

      except ValueError as err:
          print(err)


def play_rps():
   play = True
   while play:
       os.system('cls' if os.name == 'nt' else 'clear')
       print('')
       print('Rock, Paper, Scissors - Shoot!')

       user_choice = input('Choose your weapon'
                           ' [R]ock], [P]aper, or [S]cissors: ')

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

       print(f'You chose: {user_choice}')

       choices = ['R', 'P', 'S']
       opp_choice = random.choice(choices)

       print(f'I chose: {opp_choice}')

       if opp_choice == user_choice.upper():
           print('Tie!')
           play = check_play_status()
       elif opp_choice == 'R' and user_choice.upper() == 'S':
           print('Rock beats scissors, I win!')
           play = check_play_status()
       elif opp_choice == 'S' and user_choice.upper() == 'P':
           print('Scissors beats paper! I win!')
           play = check_play_status()
       elif opp_choice == 'P' and user_choice.upper() == 'R':
           print('Paper beats rock, I win!')
           play = check_play_status()
       else:
           print('You win!\n')
           play = check_play_status()


if __name__ == '__main__':
   play_rps()
_4

25. Tes Mengetik Kecepatan

Ini adalah proyek Python menarik yang menguji seberapa cepat Anda bisa mengetik kalimat dengan akurat

Program ini mengharuskan kita untuk membuat antarmuka pengguna grafis (GUI) melalui modul tkinter. Jika Anda baru mengenal GUI, contoh ini adalah pengantar yang bagus karena kami menggunakan serangkaian label, tombol, dan bidang entri sederhana untuk membuat jendela. Kami juga telah menggunakan modul timeit Python untuk menangani aspek waktu pengujian pengetikan kami, dan modul acak untuk memilih frase pengujian secara acak

Kami hanya menambahkan dua frasa pengujian ke contoh ini, tetapi jangan ragu untuk bereksperimen dengan lebih banyak atau bahkan mengintegrasikan kamus pihak ketiga untuk rangkaian contoh yang lebih luas

Kode sumber

'''
Rock Paper Scissors
-------------------------------------------------------------
'''


import random
import os
import re


def check_play_status():
  valid_responses = ['yes', 'no']
  while True:
      try:
          response = input('Do you wish to play again? (Yes or No): ')
          if response.lower() not in valid_responses:
              raise ValueError('Yes or No only')

          if response.lower() == 'yes':
              return True
          else:
              os.system('cls' if os.name == 'nt' else 'clear')
              print('Thanks for playing!')
              exit()

      except ValueError as err:
          print(err)


def play_rps():
   play = True
   while play:
       os.system('cls' if os.name == 'nt' else 'clear')
       print('')
       print('Rock, Paper, Scissors - Shoot!')

       user_choice = input('Choose your weapon'
                           ' [R]ock], [P]aper, or [S]cissors: ')

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

       print(f'You chose: {user_choice}')

       choices = ['R', 'P', 'S']
       opp_choice = random.choice(choices)

       print(f'I chose: {opp_choice}')

       if opp_choice == user_choice.upper():
           print('Tie!')
           play = check_play_status()
       elif opp_choice == 'R' and user_choice.upper() == 'S':
           print('Rock beats scissors, I win!')
           play = check_play_status()
       elif opp_choice == 'S' and user_choice.upper() == 'P':
           print('Scissors beats paper! I win!')
           play = check_play_status()
       elif opp_choice == 'P' and user_choice.upper() == 'R':
           print('Paper beats rock, I win!')
           play = check_play_status()
       else:
           print('You win!\n')
           play = check_play_status()


if __name__ == '__main__':
   play_rps()
5

26. Editor Teks

Membangun contoh tkinter terakhir kami, proyek Python yang menyenangkan ini membuat GUI untuk mensimulasikan editor teks kami sendiri. Contoh ini juga menggunakan komponen GUI standar, termasuk label, tombol, dan kolom entri

Namun, kami juga menambahkan kemampuan untuk membuka dan menyimpan file seperti editor teks asli. Jika Anda baru menangani file, proyek Python ini adalah cara yang bagus untuk memahami cara membaca dan menyimpan file

Bereksperimenlah dengan kode di bawah ini untuk memperkuat pemahaman Anda, dan lihat apakah Anda dapat memperluas kode ini untuk membuat fitur lain yang biasa Anda gunakan dengan editor teks, seperti fungsi 'temukan kata'

Kode sumber

'''
Rock Paper Scissors
-------------------------------------------------------------
'''


import random
import os
import re


def check_play_status():
  valid_responses = ['yes', 'no']
  while True:
      try:
          response = input('Do you wish to play again? (Yes or No): ')
          if response.lower() not in valid_responses:
              raise ValueError('Yes or No only')

          if response.lower() == 'yes':
              return True
          else:
              os.system('cls' if os.name == 'nt' else 'clear')
              print('Thanks for playing!')
              exit()

      except ValueError as err:
          print(err)


def play_rps():
   play = True
   while play:
       os.system('cls' if os.name == 'nt' else 'clear')
       print('')
       print('Rock, Paper, Scissors - Shoot!')

       user_choice = input('Choose your weapon'
                           ' [R]ock], [P]aper, or [S]cissors: ')

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

       print(f'You chose: {user_choice}')

       choices = ['R', 'P', 'S']
       opp_choice = random.choice(choices)

       print(f'I chose: {opp_choice}')

       if opp_choice == user_choice.upper():
           print('Tie!')
           play = check_play_status()
       elif opp_choice == 'R' and user_choice.upper() == 'S':
           print('Rock beats scissors, I win!')
           play = check_play_status()
       elif opp_choice == 'S' and user_choice.upper() == 'P':
           print('Scissors beats paper! I win!')
           play = check_play_status()
       elif opp_choice == 'P' and user_choice.upper() == 'R':
           print('Paper beats rock, I win!')
           play = check_play_status()
       else:
           print('You win!\n')
           play = check_play_status()


if __name__ == '__main__':
   play_rps()
6

27. Sudoku Solver

Proyek Python ini menggunakan pustaka pygame (lihat instruksi instalasi pip) untuk mengimplementasikan GUI untuk memecahkan teka-teki sudoku secara otomatis. Kami menggunakan beberapa fungsi yang ditentukan pengguna untuk membuat GUI, seperti yang ditunjukkan di bawah ini

Untuk memecahkan teka-teki sudoku, program ini menggunakan algoritme backtracking yang secara bertahap memeriksa solusi, baik mengadopsi atau meninggalkan solusi saat ini jika tidak dapat dijalankan.

Langkah meninggalkan solusi ini adalah fitur yang menentukan dari pendekatan backtracking, karena program mundur untuk mencoba solusi baru hingga menemukan solusi yang valid. Proses ini dilakukan secara bertahap hingga seluruh grid terisi dengan benar

Jangan ragu untuk bereksperimen dengan masalah sudoku yang berbeda, dan bahkan berpikir untuk memperluas ukuran kisi masalah (Anda memerlukan gambar dasar baru jika melakukan ini)

Kode sumber

'''
Rock Paper Scissors
-------------------------------------------------------------
'''


import random
import os
import re


def check_play_status():
  valid_responses = ['yes', 'no']
  while True:
      try:
          response = input('Do you wish to play again? (Yes or No): ')
          if response.lower() not in valid_responses:
              raise ValueError('Yes or No only')

          if response.lower() == 'yes':
              return True
          else:
              os.system('cls' if os.name == 'nt' else 'clear')
              print('Thanks for playing!')
              exit()

      except ValueError as err:
          print(err)


def play_rps():
   play = True
   while play:
       os.system('cls' if os.name == 'nt' else 'clear')
       print('')
       print('Rock, Paper, Scissors - Shoot!')

       user_choice = input('Choose your weapon'
                           ' [R]ock], [P]aper, or [S]cissors: ')

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

       print(f'You chose: {user_choice}')

       choices = ['R', 'P', 'S']
       opp_choice = random.choice(choices)

       print(f'I chose: {opp_choice}')

       if opp_choice == user_choice.upper():
           print('Tie!')
           play = check_play_status()
       elif opp_choice == 'R' and user_choice.upper() == 'S':
           print('Rock beats scissors, I win!')
           play = check_play_status()
       elif opp_choice == 'S' and user_choice.upper() == 'P':
           print('Scissors beats paper! I win!')
           play = check_play_status()
       elif opp_choice == 'P' and user_choice.upper() == 'R':
           print('Paper beats rock, I win!')
           play = check_play_status()
       else:
           print('You win!\n')
           play = check_play_status()


if __name__ == '__main__':
   play_rps()
7

28. Pemeriksa Konektivitas Situs

Proyek Python ini menggunakan modul urllib dan tkinter untuk menguji konektivitas situs web

Kami telah menggunakan modul tkinter untuk membuat GUI yang memungkinkan pengguna memasukkan alamat web. Sama seperti contoh kami sebelumnya, ini termasuk label, tombol, dan bidang entri

Setelah kami mengumpulkan alamat web pengguna, kami meneruskannya ke fungsi yang ditentukan pengguna kami untuk mengembalikan kode status HTTP untuk situs web saat ini melalui modul urllib. fungsi getcode()

Untuk contoh ini, kami hanya menentukan apakah kode HTTP adalah 200. Jika ya, kami tahu situs tersebut berfungsi;

Anda dapat mengembangkan kode ini untuk mempertimbangkan pendekatan yang lebih terperinci dalam menangani berbagai kode tanggapan HTTP, jadi jangan ragu untuk menambahkan ini

Kode sumber

'''
Rock Paper Scissors
-------------------------------------------------------------
'''


import random
import os
import re


def check_play_status():
  valid_responses = ['yes', 'no']
  while True:
      try:
          response = input('Do you wish to play again? (Yes or No): ')
          if response.lower() not in valid_responses:
              raise ValueError('Yes or No only')

          if response.lower() == 'yes':
              return True
          else:
              os.system('cls' if os.name == 'nt' else 'clear')
              print('Thanks for playing!')
              exit()

      except ValueError as err:
          print(err)


def play_rps():
   play = True
   while play:
       os.system('cls' if os.name == 'nt' else 'clear')
       print('')
       print('Rock, Paper, Scissors - Shoot!')

       user_choice = input('Choose your weapon'
                           ' [R]ock], [P]aper, or [S]cissors: ')

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

       print(f'You chose: {user_choice}')

       choices = ['R', 'P', 'S']
       opp_choice = random.choice(choices)

       print(f'I chose: {opp_choice}')

       if opp_choice == user_choice.upper():
           print('Tie!')
           play = check_play_status()
       elif opp_choice == 'R' and user_choice.upper() == 'S':
           print('Rock beats scissors, I win!')
           play = check_play_status()
       elif opp_choice == 'S' and user_choice.upper() == 'P':
           print('Scissors beats paper! I win!')
           play = check_play_status()
       elif opp_choice == 'P' and user_choice.upper() == 'R':
           print('Paper beats rock, I win!')
           play = check_play_status()
       else:
           print('You win!\n')
           play = check_play_status()


if __name__ == '__main__':
   play_rps()
_8

29. Detektor Bahasa

Proyek Python ini menggunakan modul langdetect (lihat instruksi pemasangan pip) untuk membantu kami mengidentifikasi bahasa yang telah dimasukkan. Ini bisa sangat berguna jika Anda tidak yakin bahasa apa yang Anda gunakan.  

Ini adalah contoh lain di mana kami menggunakan tkinter untuk membuat GUI sederhana yang melibatkan label, tombol, dan bidang entri. Kami kemudian dapat mengumpulkan teks dari bidang entri dan memprosesnya dengan langdetect untuk menentukan bahasa mana yang dimasukkan. Terakhir, kami mencetak hasil ini ke GUI agar pengguna mengetahui hasilnya

Perhatikan bahwa hasil yang dikembalikan oleh langdetect adalah kode bahasa yang disingkat. Misalnya, jika kita memasukkan teks bahasa Inggris, kita akan melihat 'en' sebagai nilai kembaliannya

Kode sumber

'''
Rock Paper Scissors
-------------------------------------------------------------
'''


import random
import os
import re


def check_play_status():
  valid_responses = ['yes', 'no']
  while True:
      try:
          response = input('Do you wish to play again? (Yes or No): ')
          if response.lower() not in valid_responses:
              raise ValueError('Yes or No only')

          if response.lower() == 'yes':
              return True
          else:
              os.system('cls' if os.name == 'nt' else 'clear')
              print('Thanks for playing!')
              exit()

      except ValueError as err:
          print(err)


def play_rps():
   play = True
   while play:
       os.system('cls' if os.name == 'nt' else 'clear')
       print('')
       print('Rock, Paper, Scissors - Shoot!')

       user_choice = input('Choose your weapon'
                           ' [R]ock], [P]aper, or [S]cissors: ')

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

       print(f'You chose: {user_choice}')

       choices = ['R', 'P', 'S']
       opp_choice = random.choice(choices)

       print(f'I chose: {opp_choice}')

       if opp_choice == user_choice.upper():
           print('Tie!')
           play = check_play_status()
       elif opp_choice == 'R' and user_choice.upper() == 'S':
           print('Rock beats scissors, I win!')
           play = check_play_status()
       elif opp_choice == 'S' and user_choice.upper() == 'P':
           print('Scissors beats paper! I win!')
           play = check_play_status()
       elif opp_choice == 'P' and user_choice.upper() == 'R':
           print('Paper beats rock, I win!')
           play = check_play_status()
       else:
           print('You win!\n')
           play = check_play_status()


if __name__ == '__main__':
   play_rps()
_9

30. Sistem Rekomendasi Netflix

Sebagai penutup, kami telah menyimpan proyek Python yang sangat menarik untuk yang terakhir. Ini adalah sistem rekomendasi Netflix, ideal untuk calon ilmuwan data atau penggemar pembelajaran mesin

Untuk membuat proyek ini, Anda perlu mengimpor berbagai modul, termasuk tkinter, re, nltk, panda, dan numpy (lihat petunjuk pemasangan pip untuk modul baru). Anda juga harus mengunduh kumpulan data yang berisi film dan acara TV Netflix dari sini.  

Kami akan menggunakan tkinter untuk membuat GUI kami, yang akan menggunakan label, tombol, dan kolom entri. Pengguna kemudian dapat memasukkan acara TV atau film yang mereka sukai di Netflix untuk mengembalikan rekomendasi berdasarkan selera mereka.  

Mesin rekomendasi menggunakan pemeran, sutradara, peringkat, negara, dan genre sebagai 'fitur' machine learning (ML). Kode kemudian menggunakan pendekatan 'kesamaan cosinus' untuk menemukan hasil yang serupa berdasarkan input pengguna. Ini secara ekstensif menggunakan panda dan numpy untuk membersihkan data dan mempersiapkannya untuk diproses

Ada banyak hal yang harus dibongkar dalam contoh ini. Pendekatan terbaik adalah bekerja perlahan melalui kode dan kemudian melakukan penelitian lebih lanjut tentang Pembelajaran Mesin (ML), 'fitur', dan 'kemiripan kosinus'.  

Anda kemudian akan dapat memahami cara menggunakan kumpulan data untuk mendapatkan rekomendasi berdasarkan kesamaan. Jika Anda seorang ilmuwan data yang bercita-cita tinggi, ini adalah proyek hebat untuk membuat kaki Anda basah

Kode sumber

'''
Dice Roll Generator
-------------------------------------------------------------
'''


import random
import os


def num_die():
  while True:
      try:
          num_dice = input('Number of dice: ')
          valid_responses = ['1', 'one', 'two', '2']
          if num_dice not in valid_responses:
              raise ValueError('1 or 2 only')
          else:
              return num_dice
      except ValueError as err:
          print(err)


def roll_dice():
   min_val = 1
   max_val = 6
   roll_again = 'y'

   while roll_again.lower() == 'yes' or roll_again.lower() == 'y':
       os.system('cls' if os.name == 'nt' else 'clear')
       amount = num_die()

       if amount == '2' or amount == 'two':
           print('Rolling the dice...')
           dice_1 = random.randint(min_val, max_val)
           dice_2 = random.randint(min_val, max_val)

           print('The values are:')
           print('Dice One: ', dice_1)
           print('Dice Two: ', dice_2)
           print('Total: ', dice_1 + dice_2)

           roll_again = input('Roll Again? ')
       else:
           print('Rolling the die...')
           dice_1 = random.randint(min_val, max_val)
           print(f'The value is: {dice_1}')

           roll_again = input('Roll Again? ')


if __name__ == '__main__':
   roll_dice()
0

Kesimpulan

Dan begitulah. Kami telah membahas 30 proyek Python yang keren, menyenangkan, dan mengasyikkan dengan kode sumber, mulai dari yang sederhana hingga yang canggih. Ini termasuk game, pemrograman berorientasi objek, GUI, kecerdasan buatan (AI), pembelajaran mesin (ML), API, bot, modul perpustakaan standar, dan beberapa perpustakaan pihak ke-3

Satu hal yang sama-sama dimiliki oleh masing-masing ide proyek Python ini adalah mereka mengharuskan Anda mempraktikkan pembelajaran Python teoretis Anda. Dengan melakukan ini, Anda dapat menguji diri sendiri dan meningkatkan keterampilan Python Anda saat mengambil langkah untuk menjadi pemrogram praktis yang lebih baik.  

Ingin membangun lebih banyak proyek dengan Python? .  

Pertanyaan yang Sering Diajukan

1. Apakah Python Cocok untuk Proyek Besar?

Meskipun ada argumen bahwa Python lebih lambat daripada bahasa populer lainnya seperti C dan C++, Python masih banyak digunakan oleh banyak perusahaan teknologi terkemuka karena sangat serbaguna, mudah dipelihara, dan menawarkan banyak pustaka dan dukungan dari komunitas.

2. Seperti Apa Proyek Python Pertama Saya?

Lihat salah satu proyek pemula Python yang telah kami bahas di atas, termasuk Mad Libs, Rock Paper Scissors, Hangman, atau Tic-Tac-Toe

Bisakah Python digunakan untuk otomatisasi?

Python sering digunakan di tempat kerja untuk mengotomatiskan dan menjadwalkan pengiriman/penerimaan email dan SMS . Paket Python – email, smtplib, digunakan untuk mengirim email hanya dengan menggunakan Python. Anda dapat mengubah tugas yang memakan waktu menjadi tugas otomatis/terjadwal.

Apa saja proyek Python yang keren?

Ide Proyek Python. Tingkat Pemula .
Buat pembuat kode. .
Buat kalkulator hitung mundur. .
Tulis metode pengurutan. .
Bangun kuis interaktif. .
Tic-Tac-Toe melalui Teks. .
Membuat konverter suhu/pengukuran. .
Bangun aplikasi penghitung. .
Bangun permainan tebak angka

Apa proyek Python termudah?

Tingkat Pemula .
2) Permainan Tic-Tac-Toe. Game Tic-Tac-Toe adalah proyek Python sederhana berdasarkan Game Tic-Tac-Toe yang populer. .
3) Pemotong Email. .
4) Generator Libs Gila. .
5) Game Tebak Angka. .
6) Simulasi Dadu Bergulir. .
7) Game Tebak Kata. .
8) Penghitung Waktu Mundur. .
9) Gambar ke Suara

Bagaimana cara menggunakan kode sumber dengan Python?

getsource() digunakan untuk mendapatkan kode sumber objek Python. .
Sintaksis. memeriksa. getsource(objek)
Parameter. Parameter tipe objek, yang kita inginkan kode sumbernya
Jenis pengembalian. teks kode sumber untuk objek