بايثون

أفضل 5 أكواد بايثون جاهزة للمبتدئين

أن العمل على مشاريع بايثون هو طريقه مؤكدة لتعزيز مهاراتك وصقل معرفتك في استخدام لغة البرمجة. على الرغم من أن كتب Python ودروس Python التعليمية مفيدة ، فلا شيء يضاهي جعل يديك متمرسه على كتابة الأكواد والفهم وطريقة عملها.

سوف ندرج بأذن الله في هذه المقاله على العديد من مشاريع Python للمبتدئين لكي تتحدى نفسك.

لعبة الكلمات النموذجية

يعد مشروع بايثون هذا جيد للمبتدئين لأنه يستخدم السلاسل والمتغيرات والتسلسل. يتعامل مولد لعبة الكلمات النموذجية مع بيانات الإدخال ، والتي يمكن أن تكون أي شيء: صفة أو ضمير أو فعل. بعد أخذ المدخلات ، يأخذ البرنامج البيانات ويرتبها لبناء قصة. هذا المشروع رائع جدًا لتجربته إذا كنت جديدًا في مجال البرمجة.

#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

تخمين الأرقام

هذا المشروع عبارة عن لعبة ممتعة تنشئ رقمًا عشوائيًا في نطاق محدد ويجب على المستخدم تخمين الرقم بعد تلقي التلميحات. في كل مرة يكون فيها تخمين المستخدم خاطئًا ، تتم اعطائك المزيد من التلميحات لتسهيل الأمر.

import random

attempts_list = []

def show_score():

if len(attempts_list) <= 0:

print("There is currently no high score, it's yours for the taking!")

else:

print("The current high score is {} attempts".format(min(attempts_list)))

def start_game():

random_number = int(random.randint(1, 10))

print("Hello traveler! Welcome to the game of guesses!")

player_name = input("What is your name? ")

wanna_play = input("Hi, {}, would you like to play the guessing game? (Enter Yes/No) ".format(player_name))

# Where the show_score function USED to be

attempts = 0

show_score()

while wanna_play.lower() == "yes":

try:

guess = input("Pick a number between 1 and 10 ")

if int(guess) < 1 or int(guess) > 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()

منبه

يعد تطبيق Python بواجهة سطر الأوامر (CLI) خطوة جيدة للمطور المبتدئ. أكثر من مجرد تشغيل المنبه ، يسمح هذا البرنامج بإضافة بعض روابط YouTube إلى ملف نصي. عندما يقوم المستخدم بضبط المنبه ، يختار الكود مقطع فيديو عشوائيًا ويبدأ في تشغيله.

""" 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("https://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))

العد التنازلي

يستغرق برنامج مؤقت العد التنازلي عدد الثواني كمدخلات.

import time

# The countdown function is defined below

def countdown(t):

while t:

mins, secs = divmod(t, 60)

timer = '{:02d}:{:02d}'.format(mins, secs)

print(timer, end="\r")

time.sleep(1)

t -= 1

print('Lift off!')

# Ask the user to enter the countdown period in seconds

t = input("Enter the time in seconds: ")

# function call

countdown(int(t))

لعبة رمي النرد

يعد مولد لفة النرد هذا برنامجًا بسيطًا إلى حد ما يستخدم الوظيفة العشوائية لمحاكاة لفات النرد. يمكنك تغيير القيمة القصوى إلى أي رقم ، مما يجعل من الممكن محاكاة النرد متعدد السطوح المستخدم في العديد من ألعاب الطاولة وألعاب تمثيل الأدوار.

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?")

مقالات ذات صلة

اترك تعليقاً

لن يتم نشر عنوان بريدك الإلكتروني. الحقول الإلزامية مشار إليها بـ *