مدرسه زبان برنامه‌نویسی PYTHON

وبلاگی جهت معرفی - آموزش و تحلیل زبان برنامه نویسی ‍پایتون

مدرسه زبان برنامه‌نویسی PYTHON

وبلاگی جهت معرفی - آموزش و تحلیل زبان برنامه نویسی ‍پایتون

طبقه بندی موضوعی
بایگانی

۱۱ مطلب با موضوع «تمرین» ثبت شده است

کد زیر یک عدد  رو از ورودی میگیره و جمله خواسته شده  سری فیبونانچی رو چاپ میکنه. دقت کنید که به صورت بازگشتی نوشته شده. سعی کنید روش غیر بازگشتی همین کد رو شما بنویسید.


#Programmer : Saeed Damghanian

#Web : Pyschool.blg.ir


# Function for nth Fibonacci number 

  

def Fibonacci(n): 

    if n<0: 

        print("Incorrect input") 

    # First Fibonacci number is 0 

    elif n==1: 

        return 0

    # Second Fibonacci number is 1 

    elif n==2: 

        return 1

    else: 

        return Fibonacci(n-1)+Fibonacci(n-2) 

  

# Driver Program 


n=int(input("Pleas Enter n: "))  

print(Fibonacci(n)) 

  


#------------Telegram: @Ghoghnous_Iran-----------------------




b444745_Untitled.png

۱ نظر موافقین ۰ مخالفین ۰ ۳۰ تیر ۹۸ ، ۰۶:۳۹
سعید دامغانیان

برنامه ای نوشتم که تعدادی عدد رو داخل خود برنامه تعریف کرده و ســــپس با روش مرتب سازی حبابی مرتبشون کنه. حالا شما سعی کنید برنامه ای بنویسید که همین اعداد رو از ورودی گرفته و مرتب کنه. میتونید یک شرط بگذارید که اگه کاربر کاراکتر خاصی رو وارد کرد به معنای پایان اعداد  وارد شده باشه. یا میتونید اعداد رو یکجا بگیرید و پردازش کنید. اگه سوالی بود در خدمت هستم.


#Programmer : Saeed Damghanian

#Web : Pyschool.blg.ir


def bubbleSort(arr):

    n = len(arr)

 

    # Traverse through all array elements

    for i in range(n):

 

        # Last i elements are already in place

        for j in range(0, n-i-1):

 

            # traverse the array from 0 to n-i-1

            # Swap if the element found is greater

            # than the next element

            if arr[j] > arr[j+1] :

                arr[j], arr[j+1] = arr[j+1], arr[j]

 

# Driver code to test above

arr = [64, 34, 25, 12, 22, 11, 90]

 

bubbleSort(arr)

 

print ("Sorted array is:")

for i in range(len(arr)):

    print ("%d" %arr[i])


#------------Telegram: @Ghoghnous_Iran-----------------------



a887838_Untitled.png


۰ نظر موافقین ۰ مخالفین ۰ ۳۰ تیر ۹۸ ، ۰۶:۲۸
سعید دامغانیان

برنامه زیر ضرائب معادله درجه 2 را گرفته و معادله را حل نموده و جوابهای معادله را در صورت حقیقی بودن نمایش می‌دهد. سعی کنید برنامه‌ای بنویسید که جوابهای موهمومی معادله را نیز محاسبه و چاپ کند.


#Programmer : Saeed Damghanian

#Web : Pyschool.blg.ir


import math

a=int(input("Please Enter a: "))

b=int(input("Please Enter b: "))

c=int(input("Please Enter c: "))

delta=b*b-4*a*c

if delta==0 :

    x=(-b + math.sqrt(delta))

    print("Moadele Yek javab darad. X=",x)

elif delta<0:

    print("Moadele javabe haghighi nadarad!")

else :    

    x1=(-b + math.sqrt(delta))/(2*a)

    x2=(-b - math.sqrt(delta))/(2*a)

    print("Moadele 2 javab darad.\n X1= ",x1, "\nX2= " , x2)


#------------Telegram: @Ghoghnous_Iran-----------------------


 

h909262_Untitled.png

۱ نظر موافقین ۰ مخالفین ۰ ۳۰ تیر ۹۸ ، ۰۶:۰۵
سعید دامغانیان

در این پست آموزشی قصد دارم که ارسال ُ نوشتن و ویرایش یک پست الکترونیک را با هم ببینیم و همچنین بعد با پروتکلها و استاندارهایی همچون MIME  و ارسال نامه به این سبک را آموزش دهم. با من (سعید دامغانیان) همراه باشید...

