AI, ML và Khoa học dữ liệu thống trị nhiều lĩnh vực và ngành công nghiệp ngày nay - tất cả chúng đều sử dụng rất nhiều ngôn ngữ lập trình Python theo cách này hay cách khác.
Trở thành bậc thầy về Python có thể mở ra nhiều cánh cửa trong sự nghiệp của bạn và giành được một số cơ hội tốt nhất trên khắp hành tinh. Bất kể bạn tự đánh giá mình ở đâu về kỹ năng Python, làm việc trên các dự án Python là một cách chắc chắn để nâng cao kỹ năng và xây dựng hồ sơ của bạn. Mặc dù sách Python và hướng dẫn Python rất hữu ích, nhưng không có gì có thể khiến bạn bị bẩn tay khi viết mã thực tế
Chúng tôi liệt kê một số dự án Python dành cho người mới bắt đầu để bạn thử thách bản thân và cải thiện mã hóa Python
10 ý tưởng dự án Python hàng đầu cho người mới bắt đầu
Dự án dành cho người mới bắt đầu Python này là một khởi đầu tốt cho người mới bắt đầu vì nó sử dụng các chuỗi, biến và phép nối. Mad Libs Generator thao tác dữ liệu đầu vào, có thể là bất cứ thứ gì. một tính từ, một đại từ, hoặc động từ. Sau khi nhập dữ liệu vào, chương trình sẽ lấy dữ liệu và sắp xếp để xây dựng một câu chuyện. Đây là một dự án Python rất thú vị để thử nếu bạn chưa quen với việc viết mã
Mã mẫu
""" Mad Libs Generator
----------------------------------------
"""
#Loop back to this point once code finishes
loop = 1
while [loop < 10]:
# All the questions that the program asks the user
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: "]
#Displays the story based on the users 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,"."]
print []
print ["You may think that is this the",noun3,","]
print ["Well it is."]
print ["------------------------------------------"]
# Loop back to "loop = 1"
loop = loop + 1
Dự án này là một trò chơi thú vị tạo ra một số ngẫu nhiên trong một phạm vi nhất định và người dùng phải đoán số sau khi nhận được gợi ý. Mỗi khi người dùng đoán sai, họ sẽ được nhắc nhở với nhiều gợi ý hơn để làm cho nó dễ dàng hơn - với cái giá là giảm điểm
Chương trình cũng yêu cầu các chức năng để kiểm tra xem một số thực được người dùng nhập vào và tìm sự khác biệt giữa hai số.
Mã mẫu
""" Number Guessing Game
----------------------------------------
"""
import random
attempts_list = []
def show_score[]:
if len[attempts_list] 10:
raise ValueError["Please guess a number within the given range"]
if int[guess] == random_number:
print["Nice! You got it!"]
attempts += 1
attempts_list.append[attempts]
print["It took you {} attempts".format[attempts]]
play_again = input["Would you like to play again? [Enter Yes/No] "]
attempts = 0
show_score[]
random_number = int[random.randint[1, 10]]
if play_again.lower[] == "no":
print["That's cool, have a good one!"]
break
elif int[guess] > random_number:
print["It's lower"]
attempts += 1
elif int[guess] < random_number:
print["It's higher"]
attempts += 1
except ValueError as err:
print["Oh no!, that is not a valid value. Try again..."]
print["[{}]".format[err]]
else:
print["That's cool, have a good one!"]
if __name__ == '__main__':
start_game[]
Đề xuất khóa học Python
Hoàn thành Python Bootcamp từ Zero đến Hero trong Python
Chương trình oẳn tù tì này sử dụng một số chức năng, vì vậy đây là một cách hay để bạn nắm được khái niệm quan trọng đó
- hàm ngẫu nhiên. để tạo oẳn tù tì hoặc kéo.
- hàm hợp lệ. để kiểm tra tính hợp lệ của di chuyển
- hàm kết quả. để tuyên bố người chiến thắng của vòng
- người ghi bàn. để theo dõi điểm số
Chương trình yêu cầu người dùng thực hiện bước di chuyển đầu tiên trước khi thực hiện bước di chuyển. Đầu vào có thể là một chuỗi hoặc một bảng chữ cái đại diện cho oẳn tù tì hoặc kéo. Sau khi đánh giá chuỗi đầu vào, người chiến thắng được quyết định bởi chức năng kết quả và điểm số của vòng được cập nhật bởi chức năng người ghi điểm.
Mã mẫu
""" Rock Paper Scissors
----------------------------------------
"""
import random
import os
import re
os.system['cls' if os.name=='nt' else 'clear']
while [1 < 2]:
print ["\n"]
print ["Rock, Paper, Scissors - Shoot!"]
userChoice = input["Choose your weapon [R]ock], [P]aper, or [S]cissors: "]
if not re.match["[SsRrPp]", userChoice]:
print ["Please choose a letter:"]
print ["[R]ock, [S]cissors or [P]aper."]
continue
# Echo the user's choice
print ["You chose: " + userChoice]
choices = ['R', 'P', 'S']
opponenetChoice = random.choice[choices]
print ["I chose: " + opponenetChoice]
if opponenetChoice == str.upper[userChoice]:
print ["Tie! "]
#if opponenetChoice == str["R"] and str.upper[userChoice] == "P"
elif opponenetChoice == 'R' and userChoice.upper[] == 'S':
print ["Scissors beats rock, I win! "]
continue
elif opponenetChoice == 'S' and userChoice.upper[] == 'P':
print ["Scissors beats paper! I win! "]
continue
elif opponenetChoice == 'P' and userChoice.upper[] == 'R':
print ["Paper beat rock, I win!"]
continue
else:
print ["You win!"]
Trình tạo cuộn xúc xắc này là một chương trình khá đơn giản, sử dụng chức năng ngẫu nhiên để mô phỏng cuộn xúc xắc. Bạn có thể thay đổi giá trị tối đa thành bất kỳ số nào, giúp có thể mô phỏng xúc xắc đa diện được sử dụng trong nhiều trò chơi cờ bàn và trò chơi nhập vai
Mã mẫu
import random
#Enter the minimum and maximum limits of the dice rolls below
min_val = 1
max_val = 6
#the variable that stores the user’s decision
roll_again = "yes"
#The dice roll loop if the user wants to continue
while roll_again == "yes" or roll_again == "y":
print["Dices rolling..."]
print["The values are :"]
#Printing the randomly generated variable of the first dice
print[random.randint[min_val, max_val]]
#Printing the randomly generated variable of the second dice
print[random.randint[min_val, max_val]]
#Here the user enters yes or y to continue and any other input ends the program
roll_again = input["Roll the Dices Again?"]
Thuật toán tìm kiếm nhị phân là một thuật toán rất quan trọng và yêu cầu bạn tạo danh sách các số từ 0 đến giới hạn trên, với mỗi số tiếp theo có chênh lệch 2 giữa chúng.
Khi người dùng nhập một số ngẫu nhiên để tìm kiếm, chương trình bắt đầu tìm kiếm bằng cách chia danh sách thành hai nửa. Đầu tiên, nửa đầu tiên được tìm kiếm cho số cần thiết và nếu tìm thấy, nửa còn lại sẽ bị từ chối và ngược lại. Quá trình tìm kiếm tiếp tục cho đến khi số được tìm thấy hoặc kích thước mảng con bằng không
Mã mẫu
# Recursive Binary Search algorithm in Python
def binarySearch[array, x, low, high]:
if high >= low:
mid = low + [high - low]//2
# If found at mid, return the value
if array[mid] == x:
return mid
# Search the first half
elif array[mid] > x:
return binarySearch[array, x, low, mid-1]
# Search the second half
else:
return binarySearch[array, x, mid + 1, high]
else:
return -1
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x = int[input["Enter a number between 1 and 10:"]]
result = binarySearch[array, x, 0, len[array]-1]
if result != -1:
print["Element is present at position" + str[result]]
else:
print["Element not found"]
Dự án này dạy bạn thiết kế giao diện đồ họa và là một cách hay để làm quen với một thư viện như Tkinter. Thư viện này cho phép bạn tạo các nút để thực hiện các thao tác khác nhau và hiển thị kết quả trên màn hình.
Mã mẫu
# Calculator
def addition []:
print["Addition"]
n = float[input["Enter the number: "]]
t = 0 #Total number enter
ans = 0
while n != 0:
ans = ans + n
t+=1
n = float[input["Enter another number [0 to calculate]: "]]
return [ans,t]
def subtraction []:
print["Subtraction"];
n = float[input["Enter the number: "]]
t = 0 #Total number enter
sum = 0
while n != 0:
ans = ans - n
t+=1
n = float[input["Enter another number [0 to calculate]: "]]
return [ans,t]
def multiplication []:
print["Multiplication"]
n = float[input["Enter the number: "]]
t = 0 #Total number enter
ans = 1
while n != 0:
ans = ans * n
t+=1
n = float[input["Enter another number [0 to calculate]: "]]
return [ans,t]
def average[]:
an = []
an = addition[]
t = an[1]
a = an[0]
ans = a / t
return [ans,t]
# main...
while True:
list = []
print[" My first python program!"]
print[" Simple Calculator in python by Malik Umer Farooq"]
print[" Enter 'a' for addition"]
print[" Enter 's' for substraction"]
print[" Enter 'm' for multiplication"]
print[" Enter 'v' for average"]
print[" Enter 'q' for quit"]
c = input[" "]
if c != 'q':
if c == 'a':
list = addition[]
print["Ans = ", list[0], " total inputs ",list[1]]
elif c == 's':
list = subtraction[]
print["Ans = ", list[0], " total inputs ",list[1]]
elif c == 'm':
list = multiplication[]
print["Ans = ", list[0], " total inputs ",list[1]]
elif c == 'v':
list = average[]
print["Ans = ", list[0], " total inputs ",list[1]]
else:
print ["Sorry, invilid character"]
else:
break
Ứng dụng Python Giao diện dòng lệnh [CLI] này là một bước khởi đầu tốt cho nhà phát triển mới bắt đầu. Không chỉ đặt báo thức, chương trình này cho phép thêm một số liên kết YouTube nhất định vào tệp văn bản. Khi người dùng đặt báo thức, mã sẽ chọn một video ngẫu nhiên và bắt đầu phát video đó
Mã mẫu
""" Alarm Clock
----------------------------------------
"""
import datetime
import os
import time
import random
import webbrowser
# If video URL file does not exist, create one
if not os.path.isfile["youtube_alarm_videos.txt"]:
print['Creating "youtube_alarm_videos.txt"...']
with open["youtube_alarm_videos.txt", "w"] as alarm_file:
alarm_file.write["//www.youtube.com/watch?v=anM6uIZvx74"]
def check_alarm_input[alarm_time]:
"""Checks to see if the user has entered in a valid alarm time"""
if len[alarm_time] == 1: # [Hour] Format
if alarm_time[0] < 24 and alarm_time[0] >= 0:
return True
if len[alarm_time] == 2: # [Hour:Minute] Format
if alarm_time[0] < 24 and alarm_time[0] >= 0 and \
alarm_time[1] < 60 and alarm_time[1] >= 0:
return True
elif len[alarm_time] == 3: # [Hour:Minute:Second] Format
if alarm_time[0] < 24 and alarm_time[0] >= 0 and \
alarm_time[1] < 60 and alarm_time[1] >= 0 and \
alarm_time[2] < 60 and alarm_time[2] >= 0:
return True
return False
# Get user input for the alarm time
print["Set a time for the alarm [Ex. 06:30 or 18:30:00]"]
while True:
alarm_input = input[">> "]
try:
alarm_time = [int[n] for n in alarm_input.split[":"]]
if check_alarm_input[alarm_time]:
break
else:
raise ValueError
except ValueError:
print["ERROR: Enter time in HH:MM or HH:MM:SS format"]
# Convert the alarm time from [H:M] or [H:M:S] to seconds
seconds_hms = [3600, 60, 1] # Number of seconds in an Hour, Minute, and Second
alarm_seconds = sum[[a*b for a,b in zip[seconds_hms[:len[alarm_time]], alarm_time]]]
# Get the current time of day in seconds
now = datetime.datetime.now[]
current_time_seconds = sum[[a*b for a,b in zip[seconds_hms, [now.hour, now.minute, now.second]]]]
# Calculate the number of seconds until alarm goes off
time_diff_seconds = alarm_seconds - current_time_seconds
# If time difference is negative, set alarm for next day
if time_diff_seconds < 0:
time_diff_seconds += 86400 # number of seconds in a day
# Display the amount of time until the alarm goes off
print["Alarm set to go off in %s" % datetime.timedelta[seconds=time_diff_seconds]]
# Sleep until the alarm goes off
time.sleep[time_diff_seconds]
# Time for the alarm to go off
print["Wake Up!"]
# Load list of possible video URLs
with open["youtube_alarm_videos.txt", "r"] as alarm_file:
videos = alarm_file.readlines[]
# Open a random video from the list
webbrowser.open[random.choice[videos]]
Tic-Tac-Toe là một trò chơi hai người chơi bao gồm một lưới chín ô vuông. Mỗi người chơi đánh dấu không gian của họ bằng O hoặc X luân phiên. Người chơi đánh được ba chữ O hoặc X theo đường chéo, hàng ngang hoặc hàng dọc sẽ thắng. Mỗi người chơi phải chặn đối thủ của họ trong khi cố gắng tạo chuỗi của họ. Đối với dự án này, chúng tôi sử dụng thư viện Pygame Python.
Mã mẫu.
""" Tic Tac Toe
----------------------------------------
"""
import random
import sys
board=[i for i in range[0,9]]
player, computer = '',''
# Corners, Center and Others, respectively
moves=[[1,7,3,9],[5,],[2,4,6,8]]
# Winner combinations
winners=[[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
# Table
tab=range[1,10]
def print_board[]:
x=1
for i in board:
end = ' | '
if x%3 == 0:
end = ' \n'
if i != 1: end+='---------\n';
char=' '
if i in ['X','O']: char=i;
x+=1
print[char,end=end]
def select_char[]:
chars=['X','O']
if random.randint[0,1] == 0:
return chars[::-1]
return chars
def can_move[brd, player, move]:
if move in tab and brd[move-1] == move-1:
return True
return False
def can_win[brd, player, move]:
places=[]
x=0
for i in brd:
if i == player: places.append[x];
x+=1
win=True
for tup in winners:
win=True
for ix in tup:
if brd[ix] != player:
win=False
break
if win == True:
break
return win
def make_move[brd, player, move, undo=False]:
if can_move[brd, player, move]:
brd[move-1] = player
win=can_win[brd, player, move]
if undo:
brd[move-1] = move-1
return [True, win]
return [False, False]
# AI goes here
def computer_move[]:
move=-1
# If I can win, others do not matter.
for i in range[1,10]:
if make_move[board, computer, i, True][1]:
move=i
break
if move == -1:
# If player can win, block him.
for i in range[1,10]:
if make_move[board, player, i, True][1]:
move=i
break
if move == -1:
# Otherwise, try to take one of desired places.
for tup in moves:
for mv in tup:
if move == -1 and can_move[board, computer, mv]:
move=mv
break
return make_move[board, computer, move]
def space_exist[]:
return board.count['X'] + board.count['O'] != 9
player, computer = select_char[]
print['Player is [%s] and computer is [%s]' % [player, computer]]
result='%%% Deuce ! %%%'
while space_exist[]:
print_board[]
print['#Make your move ! [1-9] : ', end='']
move = int[input[]]
moved, won = make_move[board, player, move]
if not moved:
print[' >> Invalid number ! Try again !']
continue
if won:
result='*** Congratulations ! You won ! ***'
break
elif computer_move[][1]:
result='=== You lose ! =='
break;
print_board[]
print[result]
Chương trình đồng hồ đếm ngược này lấy số giây làm đầu vào và đếm ngược từng giây cho đến khi hiển thị thông báo. Nó thực hiện mô-đun thời gian, đáng để biết và là một mô-đun khá dễ tạo
Mã mẫu
________số 8Sắp xếp là một khái niệm quan trọng cần có trong bộ công cụ của bất kỳ lập trình viên nào và sắp xếp hợp nhất là một khái niệm đặc biệt quan trọng. Mặc dù có các chức năng sắp xếp như sắp xếp chèn, sắp xếp bong bóng và sắp xếp lựa chọn, nhưng sắp xếp hợp nhất đáng để biết vì nó hiệu quả để sắp xếp lượng lớn dữ liệu
Mã mẫu
def merge_sort[unsorted_list]
nếu len[unsorted_list]