در قطعه کد زیر اولاْ ارسال یک ایمیل ساده را بررسی کنید :

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.message import EmailMessage

# Open the plain text file whose name is in textfile for reading.
with open(textfile) as fp:
    # Create a text/plain message
    msg = EmailMessage()
    msg.set_content(fp.read())

# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you

# Send the message via our own SMTP server.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()

حال با استاندارد RFC822 آشنا شده و سپس کد زیر را بررسی کنید :

# Import the email modules we'll need
from email.parser import BytesParser, Parser
from email.policy import default

# If the e-mail headers are in a file, uncomment these two lines:
# with open(messagefile, 'rb') as fp:
#     headers = BytesParser(policy=default).parse(fp)

#  Or for parsing headers in a string (this is an uncommon operation), use:
headers = Parser(policy=default).parsestr(
        'From: Foo Bar <user@example.com>\n'
        'To: <someone_else@example.com>\n'
        'Subject: Test message\n'
        '\n'
        'Body would go here\n')

#  Now the header items can be accessed as a dictionary:
print('To: {}'.format(headers['to']))
print('From: {}'.format(headers['from']))
print('Subject: {}'.format(headers['subject']))

# You can also access the parts of the addresses:
print('Recipient username: {}'.format(headers['to'].addresses[0].username))
print('Sender name: {}'.format(headers['from'].addresses[0].display_name))

حال نوبت رسیده کمی فراتر رفته و به استاندارد MIME بپردازیم. نوبت شماست ...

# Import smtplib for the actual sending function
import smtplib

# And imghdr to find the types of our images
import imghdr

# Here are the email package modules we'll need
from email.message import EmailMessage

# Create the container email message.
msg = EmailMessage()
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = me
msg['To'] = ', '.join(family)
msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'

# Open the files in binary mode.  Use imghdr to figure out the
# MIME subtype for each specific image.
for file in pngfiles:
    with open(file, 'rb') as fp:
        img_data = fp.read()
    msg.add_attachment(img_data, maintype='image',
                                 subtype=imghdr.what(None, img_data))

# Send the email via our own SMTP server.
with smtplib.SMTP('localhost') as s:
    s.send_message(msg)

در قطعه کد زیر فصد داریم محتویات یک دایرکتوری را به استاندارد MIME ارسال کنیم...

#!/usr/bin/env python3

"""Send the contents of a directory as a MIME message."""

import os
import smtplib
# For guessing MIME type based on file name extension
import mimetypes

from argparse import ArgumentParser

from email.message import EmailMessage
from email.policy import SMTP


def main():
    parser = ArgumentParser(description="""\
Send the contents of a directory as a MIME message.
Unless the -o option is given, the email is sent by forwarding to your local
SMTP server, which then does the normal delivery process.  Your local machine
must be running an SMTP server.
""")
    parser.add_argument('-d', '--directory',
                        help="""Mail the contents of the specified directory,
                        otherwise use the current directory.  Only the regular
                        files in the directory are sent, and we don't recurse to
                        subdirectories.""")
    parser.add_argument('-o', '--output',
                        metavar='FILE',
                        help="""Print the composed message to FILE instead of
                        sending the message to the SMTP server.""")
    parser.add_argument('-s', '--sender', required=True,
                        help='The value of the From: header (required)')
    parser.add_argument('-r', '--recipient', required=True,
                        action='append', metavar='RECIPIENT',
                        default=[], dest='recipients',
                        help='A To: header value (at least one required)')
    args = parser.parse_args()
    directory = args.directory
    if not directory:
        directory = '.'
    # Create the message
    msg = EmailMessage()
    msg['Subject'] = 'Contents of directory %s' % os.path.abspath(directory)
    msg['To'] = ', '.join(args.recipients)
    msg['From'] = args.sender
    msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'

    for filename in os.listdir(directory):
        path = os.path.join(directory, filename)
        if not os.path.isfile(path):
            continue
        # Guess the content type based on the file's extension.  Encoding
        # will be ignored, although we should check for simple things like
        # gzip'd or compressed files.
        ctype, encoding = mimetypes.guess_type(path)
        if ctype is None or encoding is not None:
            # No guess could be made, or the file is encoded (compressed), so
            # use a generic bag-of-bits type.
            ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
        with open(path, 'rb') as fp:
            msg.add_attachment(fp.read(),
                               maintype=maintype,
                               subtype=subtype,
                               filename=filename)
    # Now send or store the message
    if args.output:
        with open(args.output, 'wb') as fp:
            fp.write(msg.as_bytes(policy=SMTP))
    else:
        with smtplib.SMTP('localhost') as s:
            s.send_message(msg)


if __name__ == '__main__':
    main()
در اینجا طریقه باز کردن ایمیل دریافتی مشابه بالا را در همان استاندارد بررسی خواهیم نمود 
#!/usr/bin/env python3

"""Unpack a MIME message into a directory of files."""

import os
import email
import mimetypes

from email.policy import default

from argparse import ArgumentParser


def main():
    parser = ArgumentParser(description="""\
Unpack a MIME message into a directory of files.
""")
    parser.add_argument('-d', '--directory', required=True,
                        help="""Unpack the MIME message into the named
                        directory, which will be created if it doesn't already
                        exist.""")
    parser.add_argument('msgfile')
    args = parser.parse_args()

    with open(args.msgfile, 'rb') as fp:
        msg = email.message_from_binary_file(fp, policy=default)

    try:
        os.mkdir(args.directory)
    except FileExistsError:
        pass

    counter = 1
    for part in msg.walk():
        # multipart/* are just containers
        if part.get_content_maintype() == 'multipart':
            continue
        # Applications should really sanitize the given filename so that an
        # email message can't be used to overwrite important files
        filename = part.get_filename()
        if not filename:
            ext = mimetypes.guess_extension(part.get_content_type())
            if not ext:
                # Use a generic bag-of-bits extension
                ext = '.bin'
            filename = 'part-%03d%s' % (counter, ext)
        counter += 1
        with open(os.path.join(args.directory, filename), 'wb') as fp:
            fp.write(part.get_payload(decode=True))


if __name__ == '__main__':
    main()

در اینجا یک مثال که نحوه ایجاد یک پیام HTML با یک نسخه متنی ساده است را نوشته ایم. برای ایجاد چیزهای کمی جالب تر، ما یک تصویر مربوط به آن را در بخش HTML می نویسیم و یک کپی از آنچه که ما می خواهیم برای ارسال به دیسک داریم، و همچنین ارسال آن را ذخیره کرده ایم...

#!/usr/bin/env python3

import smtplib

from email.message import EmailMessage
from email.headerregistry import Address
from email.utils import make_msgid

# Create the base text message.
msg = EmailMessage()
msg['Subject'] = "Ayons asperges pour le déjeuner"
msg['From'] = Address("Pepé Le Pew", "pepe", "example.com")
msg['To'] = (Address("Penelope Pussycat", "penelope", "example.com"),
             Address("Fabrette Pussycat", "fabrette", "example.com"))
msg.set_content("""\
Salut!

Cela ressemble à un excellent recipie[1] déjeuner.

[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718

--Pepé
""")

# Add the html version.  This converts the message into a multipart/alternative
# container, with the original text message as the first part and the new html
# message as the second part.
asparagus_cid = make_msgid()
msg.add_alternative("""\
<html>
  <head></head>
  <body>
    <p>Salut!</p>
    <p>Cela ressemble à un excellent
        <a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718">
            recipie
        </a> déjeuner.
    </p>
    <img src="cid:{asparagus_cid}" />
  </body>
</html>
""".format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')
# note that we needed to peel the <> off the msgid for use in the html.

# Now add the related image to the html part.
with open("roasted-asparagus.jpg", 'rb') as img:
    msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',
                                     cid=asparagus_cid)

# Make a local copy of what we are going to send.
with open('outgoing.msg', 'wb') as f:
    f.write(bytes(msg))

# Send the message via local SMTP server.
with smtplib.SMTP('localhost') as s:
    s.send_message(msg)

اگر پیام از آخرین نمونه ای که نوشتم ارسال شد، در اینجا یکی از راه هایی است که می توانیم آن را پردازش کنیم:

import os
import sys
import tempfile
import mimetypes
import webbrowser

# Import the email modules we'll need
from email import policy
from email.parser import BytesParser

# An imaginary module that would make this work and be safe.
from imaginary import magic_html_parser

# In a real program you'd get the filename from the arguments.
with open('outgoing.msg', 'rb') as fp:
    msg = BytesParser(policy=policy.default).parse(fp)

# Now the header items can be accessed as a dictionary, and any non-ASCII will
# be converted to unicode:
print('To:', msg['to'])
print('From:', msg['from'])
print('Subject:', msg['subject'])

# If we want to print a preview of the message content, we can extract whatever
# the least formatted payload is and print the first three lines.  Of course,
# if the message has no plain text part printing the first three lines of html
# is probably useless, but this is just a conceptual example.
simplest = msg.get_body(preferencelist=('plain', 'html'))
print()
print(''.join(simplest.get_content().splitlines(keepends=True)[:3]))

ans = input("View full message?")
if ans.lower()[0] == 'n':
    sys.exit()

# We can extract the richest alternative in order to display it:
richest = msg.get_body()
partfiles = {}
if richest['content-type'].maintype == 'text':
    if richest['content-type'].subtype == 'plain':
        for line in richest.get_content().splitlines():
            print(line)
        sys.exit()
    elif richest['content-type'].subtype == 'html':
        body = richest
    else:
        print("Don't know how to display {}".format(richest.get_content_type()))
        sys.exit()
elif richest['content-type'].content_type == 'multipart/related':
    body = richest.get_body(preferencelist=('html'))
    for part in richest.iter_attachments():
        fn = part.get_filename()
        if fn:
            extension = os.path.splitext(part.get_filename())[1]
        else:
            extension = mimetypes.guess_extension(part.get_content_type())
        with tempfile.NamedTemporaryFile(suffix=extension, delete=False) as f:
            f.write(part.get_content())
            # again strip the <> to go from email form of cid to html form.
            partfiles[part['content-id'][1:-1]] = f.name
else:
    print("Don't know how to display {}".format(richest.get_content_type()))
    sys.exit()
with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
    # The magic_html_parser has to rewrite the href="cid:...." attributes to
    # point to the filenames in partfiles.  It also has to do a safety-sanitize
    # of the html.  It could be written using html.parser.
    f.write(magic_html_parser(body.get_content(), partfiles))
webbrowser.open(f.name)
os.remove(f.name)
for fn in partfiles.values():
    os.remove(fn)

# Of course, there are lots of email messages that could break this simple
# minded program, but it will handle the most common ones.

خروجی قطعه کد بالا را در ذیل ببینید :

To: Penelope Pussycat <penelope@example.com>, Fabrette Pussycat <fabrette@example.com>
From: Pepé Le Pew <pepe@example.com>
Subject: Ayons asperges pour le déjeuner

Salut!

Cela ressemble à un excellent recipie[1] déjeuner.
۰ نظر موافقین ۰ مخالفین ۰ ۲۴ تیر ۹۸ ، ۱۳:۳۲
سعید دامغانیان

  turtle و math  کدی نوشتم که شکل یک لانه ی زنبور را ترسیم کند. با استفاده از


# Hive

# By: Saeed Damghanian


from turtle import *

from math import *


def line(x, y, x2, y2):

    ''' Draw a line from (x, y) to (x2, y2) '''

    penup()

    goto(x, y)

    pendown()

    goto(x2, y2)



def draw_tree(x, y, size, angle,n):

    ''' Draw a tree of given size and angle at (x, y) '''

    if n==1:

        return

    if size < 4:

        return

    x2 = x + size * cos(radians(angle))

    y2 = y + size * sin(radians(angle))

    line(x, y, x2, y2)

    draw_tree(x2, y2, size , angle + 60,n-1)

    draw_tree(x2, y2, size , angle - 60,n-1)



# main program

#tracer(0,0)


#speed(10)

#delay(2)

draw_tree(0, 0, 50, 90,10)

mainloop()


u544287_Untitled.png

۲ نظر موافقین ۰ مخالفین ۰ ۲۴ تیر ۹۸ ، ۱۱:۰۷
سعید دامغانیان

کدی که در ذیل مشاهده می‌کنید یک خورشید را به صورت خطهای هندسی رسم کرده و رنگ میزند. #جالبناک


from turtle import *

color('blue', 'yellow')

begin_fill()

while True:

    forward(200)

    left(100)

    if abs(pos()) < 1:

        break

end_fill()

done()


خروجی کد بالا شکلی مطابق ذیل است. با ما همراه شوید.. . مدرسه پایتون

n488379_Untitled.png

۱ نظر موافقین ۰ مخالفین ۰ ۲۴ تیر ۹۸ ، ۱۰:۵۲
سعید دامغانیان

برنامه ای نوشتم که آدرس یک سایت رو بگیره و آی پی سایت رو نمایش بده. خیلی ساده (البته گرافیکی* #پایتون )


#Code By Saeed Damghanian

#Software Engineer from Semnan


import os, socket

import tkinter as tk

from tkinter import font


def response(a):

    b = socket.gethostbyname(a)

    c = "\n \n \nProgrammer: Saeed Damghanian\nWebsPyschool.blog.ir\nWant to Join our Telegram Channel? >> t.me/ghoghnous_iran"

    return b + c


def do(a):

    label['text'] = response(a)


root = tk.Tk()

root.title('Get Website Ip')


canvas = tk.Canvas(root, height=500, width=600)

canvas.pack()


#background_image1 = tk.PhotoImage(file='bg.png')

#background_label =tk.Label(root, image=background_image1)

#background_label.place(relwidth=1, relheight=1)


frame = tk.Frame(root, bg='#C02F11', bd=5)

frame.place(relx=0.5, rely=0.1, relwidth=0.75, relheight=0.1, anchor='n')


entry = tk.Entry(frame, font=('Modern', 15))

entry.insert(0, 'Website URL')

entry.place(relwidth=0.65, relheight=1)


button = tk.Button(frame, text='Get IP', bd=0, bg='white', fg='#098f00', font=60, command=lambda:do(entry.get()))

button.place(relx=0.7, relheight=1, relwidth=0.3)


lower_frame = tk.Frame(root, bg='#0ed400', bd=10)

lower_frame.place(relx=0.5, rely=0.25, relwidth=0.75, relheight=0.6, anchor='n')


label = tk.Label(lower_frame, font=('Modern', 15), anchor='nw', bg='#323142', fg='white', justify='left', bd=4)

label.place(relwidth=1, relheight=1)


root.mainloop()


g241362_Untitled.png


۰ نظر موافقین ۰ مخالفین ۰ ۲۳ تیر ۹۸ ، ۰۰:۰۰
سعید دامغانیان

مثال هایی از SORT (مرتب سازی ) در پایتون. تحلیل و تفسیر با شما...


a29009_01.jpg

e2519_02.jpg

a944746_03.jpg

o38084_04.jpg


r04659_05.jpg


موفق و پیروز باشید #سعیددامغانیان


۰ نظر موافقین ۰ مخالفین ۰ ۱۲ تیر ۹۸ ، ۱۱:۵۵
سعید دامغانیان

: برنامه ای بنویسید که دو عدد را از ورودی بگیرد و تمام اعداد اول مابین آنها را نمایش دهد


# Python program to print all  

# prime number in an interval 

  

start =int( input("Please Enter Statr Number: "))


end =  int( input("Please Enter End Number: "))

  

for val in range(start, end + 1): 

      

   # If num is divisible by any number   

   # between 2 and val, it is not prime  

   if val > 1: 

       for n in range(2, val): 

           if (val % n) == 0: 

               break

       else: 

           print(val) 


u76042_01.jpg

۰ نظر موافقین ۰ مخالفین ۰ ۱۲ تیر ۹۸ ، ۱۱:۲۴
سعید دامغانیان

پروژه برعکس کننده کلمات ! 


در این تمرین ابتدا با تابع input از کاربر یک رشته گرفته ایم و در word ریخته ایم. سپس با تابع len طول آن رشته را در یک متغیر به اسم i ذخیره کرده ایم. و سپس متغیر rev را برای رشته برعکس شده ساخته ایم.

در حلقه while شرط گذاشته ایم که تا وقتی که i صفر نشده، محتویات متغیر rev را با [i-1] رشته مان یعنی word جمع کن و بعد یکی از i کم کن.

همانطور که میدانید کامپیوتر ها از صفر میشمرند یعنی مثلا اگر طول word ما 3 بود بدین صورت است :

حرف اول : 0

حرف دوم: 1

حرف سوم:2

پس این حلقه از حرف آخر کلمه شروع کرده و به اول رشته برعکس یعنی rev میچسباند و وقتی کار تمام شد از حلقه خارج شده و rev را نمایش میدهد. خط آخر نیز فقط برای خوانا تر شدن نتایج است :)

در آخر تمام این کدها در یک حلقه بینهایت (While True) قرار داده شده تا برنامه تا همیشه اجرا شود.


824627_photo_2019-06-27_23-26-00.jpg

۰ نظر موافقین ۰ مخالفین ۰ ۰۷ تیر ۹۸ ، ۲۱:۴۷
سعید دامغانیان