/
fedorhub
/
Python_Le
Обзор
Документация
Войти
/
fedorhub
/
Python_Le
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
python/script-13/index.htm
2 577 строк
371 KB
fedorhub
upload files
17 дек 2025, 14:35
17 дек 2025, 14:35
50de53d
Код
Авторство
О чём код?
<!DOCTYPE html> <html class="no-js" lang="ru-RU"> <head> <meta http-equiv="content-type" content="text/html" charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" > <link rel="profile" href="http://gmpg.org/xfn/11"> <meta name='robots' content='index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1' /> <script> MathJax = { tex: { inlineMath: [['$','$'],['\\(','\\)']], processEscapes: true }, options: { ignoreHtmlClass: 'tex2jax_ignore|editor-rich-text' } }; </script> <!-- This site is optimized with the Yoast SEO plugin v23.8 - https://yoast.com/wordpress/plugins/seo/ --> <title>Программа на Питоне | Программирование на Питоне</title> <meta name="description" content="Программа на Питоне - это файл с расширением .py. Мы научимся писать и запускать такие программы, а также создавать модули и пакеты." /> <link rel="canonical" href="https://www.dmitrymakarov.ru/python/script-13/" /> <meta property="og:locale" content="ru_RU" /> <meta property="og:type" content="article" /> <meta property="og:title" content="Программа на Питоне | Программирование на Питоне" /> <meta property="og:description" content="Программа на Питоне - это файл с расширением .py. Мы научимся писать и запускать такие программы, а также создавать модули и пакеты." /> <meta property="og:url" content="https://www.dmitrymakarov.ru/python/script-13/" /> <meta property="og:site_name" content="Машинное обучение" /> <meta property="article:modified_time" content="2024-10-12T18:25:10+00:00" /> <meta property="og:image" content="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/executing-python.png" /> <meta property="og:image:width" content="1114" /> <meta property="og:image:height" content="505" /> <meta property="og:image:type" content="image/png" /> <meta name="twitter:card" content="summary_large_image" /> <meta name="twitter:label1" content="Примерное время для чтения" /> <meta name="twitter:data1" content="35 минут" /> <script type="application/ld+json" class="yoast-schema-graph">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","@id":"https://www.dmitrymakarov.ru/python/script-13/","url":"https://www.dmitrymakarov.ru/python/script-13/","name":"Программа на Питоне | Программирование на Питоне","isPartOf":{"@id":"https://www.dmitrymakarov.ru/#website"},"primaryImageOfPage":{"@id":"https://www.dmitrymakarov.ru/python/script-13/#primaryimage"},"image":{"@id":"https://www.dmitrymakarov.ru/python/script-13/#primaryimage"},"thumbnailUrl":"https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/executing-python-1024x464.png","datePublished":"2022-04-22T14:07:50+00:00","dateModified":"2024-10-12T18:25:10+00:00","description":"Программа на Питоне - это файл с расширением .py. Мы научимся писать и запускать такие программы, а также создавать модули и пакеты.","breadcrumb":{"@id":"https://www.dmitrymakarov.ru/python/script-13/#breadcrumb"},"inLanguage":"ru-RU","potentialAction":[{"@type":"ReadAction","target":["https://www.dmitrymakarov.ru/python/script-13/"]}]},{"@type":"ImageObject","inLanguage":"ru-RU","@id":"https://www.dmitrymakarov.ru/python/script-13/#primaryimage","url":"https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/executing-python.png","contentUrl":"https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/executing-python.png","width":1114,"height":505},{"@type":"BreadcrumbList","@id":"https://www.dmitrymakarov.ru/python/script-13/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Главная страница","item":"https://www.dmitrymakarov.ru/"},{"@type":"ListItem","position":2,"name":"Программирование на Питоне","item":"https://www.dmitrymakarov.ru/python/"},{"@type":"ListItem","position":3,"name":"Программа на Питоне"}]},{"@type":"WebSite","@id":"https://www.dmitrymakarov.ru/#website","url":"https://www.dmitrymakarov.ru/","name":"Машинное обучение","description":"","publisher":{"@id":"https://www.dmitrymakarov.ru/#/schema/person/3fc221e2d391cc5cfd9d31c9c251c2a4"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://www.dmitrymakarov.ru/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"ru-RU"},{"@type":["Person","Organization"],"@id":"https://www.dmitrymakarov.ru/#/schema/person/3fc221e2d391cc5cfd9d31c9c251c2a4","name":"DmitryMakarov","image":{"@type":"ImageObject","inLanguage":"ru-RU","@id":"https://www.dmitrymakarov.ru/#/schema/person/image/","url":"https://secure.gravatar.com/avatar/2c5f922d990c667feffc00f99517cc0e?s=96&d=mm&r=g","contentUrl":"https://secure.gravatar.com/avatar/2c5f922d990c667feffc00f99517cc0e?s=96&d=mm&r=g","caption":"DmitryMakarov"},"logo":{"@id":"https://www.dmitrymakarov.ru/#/schema/person/image/"}}]}</script> <!-- / Yoast SEO plugin. --> <link rel='dns-prefetch' href='//cdn.jsdelivr.net' /> <link rel="alternate" type="application/rss+xml" title="Машинное обучение » Лента" href="https://www.dmitrymakarov.ru/feed/" /> <link rel="alternate" type="application/rss+xml" title="Машинное обучение » Лента комментариев" href="https://www.dmitrymakarov.ru/comments/feed/" /> <script type="text/javascript"> /* <![CDATA[ */ window._wpemojiSettings = {"baseUrl":"https:\/\/s.w.org\/images\/core\/emoji\/15.0.3\/72x72\/","ext":".png","svgUrl":"https:\/\/s.w.org\/images\/core\/emoji\/15.0.3\/svg\/","svgExt":".svg","source":{"concatemoji":"https:\/\/www.dmitrymakarov.ru\/wp-includes\/js\/wp-emoji-release.min.js?ver=6.6.2"}}; /*! This file is auto-generated */ !function(i,n){var o,s,e;function c(e){try{var t={supportTests:e,timestamp:(new Date).valueOf()};sessionStorage.setItem(o,JSON.stringify(t))}catch(e){}}function p(e,t,n){e.clearRect(0,0,e.canvas.width,e.canvas.height),e.fillText(t,0,0);var t=new Uint32Array(e.getImageData(0,0,e.canvas.width,e.canvas.height).data),r=(e.clearRect(0,0,e.canvas.width,e.canvas.height),e.fillText(n,0,0),new Uint32Array(e.getImageData(0,0,e.canvas.width,e.canvas.height).data));return t.every(function(e,t){return e===r[t]})}function u(e,t,n){switch(t){case"flag":return n(e,"\ud83c\udff3\ufe0f\u200d\u26a7\ufe0f","\ud83c\udff3\ufe0f\u200b\u26a7\ufe0f")?!1:!n(e,"\ud83c\uddfa\ud83c\uddf3","\ud83c\uddfa\u200b\ud83c\uddf3")&&!n(e,"\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc65\udb40\udc6e\udb40\udc67\udb40\udc7f","\ud83c\udff4\u200b\udb40\udc67\u200b\udb40\udc62\u200b\udb40\udc65\u200b\udb40\udc6e\u200b\udb40\udc67\u200b\udb40\udc7f");case"emoji":return!n(e,"\ud83d\udc26\u200d\u2b1b","\ud83d\udc26\u200b\u2b1b")}return!1}function f(e,t,n){var r="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?new OffscreenCanvas(300,150):i.createElement("canvas"),a=r.getContext("2d",{willReadFrequently:!0}),o=(a.textBaseline="top",a.font="600 32px Arial",{});return e.forEach(function(e){o[e]=t(a,e,n)}),o}function t(e){var t=i.createElement("script");t.src=e,t.defer=!0,i.head.appendChild(t)}"undefined"!=typeof Promise&&(o="wpEmojiSettingsSupports",s=["flag","emoji"],n.supports={everything:!0,everythingExceptFlag:!0},e=new Promise(function(e){i.addEventListener("DOMContentLoaded",e,{once:!0})}),new Promise(function(t){var n=function(){try{var e=JSON.parse(sessionStorage.getItem(o));if("object"==typeof e&&"number"==typeof e.timestamp&&(new Date).valueOf()<e.timestamp+604800&&"object"==typeof e.supportTests)return e.supportTests}catch(e){}return null}();if(!n){if("undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas&&"undefined"!=typeof URL&&URL.createObjectURL&&"undefined"!=typeof Blob)try{var e="postMessage("+f.toString()+"("+[JSON.stringify(s),u.toString(),p.toString()].join(",")+"));",r=new Blob([e],{type:"text/javascript"}),a=new Worker(URL.createObjectURL(r),{name:"wpTestEmojiSupports"});return void(a.onmessage=function(e){c(n=e.data),a.terminate(),t(n)})}catch(e){}c(n=f(s,u,p))}t(n)}).then(function(e){for(var t in e)n.supports[t]=e[t],n.supports.everything=n.supports.everything&&n.supports[t],"flag"!==t&&(n.supports.everythingExceptFlag=n.supports.everythingExceptFlag&&n.supports[t]);n.supports.everythingExceptFlag=n.supports.everythingExceptFlag&&!n.supports.flag,n.DOMReady=!1,n.readyCallback=function(){n.DOMReady=!0}}).then(function(){return e}).then(function(){var e;n.supports.everything||(n.readyCallback(),(e=n.source||{}).concatemoji?t(e.concatemoji):e.wpemoji&&e.twemoji&&(t(e.twemoji),t(e.wpemoji)))}))}((window,document),window._wpemojiSettings); /* ]]> */ </script> <link rel='stylesheet' id='mci-footnotes-no-tooltips-pagelayout-none-css' href='https://www.dmitrymakarov.ru/wp-content/plugins/footnotes/css/footnotes-nottbrpl0.min.css?ver=2.7.3' type='text/css' media='all' /> <link rel='stylesheet' id='urvanov_syntax_highlighter-css' href='https://www.dmitrymakarov.ru/wp-content/plugins/urvanov-syntax-highlighter/css/min/urvanov_syntax_highlighter.min.css?ver=2.8.37' type='text/css' media='all' /> <link rel='stylesheet' id='crayon-theme-familiar-my-copy-css' href='https://www.dmitrymakarov.ru/wp-content/uploads/urvanov-syntax-highlighter/themes/familiar-my-copy/familiar-my-copy.css?ver=2.8.37' type='text/css' media='all' /> <link rel='stylesheet' id='crayon-font-consolas-css' href='https://www.dmitrymakarov.ru/wp-content/plugins/urvanov-syntax-highlighter/fonts/consolas.css?ver=2.8.37' type='text/css' media='all' /> <style id='wp-emoji-styles-inline-css' type='text/css'> img.wp-smiley, img.emoji { display: inline !important; border: none !important; box-shadow: none !important; height: 1em !important; width: 1em !important; margin: 0 0.07em !important; vertical-align: -0.1em !important; background: none !important; padding: 0 !important; } </style> <link rel='stylesheet' id='wp-block-library-css' href='https://www.dmitrymakarov.ru/wp-includes/css/dist/block-library/style.min.css?ver=6.6.2' type='text/css' media='all' /> <link rel='stylesheet' id='ultimate_blocks-cgb-style-css-css' href='https://www.dmitrymakarov.ru/wp-content/plugins/ultimate-blocks/dist/blocks.style.build.css?ver=672da52344e05' type='text/css' media='all' /> <style id='classic-theme-styles-inline-css' type='text/css'> /*! This file is auto-generated */ .wp-block-button__link{color:#fff;background-color:#32373c;border-radius:9999px;box-shadow:none;text-decoration:none;padding:calc(.667em + 2px) calc(1.333em + 2px);font-size:1.125em}.wp-block-file__button{background:#32373c;color:#fff;text-decoration:none} </style> <style id='global-styles-inline-css' type='text/css'> :root{--wp--preset--aspect-ratio--square: 1;--wp--preset--aspect-ratio--4-3: 4/3;--wp--preset--aspect-ratio--3-4: 3/4;--wp--preset--aspect-ratio--3-2: 3/2;--wp--preset--aspect-ratio--2-3: 2/3;--wp--preset--aspect-ratio--16-9: 16/9;--wp--preset--aspect-ratio--9-16: 9/16;--wp--preset--color--black: #121212;--wp--preset--color--cyan-bluish-gray: #abb8c3;--wp--preset--color--white: #fff;--wp--preset--color--pale-pink: #f78da7;--wp--preset--color--vivid-red: #cf2e2e;--wp--preset--color--luminous-vivid-orange: #ff6900;--wp--preset--color--luminous-vivid-amber: #fcb900;--wp--preset--color--light-green-cyan: #7bdcb5;--wp--preset--color--vivid-green-cyan: #00d084;--wp--preset--color--pale-cyan-blue: #8ed1fc;--wp--preset--color--vivid-cyan-blue: #0693e3;--wp--preset--color--vivid-purple: #9b51e0;--wp--preset--color--dark-gray: #333;--wp--preset--color--medium-gray: #555;--wp--preset--color--light-gray: #777;--wp--preset--gradient--vivid-cyan-blue-to-vivid-purple: linear-gradient(135deg,rgba(6,147,227,1) 0%,rgb(155,81,224) 100%);--wp--preset--gradient--light-green-cyan-to-vivid-green-cyan: linear-gradient(135deg,rgb(122,220,180) 0%,rgb(0,208,130) 100%);--wp--preset--gradient--luminous-vivid-amber-to-luminous-vivid-orange: linear-gradient(135deg,rgba(252,185,0,1) 0%,rgba(255,105,0,1) 100%);--wp--preset--gradient--luminous-vivid-orange-to-vivid-red: linear-gradient(135deg,rgba(255,105,0,1) 0%,rgb(207,46,46) 100%);--wp--preset--gradient--very-light-gray-to-cyan-bluish-gray: linear-gradient(135deg,rgb(238,238,238) 0%,rgb(169,184,195) 100%);--wp--preset--gradient--cool-to-warm-spectrum: linear-gradient(135deg,rgb(74,234,220) 0%,rgb(151,120,209) 20%,rgb(207,42,186) 40%,rgb(238,44,130) 60%,rgb(251,105,98) 80%,rgb(254,248,76) 100%);--wp--preset--gradient--blush-light-purple: linear-gradient(135deg,rgb(255,206,236) 0%,rgb(152,150,240) 100%);--wp--preset--gradient--blush-bordeaux: linear-gradient(135deg,rgb(254,205,165) 0%,rgb(254,45,45) 50%,rgb(107,0,62) 100%);--wp--preset--gradient--luminous-dusk: linear-gradient(135deg,rgb(255,203,112) 0%,rgb(199,81,192) 50%,rgb(65,88,208) 100%);--wp--preset--gradient--pale-ocean: linear-gradient(135deg,rgb(255,245,203) 0%,rgb(182,227,212) 50%,rgb(51,167,181) 100%);--wp--preset--gradient--electric-grass: linear-gradient(135deg,rgb(202,248,128) 0%,rgb(113,206,126) 100%);--wp--preset--gradient--midnight: linear-gradient(135deg,rgb(2,3,129) 0%,rgb(40,116,252) 100%);--wp--preset--font-size--small: 16px;--wp--preset--font-size--medium: 20px;--wp--preset--font-size--large: 24px;--wp--preset--font-size--x-large: 42px;--wp--preset--font-size--normal: 18px;--wp--preset--font-size--larger: 28px;--wp--preset--spacing--20: 0.44rem;--wp--preset--spacing--30: 0.67rem;--wp--preset--spacing--40: 1rem;--wp--preset--spacing--50: 1.5rem;--wp--preset--spacing--60: 2.25rem;--wp--preset--spacing--70: 3.38rem;--wp--preset--spacing--80: 5.06rem;--wp--preset--shadow--natural: 6px 6px 9px rgba(0, 0, 0, 0.2);--wp--preset--shadow--deep: 12px 12px 50px rgba(0, 0, 0, 0.4);--wp--preset--shadow--sharp: 6px 6px 0px rgba(0, 0, 0, 0.2);--wp--preset--shadow--outlined: 6px 6px 0px -3px rgba(255, 255, 255, 1), 6px 6px rgba(0, 0, 0, 1);--wp--preset--shadow--crisp: 6px 6px 0px rgba(0, 0, 0, 1);}:where(.is-layout-flex){gap: 0.5em;}:where(.is-layout-grid){gap: 0.5em;}body .is-layout-flex{display: flex;}.is-layout-flex{flex-wrap: wrap;align-items: center;}.is-layout-flex > :is(*, div){margin: 0;}body .is-layout-grid{display: grid;}.is-layout-grid > :is(*, div){margin: 0;}:where(.wp-block-columns.is-layout-flex){gap: 2em;}:where(.wp-block-columns.is-layout-grid){gap: 2em;}:where(.wp-block-post-template.is-layout-flex){gap: 1.25em;}:where(.wp-block-post-template.is-layout-grid){gap: 1.25em;}.has-black-color{color: var(--wp--preset--color--black) !important;}.has-cyan-bluish-gray-color{color: var(--wp--preset--color--cyan-bluish-gray) !important;}.has-white-color{color: var(--wp--preset--color--white) !important;}.has-pale-pink-color{color: var(--wp--preset--color--pale-pink) !important;}.has-vivid-red-color{color: var(--wp--preset--color--vivid-red) !important;}.has-luminous-vivid-orange-color{color: var(--wp--preset--color--luminous-vivid-orange) !important;}.has-luminous-vivid-amber-color{color: var(--wp--preset--color--luminous-vivid-amber) !important;}.has-light-green-cyan-color{color: var(--wp--preset--color--light-green-cyan) !important;}.has-vivid-green-cyan-color{color: var(--wp--preset--color--vivid-green-cyan) !important;}.has-pale-cyan-blue-color{color: var(--wp--preset--color--pale-cyan-blue) !important;}.has-vivid-cyan-blue-color{color: var(--wp--preset--color--vivid-cyan-blue) !important;}.has-vivid-purple-color{color: var(--wp--preset--color--vivid-purple) !important;}.has-black-background-color{background-color: var(--wp--preset--color--black) !important;}.has-cyan-bluish-gray-background-color{background-color: var(--wp--preset--color--cyan-bluish-gray) !important;}.has-white-background-color{background-color: var(--wp--preset--color--white) !important;}.has-pale-pink-background-color{background-color: var(--wp--preset--color--pale-pink) !important;}.has-vivid-red-background-color{background-color: var(--wp--preset--color--vivid-red) !important;}.has-luminous-vivid-orange-background-color{background-color: var(--wp--preset--color--luminous-vivid-orange) !important;}.has-luminous-vivid-amber-background-color{background-color: var(--wp--preset--color--luminous-vivid-amber) !important;}.has-light-green-cyan-background-color{background-color: var(--wp--preset--color--light-green-cyan) !important;}.has-vivid-green-cyan-background-color{background-color: var(--wp--preset--color--vivid-green-cyan) !important;}.has-pale-cyan-blue-background-color{background-color: var(--wp--preset--color--pale-cyan-blue) !important;}.has-vivid-cyan-blue-background-color{background-color: var(--wp--preset--color--vivid-cyan-blue) !important;}.has-vivid-purple-background-color{background-color: var(--wp--preset--color--vivid-purple) !important;}.has-black-border-color{border-color: var(--wp--preset--color--black) !important;}.has-cyan-bluish-gray-border-color{border-color: var(--wp--preset--color--cyan-bluish-gray) !important;}.has-white-border-color{border-color: var(--wp--preset--color--white) !important;}.has-pale-pink-border-color{border-color: var(--wp--preset--color--pale-pink) !important;}.has-vivid-red-border-color{border-color: var(--wp--preset--color--vivid-red) !important;}.has-luminous-vivid-orange-border-color{border-color: var(--wp--preset--color--luminous-vivid-orange) !important;}.has-luminous-vivid-amber-border-color{border-color: var(--wp--preset--color--luminous-vivid-amber) !important;}.has-light-green-cyan-border-color{border-color: var(--wp--preset--color--light-green-cyan) !important;}.has-vivid-green-cyan-border-color{border-color: var(--wp--preset--color--vivid-green-cyan) !important;}.has-pale-cyan-blue-border-color{border-color: var(--wp--preset--color--pale-cyan-blue) !important;}.has-vivid-cyan-blue-border-color{border-color: var(--wp--preset--color--vivid-cyan-blue) !important;}.has-vivid-purple-border-color{border-color: var(--wp--preset--color--vivid-purple) !important;}.has-vivid-cyan-blue-to-vivid-purple-gradient-background{background: var(--wp--preset--gradient--vivid-cyan-blue-to-vivid-purple) !important;}.has-light-green-cyan-to-vivid-green-cyan-gradient-background{background: var(--wp--preset--gradient--light-green-cyan-to-vivid-green-cyan) !important;}.has-luminous-vivid-amber-to-luminous-vivid-orange-gradient-background{background: var(--wp--preset--gradient--luminous-vivid-amber-to-luminous-vivid-orange) !important;}.has-luminous-vivid-orange-to-vivid-red-gradient-background{background: var(--wp--preset--gradient--luminous-vivid-orange-to-vivid-red) !important;}.has-very-light-gray-to-cyan-bluish-gray-gradient-background{background: var(--wp--preset--gradient--very-light-gray-to-cyan-bluish-gray) !important;}.has-cool-to-warm-spectrum-gradient-background{background: var(--wp--preset--gradient--cool-to-warm-spectrum) !important;}.has-blush-light-purple-gradient-background{background: var(--wp--preset--gradient--blush-light-purple) !important;}.has-blush-bordeaux-gradient-background{background: var(--wp--preset--gradient--blush-bordeaux) !important;}.has-luminous-dusk-gradient-background{background: var(--wp--preset--gradient--luminous-dusk) !important;}.has-pale-ocean-gradient-background{background: var(--wp--preset--gradient--pale-ocean) !important;}.has-electric-grass-gradient-background{background: var(--wp--preset--gradient--electric-grass) !important;}.has-midnight-gradient-background{background: var(--wp--preset--gradient--midnight) !important;}.has-small-font-size{font-size: var(--wp--preset--font-size--small) !important;}.has-medium-font-size{font-size: var(--wp--preset--font-size--medium) !important;}.has-large-font-size{font-size: var(--wp--preset--font-size--large) !important;}.has-x-large-font-size{font-size: var(--wp--preset--font-size--x-large) !important;} :where(.wp-block-post-template.is-layout-flex){gap: 1.25em;}:where(.wp-block-post-template.is-layout-grid){gap: 1.25em;} :where(.wp-block-columns.is-layout-flex){gap: 2em;}:where(.wp-block-columns.is-layout-grid){gap: 2em;} :root :where(.wp-block-pullquote){font-size: 1.5em;line-height: 1.6;} </style> <link rel='stylesheet' id='ub-extension-style-css-css' href='https://www.dmitrymakarov.ru/wp-content/plugins/ultimate-blocks/src/extensions/style.css?ver=6.6.2' type='text/css' media='all' /> <link rel='stylesheet' id='mcluhan-fonts-css' href='https://www.dmitrymakarov.ru/wp-content/themes/mcluhan/assets/css/fonts.css?ver=6.6.2' type='text/css' media='all' /> <link rel='stylesheet' id='fontawesome-css' href='https://www.dmitrymakarov.ru/wp-content/themes/mcluhan/assets/css/font-awesome.css?ver=6.6.2' type='text/css' media='all' /> <link rel='stylesheet' id='mcluhan-style-css' href='https://www.dmitrymakarov.ru/wp-content/themes/mcluhan/style.css?ver=2.1.1' type='text/css' media='all' /> <script type="text/javascript" src="https://www.dmitrymakarov.ru/wp-includes/js/jquery/jquery.min.js?ver=3.7.1" id="jquery-core-js"></script> <script type="text/javascript" src="https://www.dmitrymakarov.ru/wp-includes/js/jquery/jquery-migrate.min.js?ver=3.4.1" id="jquery-migrate-js"></script> <script type="text/javascript" id="urvanov_syntax_highlighter_js-js-extra"> /* <![CDATA[ */ var UrvanovSyntaxHighlighterSyntaxSettings = {"version":"2.8.37","is_admin":"0","ajaxurl":"https:\/\/www.dmitrymakarov.ru\/wp-admin\/admin-ajax.php","prefix":"urvanov-syntax-highlighter-","setting":"urvanov-syntax-highlighter-setting","selected":"urvanov-syntax-highlighter-setting-selected","changed":"urvanov-syntax-highlighter-setting-changed","special":"urvanov-syntax-highlighter-setting-special","orig_value":"data-orig-value","debug":""}; var UrvanovSyntaxHighlighterSyntaxStrings = {"copy":"Copied to the clipboard","minimize":"Click To Expand Code"}; /* ]]> */ </script> <script type="text/javascript" src="https://www.dmitrymakarov.ru/wp-content/plugins/urvanov-syntax-highlighter/js/min/urvanov_syntax_highlighter.min.js?ver=2.8.37" id="urvanov_syntax_highlighter_js-js"></script> <style>#ub_table-of-contents-a5c541b3-6d7a-4592-939a-1040c2c23335{ }#ub_table-of-contents-a5c541b3-6d7a-4592-939a-1040c2c23335 .ub_table-of-contents-header{ text-align: left; } #ub-content-toggle-c5b683b9-e69e-4973-9cf9-466a437bd93e{ }#ub-content-toggle-c5b683b9-e69e-4973-9cf9-466a437bd93e .wp-block-ub-content-toggle-accordion{ border-color: #f1f1f1; } #ub-content-toggle-c5b683b9-e69e-4973-9cf9-466a437bd93e .wp-block-ub-content-toggle-accordion-title-wrap{ background-color: #f1f1f1; } #ub-content-toggle-c5b683b9-e69e-4973-9cf9-466a437bd93e .wp-block-ub-content-toggle-accordion-title{ color: #000000; } #ub-content-toggle-c5b683b9-e69e-4973-9cf9-466a437bd93e .wp-block-ub-content-toggle-accordion-toggle-wrap{ color: #000000; } .ub-content-toggle-title-a2dc1cc9-427d-4aa3-a502-8d2efa765dc0 > a{ color: inherit; }#ub-content-toggle-1ccce574-f88a-45f6-8de4-67c29031266f{ }#ub-content-toggle-1ccce574-f88a-45f6-8de4-67c29031266f .wp-block-ub-content-toggle-accordion{ border-color: #f1f1f1; } #ub-content-toggle-1ccce574-f88a-45f6-8de4-67c29031266f .wp-block-ub-content-toggle-accordion-title-wrap{ background-color: #f1f1f1; } #ub-content-toggle-1ccce574-f88a-45f6-8de4-67c29031266f .wp-block-ub-content-toggle-accordion-title{ color: #000000; } #ub-content-toggle-1ccce574-f88a-45f6-8de4-67c29031266f .wp-block-ub-content-toggle-accordion-toggle-wrap{ color: #000000; } .ub-content-toggle-title-634f689f-d45c-486a-b8a7-7dd478c06f51 > a{ color: inherit; }#ub-content-toggle-883f8f7e-b08e-43e1-99e2-cf6ffde097a0{ }#ub-content-toggle-883f8f7e-b08e-43e1-99e2-cf6ffde097a0 .wp-block-ub-content-toggle-accordion{ border-color: #f1f1f1; } #ub-content-toggle-883f8f7e-b08e-43e1-99e2-cf6ffde097a0 .wp-block-ub-content-toggle-accordion-title-wrap{ background-color: #f1f1f1; } #ub-content-toggle-883f8f7e-b08e-43e1-99e2-cf6ffde097a0 .wp-block-ub-content-toggle-accordion-title{ color: #000000; } #ub-content-toggle-883f8f7e-b08e-43e1-99e2-cf6ffde097a0 .wp-block-ub-content-toggle-accordion-toggle-wrap{ color: #000000; } .ub-content-toggle-title-45f5326d-0bb8-479d-9f34-b818c46207a6 > a{ color: inherit; }#ub_divider_93531865-5cb3-4cef-8a5d-5844dc608abf{ }#ub_divider_93531865-5cb3-4cef-8a5d-5844dc608abf .ub_divider{ border-top:2px solid #ccc; margin-top: 20px; margin-bottom: 20px; width: 60%; } </style> <!-- Customizer CSS --> <style type="text/css"> body .site-header { background-color:#004235; }.social-menu.desktop { background-color:#004235; }.social-menu a:hover { color:#004235; }.social-menu a.active { color:#004235; }.mobile-menu-wrapper { background-color:#004235; }.social-menu.mobile { background-color:#004235; }.mobile-search.active { background-color:#004235; } </style> <!-- /Customizer CSS --> <script>jQuery( 'html' ).removeClass( 'no-js' ).addClass( 'js' );</script> <style type="text/css">.broken_link, a.broken_link { text-decoration: line-through; }</style><style type="text/css" id="custom-background-css"> body.custom-background { background-color: #fff9ef; } </style> <link rel="icon" href="https://www.dmitrymakarov.ru/wp-content/uploads/2021/08/cropped-wp-favicon-512-32x32.png" sizes="32x32" /> <link rel="icon" href="https://www.dmitrymakarov.ru/wp-content/uploads/2021/08/cropped-wp-favicon-512-192x192.png" sizes="192x192" /> <link rel="apple-touch-icon" href="https://www.dmitrymakarov.ru/wp-content/uploads/2021/08/cropped-wp-favicon-512-180x180.png" /> <meta name="msapplication-TileImage" content="https://www.dmitrymakarov.ru/wp-content/uploads/2021/08/cropped-wp-favicon-512-270x270.png" /> <style type="text/css" media="all"> .footnotes_reference_container {margin-top: 24px !important; margin-bottom: 0px !important;} .footnote_container_prepare > p {border-bottom: 1px solid #aaaaaa !important;} </style> </head> <body class="page-template page-template-full-width-page-template page-template-full-width-page-template-php page page-id-10052 page-child parent-pageid-1374 custom-background full-width-template"> <a class="skip-link button" href="#site-content">Перейти к содержимому</a> <header class="site-header group"> <p class="site-title"><a href="https://www.dmitrymakarov.ru" class="site-name">Машинное обучение</a></p> <div class="nav-toggle"> <div class="bar"></div> <div class="bar"></div> </div> <div class="menu-wrapper"> <ul class="main-menu desktop"> </ul> </div><!-- .menu-wrapper --> <div class="social-menu desktop"> <ul class="social-menu-inner"> <li class="social-search-wrapper"><a href="https://www.dmitrymakarov.ru/?s="></a></li> </ul><!-- .social-menu-inner --> </div><!-- .social-menu --> </header><!-- header --> <div class="mobile-menu-wrapper"> <ul class="main-menu mobile"> <li class="toggle-mobile-search-wrapper"><a href="#" class="toggle-mobile-search">Поиск</a></li> </ul><!-- .main-menu.mobile --> </div><!-- .mobile-menu-wrapper --> <div class="mobile-search"> <div class="untoggle-mobile-search"></div> <form role="search" method="get" class="search-form" action="https://www.dmitrymakarov.ru/"> <label class="screen-reader-text" for="search-form-672da5238d830">Поиск:</label> <input type="search" id="search-form-672da5238d830" class="search-field" placeholder="Введите запрос" value="" name="s" autocomplete="off" /> </button> </form> <div class="mobile-results"> <div class="results-wrapper"></div> </div> </div><!-- .mobile-search --> <div class="search-overlay"> <form role="search" method="get" class="search-form" action="https://www.dmitrymakarov.ru/"> <label class="screen-reader-text" for="search-form-672da5238d8b6">Поиск:</label> <input type="search" id="search-form-672da5238d8b6" class="search-field" placeholder="Введите запрос" value="" name="s" autocomplete="off" /> </button> </form> </div><!-- .search-overlay --> <main class="site-content" id="site-content"> <article class="post-10052 page type-page status-publish hentry missing-thumbnail"> <header class="entry-header section-inner"> <h1 class="entry-title">Программа на Питоне</h1> </header><!-- .entry-header --> <div class="entry-content section-inner"> <p class="has-light-gray-color has-text-color"><a href="https://www.dmitrymakarov.ru/">Все курсы</a> > <a href="https://www.dmitrymakarov.ru/python/">Программирование на Питоне</a> > Занятие 13</p> <p>Сегодня мы изучим в целом, как можно создать программу на Питоне.</p> <p><strong>Способ 1</strong>. Писать код в облаке в Google Colab.</p> <p><strong>Способ 2</strong>. Написать программу в отдельном файле (скрипте) с расширением <strong>.py</strong> и передать этот код специальному интерпретатору для исполнения.</p> <p><strong>Способ 3</strong>. Установить Jupyter Notebook (локальный аналог Google Colab).</p> <figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="1024" height="464" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/executing-python-1024x464.png" alt="программа на Питоне, способы исполнения кода" class="wp-image-10416" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/executing-python-1024x464.png 1024w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/executing-python-300x136.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/executing-python-768x348.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/executing-python-600x272.png 600w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/executing-python.png 1114w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure> <p>С первым способом мы уже познакомились в рамках вводного курса. Сегодня мы займемся написанием программы в отдельном файле, а в следующий раз — изучим Jupyter Notebook.</p> <p>Кроме того, мы рассмотрим возможности по созданию собственных модулей и пакетов в Питоне.</p> <div class="wp-block-ub-table-of-contents-block ub_table-of-contents" id="ub_table-of-contents-a5c541b3-6d7a-4592-939a-1040c2c23335" data-linktodivider="false" data-showtext="show" data-hidetext="hide" data-scrolltype="auto" data-initiallyhideonmobile="false" data-initiallyshow="true"><div class="ub_table-of-contents-header-container"><div class="ub_table-of-contents-header"> <div class="ub_table-of-contents-title"><strong>Содержание занятия</strong></div></div></div><div class="ub_table-of-contents-extra-container"><div class="ub_table-of-contents-container ub_table-of-contents-1-column "><ul><li><a href=https://www.dmitrymakarov.ru/python/script-13/#0-ustanovka-pitona-na-windows>Установка Питона на Windows</a><ul><li><a href=https://www.dmitrymakarov.ru/python/script-13/#1-shag-1-proverit-ustanovlen-li-piton-na-vashem-kompyutere>Шаг 1. Проверить, установлен ли Питон на вашем компьютере</a></li><li><a href=https://www.dmitrymakarov.ru/python/script-13/#2-shag-2-skachat-piton-s-ofitsialnogo-sayta>Шаг 2. Скачать Питон с официального сайта</a></li><li><a href=https://www.dmitrymakarov.ru/python/script-13/#3-shag-3-zapustit-piton-iz-komandnoy-stroki>Шаг 3. Запустить Питон из командной строки</a></li></ul></li><li><a href=https://www.dmitrymakarov.ru/python/script-13/#4-sozdanie-programmy-na-pitone>Создание программы на Питоне</a><ul><li><a href=https://www.dmitrymakarov.ru/python/script-13/#5-shag-1-skachat-redaktor-koda>Шаг 1. Скачать редактор кода</a></li><li><a href=https://www.dmitrymakarov.ru/python/script-13/#7-shag-2-napisat-programmu-na-pitone>Шаг 2. Написать программу на Питоне</a></li><li><a href=https://www.dmitrymakarov.ru/python/script-13/#8-shag-3-zapustit-programmu-iz-komandnoy-stroki>Шаг 3. Запустить программу из командной строки</a></li></ul></li><li><a href=https://www.dmitrymakarov.ru/python/script-13/#9-ustanovka-bibliotek>Установка библиотек</a><ul><li><a href=https://www.dmitrymakarov.ru/python/script-13/#10-programma-pip>Программа pip</a></li><li><a href=https://www.dmitrymakarov.ru/python/script-13/#11-ustanovka-biblioteki-numpy-cherez-pip-install>Установка библиотеки Numpy через pip install</a></li><li><a href=https://www.dmitrymakarov.ru/python/script-13/#12-ispolzovanie-ustanovlennoy-biblioteki>Использование установленной библиотеки</a></li><li><a href=https://www.dmitrymakarov.ru/python/script-13/#13-obnovlenie-i-udalenie-bibliotek>Обновление и удаление библиотек</a></li></ul></li><li><a href=https://www.dmitrymakarov.ru/python/script-13/#14-modul-v-pitone>Модуль в Питоне</a><ul><li><a href=https://www.dmitrymakarov.ru/python/script-13/#15-sozdanie-sobstvennogo-modulya>Создание собственного модуля</a></li><li><a href=https://www.dmitrymakarov.ru/python/script-13/#18-dokumentirovanie-koda-s-pomoshchyu-docstrings>Документирование кода с помощью docstrings</a></li><li><a href=https://www.dmitrymakarov.ru/python/script-13/#19-stroki-dokumentatsii-dlya-modulya-v-pitone>Строки документации для модуля в Питоне</a></li><li><a href=https://www.dmitrymakarov.ru/python/script-13/#21-zagruzka-i-import-modulya-v-google-colab>Загрузка и импорт модуля в Google Colab</a></li><li><a href=https://www.dmitrymakarov.ru/python/script-13/#22-prosmotr-dokumentatsii-modulya>Просмотр документации модуля</a></li><li><a href=https://www.dmitrymakarov.ru/python/script-13/#23-import-sobstvennogo-modulya-v-komandnoy-stroke>Импорт собственного модуля в командной строке</a></li></ul></li><li><a href=https://www.dmitrymakarov.ru/python/script-13/#26-interpretatsiya-i-kompilyatsiya>Интерпретация и компиляция</a><ul><li><a href=https://www.dmitrymakarov.ru/python/script-13/#27-kompilyator>Компилятор</a></li><li><a href=https://www.dmitrymakarov.ru/python/script-13/#28-interpretator>Интерпретатор</a></li></ul></li><li><a href=https://www.dmitrymakarov.ru/python/script-13/#29-paket-v-pitone>Пакет в Питоне</a><ul><li><a href=https://www.dmitrymakarov.ru/python/script-13/#30-sozdanie-sobstvennogo-paketa>Создание собственного пакета</a></li><li><a href=https://www.dmitrymakarov.ru/python/script-13/#36-ustanovka-i-ispolzovanie-paketa>Установка и использование пакета</a></li></ul></li><li><a href=https://www.dmitrymakarov.ru/python/script-13/#37-podvedem-itog>Подведем итог</a><ul><li><a href=https://www.dmitrymakarov.ru/python/script-13/#38-voprosy-dlya-zakrepleniya>Вопросы для закрепления</a></li><li><a href=https://www.dmitrymakarov.ru/python/script-13/#39-otvety-na-voprosy>Ответы на вопросы</a></li></ul></li></ul></div></div></div> <h2 class="wp-block-heading" id="0-ustanovka-pitona-na-windows">Установка Питона на Windows</h2> <p>Прежде чем мы начнем писать программу, нам нужно установить библиотеки (libraries) и интерпретатор (interpreter) для обработки кода.</p> <h3 class="wp-block-heading" id="1-shag-1-proverit-ustanovlen-li-piton-na-vashem-kompyutere">Шаг 1. Проверить, установлен ли Питон на вашем компьютере</h3> <p>Для этого вначале нажмите клавишу <strong>Windows</strong> и клавишу <strong>R</strong> на клавиатуре.</p> <figure class="wp-block-image size-full is-resized"><img decoding="async" width="432" height="197" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/windows-R.png" alt="клавиши Windows + R" class="wp-image-10057" style="width:186px;height:85px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/windows-R.png 432w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/windows-R-300x137.png 300w" sizes="(max-width: 432px) 100vw, 432px" /></figure> <p>В появившемся окне «Выполнить» введите <span id="urvanov-syntax-highlighter-672da52340940035027068" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">cmd</span></span> и нажмите <strong>Enter</strong>.</p> <figure class="wp-block-image size-full"><img decoding="async" width="514" height="297" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/command-line.png" alt="окно "Выполнить" в Windows" class="wp-image-10461" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/command-line.png 514w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/command-line-300x173.png 300w" sizes="(max-width: 514px) 100vw, 514px" /></figure> <p>Появится так называемая «командная строка» (Command Line Promt) — отдельная программа, позволяющая взаимодействовать с Windows не графически (как мы привыкли это делать), а через текстовые команды.</p> <figure class="wp-block-image size-full is-resized"><img loading="lazy" decoding="async" width="832" height="283" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/open-cmd.png" alt="командная строка (Command Line Promt)" class="wp-image-10462" style="width:741px;height:252px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/open-cmd.png 832w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/open-cmd-300x102.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/open-cmd-768x261.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/open-cmd-600x204.png 600w" sizes="(max-width: 832px) 100vw, 832px" /></figure> <p>Теперь введите <span id="urvanov-syntax-highlighter-672da5234094a464233929" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">python --version</span></span>. Если Питон установлен, то программа сообщит текущую версию. В противном случае появится вот такая запись.</p> <figure class="wp-block-image size-full is-resized"><img loading="lazy" decoding="async" width="880" height="315" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/is-python-installed.png" alt="проверка, установлен ли Питон" class="wp-image-10465" style="width:779px;height:278px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/is-python-installed.png 880w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/is-python-installed-300x107.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/is-python-installed-768x275.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/is-python-installed-600x215.png 600w" sizes="(max-width: 880px) 100vw, 880px" /></figure> <p>Если Питон не установлен, переходите к шагу 2. В случае если вы его уже установили, переходите сразу к шагу 3.</p> <h3 class="wp-block-heading" id="2-shag-2-skachat-piton-s-ofitsialnogo-sayta">Шаг 2. Скачать Питон с официального сайта</h3> <p>Перейдем на сайт <a href="https://www.python.org/downloads/" target="_blank" rel="noreferrer noopener">www.python.org/dowloads/</a>⧉ и скачаем, среди прочего, <a href="https://www.dmitrymakarov.ru/intro/data-and-plots-07/#0-struktura-pitona">базовый функционал</a> Питона, а также интерпретатор для Windows, который позволит нам исполнять написанный нами код.</p> <figure class="wp-block-image size-full is-resized"><img loading="lazy" decoding="async" width="859" height="425" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/latest-python-for-windows.png" alt="скачивание Питона с официального сайта" class="wp-image-10083" style="width:632px;height:312px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/latest-python-for-windows.png 859w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/latest-python-for-windows-300x148.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/latest-python-for-windows-768x380.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/latest-python-for-windows-600x297.png 600w" sizes="(max-width: 859px) 100vw, 859px" /></figure> <p>После скачивания и запуска файла откроется мастер установки.</p> <figure class="wp-block-image size-full is-resized"><img loading="lazy" decoding="async" width="873" height="648" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/install-python.png" alt="добавление Питона в переменную PATH" class="wp-image-10084" style="width:804px;height:596px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/install-python.png 873w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/install-python-300x223.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/install-python-768x570.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/install-python-600x445.png 600w" sizes="(max-width: 873px) 100vw, 873px" /></figure> <p>Нижняя галочка добавит Питон в переменную окружения PATH. Благодаря этому мы сможем исполнять код на Питоне напрямую из командной строки. Мы разберем как это делается уже на следующем шаге.</p> <p>Снова проверим установку Питона на компьютере, повторив действия <strong>Шага 1</strong>. В командной строке должна появиться установленная на данный момент версия Питона.</p> <figure class="wp-block-image size-full is-resized"><img loading="lazy" decoding="async" width="862" height="324" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/python-version.png" alt="проверка версии Питона" class="wp-image-10467" style="width:787px;height:295px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/python-version.png 862w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/python-version-300x113.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/python-version-768x289.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/python-version-600x226.png 600w" sizes="(max-width: 862px) 100vw, 862px" /></figure> <h3 class="wp-block-heading" id="3-shag-3-zapustit-piton-iz-komandnoy-stroki">Шаг 3. Запустить Питон из командной строки</h3> <p>Теперь давайте введем в командной строке команду <span id="urvanov-syntax-highlighter-672da5234094c051269154" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">py</span></span>. Должны появиться символы <span id="urvanov-syntax-highlighter-672da5234094d770241539" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">>>></span></span>.</p> <figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="863" height="398" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/python-interactive.png" alt="запуск Питона из командной строки" class="wp-image-10469" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/python-interactive.png 863w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/python-interactive-300x138.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/python-interactive-768x354.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/python-interactive-600x277.png 600w" sizes="(max-width: 863px) 100vw, 863px" /></figure> <p class="has-background" style="background-color:#ffe8c4">Это значит, что командная строка перешла в интерактивный режим, и мы можем писать код на Питоне.</p> <p>Напишем классическую фразу:</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da5234094f599666031" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234094f599666031-1">1</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234094f599666031-1"><span class="crayon-k ">print</span><span class="crayon-sy">(</span><span class="crayon-s">'Hello World!'</span><span class="crayon-sy">)</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0001 seconds] --> </div> <p>При корректном исполнении кода фраза будет выведена на экран.</p> <figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="859" height="417" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/hw-python.png" alt="написание и исполнение кода на Питоне в интерактивном режиме" class="wp-image-10470" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/hw-python.png 859w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/hw-python-300x146.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/hw-python-768x373.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/hw-python-600x291.png 600w" sizes="(max-width: 859px) 100vw, 859px" /></figure> <p>Однако, как вы помните, наша задача — исполнить не отдельную команду, а скрипт, то есть целую программу на Питоне, а для этого нам нужно эту программу создать.</p> <p>Поэтому выйдем из интерактивного режима с помощью команды <span id="urvanov-syntax-highlighter-672da52340950609066639" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">quit()</span></span> или <span id="urvanov-syntax-highlighter-672da52340951908454434" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">exit()</span></span>, закроем окно командной строки и перейдем к созданию программы на Питоне.</p> <h2 class="wp-block-heading" id="4-sozdanie-programmy-na-pitone">Создание программы на Питоне</h2> <p>Технически для создания программы нам понадобится редактор кода. В нем мы будем создавать файлы с расширением <strong>.py</strong> и передавать их интерпретатору.</p> <h3 class="wp-block-heading" id="5-shag-1-skachat-redaktor-koda">Шаг 1. Скачать редактор кода</h3> <p>Редактор кода — это текстовый редактор, который, среди прочего, правильно подсвечивает код на том языке, на котором вы программируете.</p> <p>В принципе, если вы работаете на Windows, то можете воспользоваться и «Блокнотом» (Notepad), который уже установлен в этой операционной системе (MS Word использовать не стоит). Достаточно написать в нем код, сохранить файл и изменить расширение с <strong>.txt</strong> на <strong>.py</strong>.</p> <p class="has-background" style="background-color:#ffe8c4">Если вы не видите расширения файлов, в «Проводнике» нажмите на вкладку «Вид» и поставьте галочку напротив «Расширения имен файлов».</p> <p>При этом гораздо удобнее писать код в специально предназначенных для этого редакторах. Приведу ссылки на несколько популярных программ.</p> <ul class="wp-block-list"> <li><a href="https://notepad-plus-plus.org/downloads/" target="_blank" rel="noreferrer noopener">Notepad++</a>⧉</li> <li><a href="https://www.sublimetext.com/" target="_blank" rel="noreferrer noopener">Sublime</a>⧉</li> <li><a href="https://github.com/atom/atom" target="_blank" rel="noreferrer noopener">Atom</a>⧉</li> </ul> <p>На сегодняшнем занятии мы будем использовать Atom.</p> <p class="has-background" style="background-color:#ffe8c4">Примечание. Редактор Atom был архивирован 3 марта 2023 года. Используйте два других редактора. Логика работы в каждом из них остается примерно той же.</p> <h4 class="wp-block-heading" id="6-redaktor-atom">Редактор Atom</h4> <p>После установки и запуска редактора Atom закройте ненужные вкладки и нажмите <strong>File</strong> → <strong>New File</strong>.</p> <p>Затем, чтобы сообщить редактору, что мы хотим писать код на Питоне, сохраним этот файл с расширением <strong>.py</strong>. Для этого нажмем <strong>File</strong> → <strong>Save As</strong> и сохраним файл, например, под именем <strong>script.py</strong> на Рабочий стол.</p> <figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="735" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/script-in-atom-1024x735.png" alt="интерфейс редактора Atom" class="wp-image-10472" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/script-in-atom-1024x735.png 1024w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/script-in-atom-300x215.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/script-in-atom-768x551.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/script-in-atom-600x431.png 600w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/script-in-atom.png 1169w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure> <p>Благодаря расширению <strong>.py</strong> Atom будет знать, что в файле <strong>script.py</strong> мы собираемся писать код на Питоне.</p> <h3 class="wp-block-heading" id="7-shag-2-napisat-programmu-na-pitone">Шаг 2. Написать программу на Питоне</h3> <p>Первой программой будет <strong>алгоритм линейного поиска</strong> (linear search algorithm). Этот алгоритм проверяет наличие числа в массиве путем простого перебора всех значений от первого до последнего.</p> <figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="302" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/linear-search-1024x302.jpg" alt="алгоритм линейного поиска" class="wp-image-10506" style="width:555px;height:163px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/linear-search-1024x302.jpg 1024w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/linear-search-300x88.jpg 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/linear-search-768x227.jpg 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/linear-search-1536x453.jpg 1536w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/linear-search-1200x354.jpg 1200w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/linear-search-600x177.jpg 600w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/linear-search.jpg 1902w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure> <p>Напишем такую программу в редакторе Atom и сохраним файл <strong>script.py</strong>.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340952619135568" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340952619135568-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340952619135568-2">2</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340952619135568-3">3</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340952619135568-4">4</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340952619135568-5">5</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340952619135568-6">6</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340952619135568-7">7</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340952619135568-8">8</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340952619135568-9">9</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340952619135568-10">10</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340952619135568-11">11</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340952619135568-12">12</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340952619135568-13">13</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340952619135568-14">14</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340952619135568-1"><span class="crayon-c"># возьмем массив,</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340952619135568-2"><span class="crayon-v">arr</span><span class="crayon-h"> </span><span class="crayon-o">=</span><span class="crayon-h"> </span><span class="crayon-sy">[</span><span class="crayon-cn">3</span><span class="crayon-sy">,</span><span class="crayon-h"> </span><span class="crayon-cn">7</span><span class="crayon-sy">,</span><span class="crayon-h"> </span><span class="crayon-cn">0</span><span class="crayon-sy">,</span><span class="crayon-h"> </span><span class="crayon-cn">2</span><span class="crayon-sy">,</span><span class="crayon-h"> </span><span class="crayon-cn">5</span><span class="crayon-sy">]</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340952619135568-3"> </div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340952619135568-4"><span class="crayon-c"># в котором нам нужно найти число 2</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340952619135568-5"><span class="crayon-v">x</span><span class="crayon-h"> </span><span class="crayon-o">=</span><span class="crayon-h"> </span><span class="crayon-cn">2</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340952619135568-6"> </div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340952619135568-7"><span class="crayon-c"># в цикле пройдемся по индексу массива</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340952619135568-8"><span class="crayon-st">for</span><span class="crayon-h"> </span><span class="crayon-i">i</span><span class="crayon-h"> </span><span class="crayon-st">in</span><span class="crayon-h"> </span><span class="crayon-k ">range</span><span class="crayon-sy">(</span><span class="crayon-k ">len</span><span class="crayon-sy">(</span><span class="crayon-v">arr</span><span class="crayon-sy">)</span><span class="crayon-sy">)</span><span class="crayon-o">:</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340952619135568-9"> </div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340952619135568-10"><span class="crayon-h"> </span><span class="crayon-c"># если искомое число находится на этом индексе</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340952619135568-11"><span class="crayon-h"> </span><span class="crayon-st">if</span><span class="crayon-h"> </span><span class="crayon-sy">(</span><span class="crayon-v">arr</span><span class="crayon-sy">[</span><span class="crayon-v">i</span><span class="crayon-sy">]</span><span class="crayon-h"> </span><span class="crayon-o">==</span><span class="crayon-h"> </span><span class="crayon-v">x</span><span class="crayon-sy">)</span><span class="crayon-o">:</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340952619135568-12"> </div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340952619135568-13"><span class="crayon-h"> </span><span class="crayon-c"># выведем индекс</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340952619135568-14"><span class="crayon-h"> </span><span class="crayon-k ">print</span><span class="crayon-sy">(</span><span class="crayon-v">i</span><span class="crayon-sy">)</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0004 seconds] --> </div> <p>Если у вас не получилось создать файл в редакторе Atom, вы можете его скачать.</p> <div class="wp-block-file"><a id="wp-block-file--media-02bd39d3-bb20-428e-9c22-48a2ebd473c0" href="https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/script.zip">script.zip</a><a href="https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/script.zip" class="wp-block-file__button wp-element-button" download aria-describedby="wp-block-file--media-02bd39d3-bb20-428e-9c22-48a2ebd473c0">Скачать</a></div> <p>В результате исполнения этого кода компьютер должен выдать цифру три, потому что искомое число два находится именно под этим индексом. Посмотрим, так ли это.</p> <h3 class="wp-block-heading" id="8-shag-3-zapustit-programmu-iz-komandnoy-stroki">Шаг 3. Запустить программу из командной строки</h3> <p>Запустим этот код с помощью командной строки.</p> <ol class="wp-block-list"> <li>Откроем командную строку через клавиши <strong>Window + R</strong> → <span id="urvanov-syntax-highlighter-672da52340953188688808" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">cmd</span></span>. Перейдем на Рабочий стол (напомню, файл <strong>script.py</strong> мы сохранили именно туда) с помощью команды <span id="urvanov-syntax-highlighter-672da52340954090859434" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">cd Desktop</span></span>.</li> </ol> <p>Команда cd (change directory) позволяет перейти в другую папку, а Desktop — это Рабочий стол, то есть название той папки, куда мы хотим перейти. В результате командная строка должна выглядеть вот так:</p> <figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="878" height="426" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/cd-desktop.png" alt="смена папки в командной строке" class="wp-image-10474" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/cd-desktop.png 878w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/cd-desktop-300x146.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/cd-desktop-768x373.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/cd-desktop-600x291.png 600w" sizes="(max-width: 878px) 100vw, 878px" /></figure> <ol start="2" class="wp-block-list"> <li>Теперь просто введите <strong>script.py</strong>. Так мы вызовем интерпретатор и исполним код.</li> </ol> <figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="892" height="411" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/python-script-execution.png" alt="исполнение программы на Питоне в командной строке" class="wp-image-10475" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/python-script-execution.png 892w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/python-script-execution-300x138.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/python-script-execution-768x354.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/python-script-execution-600x276.png 600w" sizes="(max-width: 892px) 100vw, 892px" /></figure> <p>Все, наша первая программа на Питоне готова.</p> <h2 class="wp-block-heading" id="9-ustanovka-bibliotek">Установка библиотек</h2> <p>Как уже было сказано, по умолчанию, с сайта www.python.org устанавливается лишь <a href="https://www.dmitrymakarov.ru/intro/data-and-plots-07/#0-struktura-pitona">базовый функционал</a>. Если мы хотим использовать, например, библиотеку Numpy или библиотеку Matplotlib нам нужно установить их отдельно. В этом нам поможет программа pip.</p> <h3 class="wp-block-heading" id="10-programma-pip">Программа pip</h3> <p><strong>pip</strong> — это программа, которая помогает устанавливать (обновлять и удалять) дополнительные библиотеки на вашем компьютере. По сути эта программа связывается с репозиторием (хранилищем) пакетов/библиотек <strong>Python Package Index</strong> или <strong>PyPI</strong> (<a href="https://pypi.org/" target="_blank" rel="noreferrer noopener">pypi.org</a>⧉) и скачивает запрашиваемые файлы.</p> <p>Все действия осуществляются из командной строки.</p> <p>Если вы устанавливали Питон в соответствии с приведенной выше инструкцией, то pip уже присутствует на вашем компьютере. Проверить это можно с помощью команды <span id="urvanov-syntax-highlighter-672da52340956150092969" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">pip --version</span></span>.</p> <figure class="wp-block-image size-full is-resized"><img loading="lazy" decoding="async" width="904" height="394" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-version-1.png" alt="проверка версии программы pip" class="wp-image-10476" style="width:753px;height:328px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-version-1.png 904w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-version-1-300x131.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-version-1-768x335.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-version-1-600x262.png 600w" sizes="(max-width: 904px) 100vw, 904px" /></figure> <p>Кроме того, мы можем посмотреть на список всех установленных на компьютере библиотек через команду <span id="urvanov-syntax-highlighter-672da52340957566840361" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">pip list</span></span>.</p> <figure class="wp-block-image size-full is-resized"><img loading="lazy" decoding="async" width="943" height="400" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-list-1.png" alt="список установленных библиотек Питона" class="wp-image-10477" style="width:819px;height:347px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-list-1.png 943w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-list-1-300x127.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-list-1-768x326.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-list-1-600x255.png 600w" sizes="(max-width: 943px) 100vw, 943px" /></figure> <h3 class="wp-block-heading" id="11-ustanovka-biblioteki-numpy-cherez-pip-install">Установка библиотеки Numpy через pip install</h3> <p>Установим библиотеку Numpy. Для этого введем в командной строке <span id="urvanov-syntax-highlighter-672da52340958594294891" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">pip install numpy</span></span>.</p> <figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="943" height="440" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-install-numpy.png" alt="установка Numpy через pip" class="wp-image-10478" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-install-numpy.png 943w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-install-numpy-300x140.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-install-numpy-768x358.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-install-numpy-600x280.png 600w" sizes="(max-width: 943px) 100vw, 943px" /></figure> <p>Проверить установку отдельного пакета можно с помощью команды <span id="urvanov-syntax-highlighter-672da52340959072730017" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">pip show numpy</span></span>.</p> <figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="932" height="487" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-show-numpy-1.png" alt="проверка версии Numpy" class="wp-image-10480" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-show-numpy-1.png 932w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-show-numpy-1-300x157.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-show-numpy-1-768x401.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-show-numpy-1-600x314.png 600w" sizes="(max-width: 932px) 100vw, 932px" /></figure> <h3 class="wp-block-heading" id="12-ispolzovanie-ustanovlennoy-biblioteki">Использование установленной библиотеки</h3> <p>Теперь мы можем использовать установленную библиотеку Numpy внутри командной строки. Вначале перейдем в интерактивный режим с помощью команды <strong>py</strong>. После этого построчно (каждый раз нажимая <strong>Enter</strong>) введем следующие команды:</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da5234095a059668258" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095a059668258-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095a059668258-2">2</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095a059668258-3">3</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234095a059668258-1">import numpy as np</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234095a059668258-2">arr=np.array([1, 2, 3])</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234095a059668258-3">type(arr)</div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0000 seconds] --> </div> <figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="886" height="403" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/import-numpy-in-cmd.png" alt="использование установленной через pip библиотеки" class="wp-image-10481" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/import-numpy-in-cmd.png 886w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/import-numpy-in-cmd-300x136.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/import-numpy-in-cmd-768x349.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/import-numpy-in-cmd-600x273.png 600w" sizes="(max-width: 886px) 100vw, 886px" /></figure> <p>Как мы видим, в результате исполнения этого кода Питон успешно создал <a href="https://www.dmitrymakarov.ru/python/numpy-09/">массив Numpy</a>.</p> <h3 class="wp-block-heading" id="13-obnovlenie-i-udalenie-bibliotek">Обновление и удаление библиотек</h3> <p>Создатели библиотек периодически вносят в них обновления, и эти обновления полезно скачивать на свой компьютер. Воспользуйтесь следующей командой: <span id="urvanov-syntax-highlighter-672da5234095b122692366" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">pip install --upgrade numpy</span></span>.</p> <figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="925" height="404" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-install-upgrade-numpy.png" alt="обновление библиотек через pip" class="wp-image-10482" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-install-upgrade-numpy.png 925w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-install-upgrade-numpy-300x131.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-install-upgrade-numpy-768x335.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-install-upgrade-numpy-600x262.png 600w" sizes="(max-width: 925px) 100vw, 925px" /></figure> <p>Для удаления пакета введите команду <span id="urvanov-syntax-highlighter-672da5234095c450113897" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">pip uninstall numpy</span></span>.</p> <figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="983" height="451" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-uninstall-numpy.png" alt="удаление библиотек через pip" class="wp-image-10483" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-uninstall-numpy.png 983w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-uninstall-numpy-300x138.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-uninstall-numpy-768x352.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/pip-uninstall-numpy-600x275.png 600w" sizes="(max-width: 983px) 100vw, 983px" /></figure> <p>В процессе удаления будет нужно нажать <strong>Y + Enter</strong> для подтверждения операции. Другие библиотеки устанавливаются, обновляются и удаляются точно так же.</p> <h2 class="wp-block-heading" id="14-modul-v-pitone">Модуль в Питоне</h2> <p>Помимо использования Питона в интерактивном режиме и запуска кода из файла мы можем создавать собственные модули.</p> <p class="has-background" style="background-color:#ffe8c4">Модуль в Питоне — это программа на Питоне (файл с расширением <strong>.py</strong>), которую мы можем использовать в других программах с помощью команды <strong>import</strong>.</p> <p>Создание собственного модуля может быть полезно, если вы написали код, который затем будете много раз использовать в других программах.</p> <h3 class="wp-block-heading" id="15-sozdanie-sobstvennogo-modulya">Создание собственного модуля</h3> <p>Наш первый модуль на Питоне будет состоять из двух алгоритмов поиска: линейного и бинарного.</p> <h4 class="wp-block-heading" id="16-algoritm-lineynogo-poiska">Алгоритм линейного поиска</h4> <p>Алгоритм линейного поиска у нас уже готов. Достаточно «обернуть» его в <a href="https://www.dmitrymakarov.ru/python/functions-06/#3-sobstvennye-funktsii-v-pitone">функцию</a>.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da5234095d179044566" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095d179044566-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095d179044566-2">2</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095d179044566-3">3</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095d179044566-4">4</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095d179044566-5">5</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234095d179044566-1"><span class="crayon-c"># объявим функцию linear()</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234095d179044566-2"><span class="crayon-r">def</span><span class="crayon-h"> </span><span class="crayon-e">linear</span><span class="crayon-sy">(</span><span class="crayon-v">arr</span><span class="crayon-sy">,</span><span class="crayon-h"> </span><span class="crayon-v">x</span><span class="crayon-sy">)</span><span class="crayon-o">:</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234095d179044566-3"><span class="crayon-h"> </span><span class="crayon-st">for</span><span class="crayon-h"> </span><span class="crayon-i">i</span><span class="crayon-h"> </span><span class="crayon-st">in</span><span class="crayon-h"> </span><span class="crayon-k ">range</span><span class="crayon-sy">(</span><span class="crayon-k ">len</span><span class="crayon-sy">(</span><span class="crayon-v">arr</span><span class="crayon-sy">)</span><span class="crayon-sy">)</span><span class="crayon-o">:</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234095d179044566-4"><span class="crayon-h"> </span><span class="crayon-st">if</span><span class="crayon-h"> </span><span class="crayon-v">arr</span><span class="crayon-sy">[</span><span class="crayon-v">i</span><span class="crayon-sy">]</span><span class="crayon-h"> </span><span class="crayon-o">==</span><span class="crayon-h"> </span><span class="crayon-v">x</span><span class="crayon-o">:</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234095d179044566-5"><span class="crayon-h"> </span><span class="crayon-st">return</span><span class="crayon-h"> </span><span class="crayon-v">i</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0003 seconds] --> </div> <p>Теперь перейдем к бинарному поиску.</p> <h4 class="wp-block-heading" id="17-algoritm-binarnogo-poiska">Алгоритм бинарного поиска</h4> <p>Вначале поговорим о том, что такое бинарный поиск. Представьте, что у вас есть телефонная книга, и вам нужно найти номер телефона определенного человека.</p> <figure class="wp-block-image size-full is-resized"><img loading="lazy" decoding="async" width="840" height="553" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/phone-book.png" alt="телефонная книга" class="wp-image-10504" style="width:254px;height:167px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/phone-book.png 840w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/phone-book-300x198.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/phone-book-768x506.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/phone-book-600x395.png 600w" sizes="(max-width: 840px) 100vw, 840px" /></figure> <p>Если фамилия этого человека начинается с буквы «А», то мы довольно быстро найдем его номер, используя уже известный нам алгоритм линейного поиска. А если он Яковлев? Линейному поиску придется перебрать все буквы от «А» до «Я».</p> <p>Бинарный же поиск действует иначе. Вначале мы открываем книгу посередине, скажем, на букве «П».</p> <figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="217" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/binary-search-1-1024x217.jpg" alt="алгоритм бинарного поиска: поиск по словарю" class="wp-image-10501" style="width:637px;height:135px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/binary-search-1-1024x217.jpg 1024w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/binary-search-1-300x64.jpg 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/binary-search-1-768x163.jpg 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/binary-search-1-1536x326.jpg 1536w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/binary-search-1-1200x255.jpg 1200w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/binary-search-1-600x127.jpg 600w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/binary-search-1.jpg 1678w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure> <p>После этого мы посмотрим, находится ли буква «Я» в первой или во второй половине книги. Так как «Я» очевидно находится во второй половине справочника, мы разобьем пополам вторую половину. И снова посмотрим справа искомая буква или слева.</p> <figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="232" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/binary-search-2-1024x232.jpg" alt="алгоритм бинарного поиска: поиск по словарю 2" class="wp-image-10502" style="width:641px;height:145px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/binary-search-2-1024x232.jpg 1024w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/binary-search-2-300x68.jpg 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/binary-search-2-768x174.jpg 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/binary-search-2-1536x349.jpg 1536w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/binary-search-2-1200x272.jpg 1200w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/binary-search-2-600x136.jpg 600w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/02/binary-search-2.jpg 1687w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure> <p>Так мы будем действовать до тех пор, пока не найдем нужную нам букву.</p> <p class="has-background" style="background-color:#ffe8c4">Важно, что в случае бинарного поиска элементы всегда <strong>упорядочены</strong>.</p> <p>Напишем код такого алгоритма на Питоне, только поиск будем выполнять не по буквам, а по числам.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da5234095e128480182" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-2">2</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-3">3</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-4">4</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-5">5</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-6">6</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-7">7</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-8">8</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-9">9</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-10">10</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-11">11</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-12">12</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-13">13</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-14">14</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-15">15</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-16">16</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-17">17</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-18">18</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-19">19</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-20">20</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-21">21</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-22">22</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-23">23</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-24">24</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-25">25</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-26">26</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-27">27</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-28">28</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-29">29</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-30">30</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-31">31</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-32">32</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-33">33</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-34">34</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-35">35</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-36">36</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-37">37</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-38">38</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-39">39</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-40">40</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-41">41</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-42">42</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-43">43</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-44">44</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-45">45</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234095e128480182-46">46</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size: … [Строка слишком длинная. Вы можете скачать файл] </tr> </table> </div> </div> <!-- [Format Time: 0.0011 seconds] --> </div> <p>Хотя это уводит нас в сторону от темы сегодняшнего занятия, поясню код нахождения индекса среднего значения списка.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340960807274381" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340960807274381-1">1</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340960807274381-1"><span class="crayon-v">mid</span><span class="crayon-h"> </span><span class="crayon-o">=</span><span class="crayon-h"> </span><span class="crayon-v">low</span><span class="crayon-h"> </span><span class="crayon-o">+</span><span class="crayon-h"> </span><span class="crayon-sy">(</span><span class="crayon-v">high</span><span class="crayon-h"> </span><span class="crayon-o">-</span><span class="crayon-h"> </span><span class="crayon-v">low</span><span class="crayon-sy">)</span><span class="crayon-h"> </span><span class="crayon-o">/</span><span class="crayon-o">/</span><span class="crayon-h"> </span><span class="crayon-cn">2</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0002 seconds] --> </div> <p>На первый взгляд индекс среднего значения можно найти вот так</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340961078509092" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340961078509092-1">1</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340961078509092-1"><span class="crayon-sy">(</span><span class="crayon-v">high</span><span class="crayon-h"> </span><span class="crayon-o">+</span><span class="crayon-h"> </span><span class="crayon-v">low</span><span class="crayon-sy">)</span><span class="crayon-h"> </span><span class="crayon-o">/</span><span class="crayon-o">/</span><span class="crayon-h"> </span><span class="crayon-cn">2</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0001 seconds] --> </div> <p>Однако первый вариант расчета индекса среднего значения позволяет избежать переполнения памяти (memory overflow) при использовании слишком больших значений.</p> <p>Также замечу, что мы используем оператор целочисленного деления <span id="urvanov-syntax-highlighter-672da52340962712535122" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><span class="crayon-o">/</span><span class="crayon-o">/</span></span></span>, потому что в Питоне результатом <a href="https://www.dmitrymakarov.ru/python/data-types-02/#2-operatsii-s-chislami">обычного деления</a> является число с плавающей точкой (float). Индекс же таким числом быть не может.</p> <p>Полностью код для обоих алгоритмов будет выглядеть следующим образом.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340963042700259" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-2">2</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-3">3</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-4">4</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-5">5</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-6">6</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-7">7</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-8">8</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-9">9</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-10">10</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-11">11</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-12">12</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-13">13</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-14">14</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-15">15</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-16">16</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-17">17</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-18">18</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-19">19</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-20">20</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-21">21</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-22">22</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-23">23</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-24">24</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-25">25</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-26">26</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-27">27</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-28">28</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-29">29</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-30">30</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-31">31</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340963042700259-32">32</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size: … [Строка слишком длинная. Вы можете скачать файл] </tr> </table> </div> </div> <!-- [Format Time: 0.0012 seconds] --> </div> <h3 class="wp-block-heading" id="18-dokumentirovanie-koda-s-pomoshchyu-docstrings">Документирование кода с помощью docstrings</h3> <p>До сих пор мы писали комментарии, которые помогали нам разобраться в том, как работает та или иная часть кода. При этом, такие комментарии при исполнении кода полностью пропадают.</p> <p class="has-background" style="background-color:#ffe8c4">Одновременно в Питоне существуют так называемые <strong>строки документации</strong> (docstrings). Они используются для описания работы функции, метода, класса или модуля. Доступ к ним можно получить через <strong>атрибут __doc__</strong> или <strong>функцию help()</strong>.</p> <p>В чем основные особенности создания docstrings?</p> <ul class="wp-block-list"> <li>Docstrings заключаются в тройные одинарные или двойные кавычки;</li> <li>Их следует располагать сразу после объявления функции, метода, класса или модуля.</li> </ul> <p>Добавим соответствующие docstrings в только что созданный нами модуль и параллельно разберем основные принципы написания документации. Начнем с модуля в целом.</p> <h3 class="wp-block-heading" id="19-stroki-dokumentatsii-dlya-modulya-v-pitone">Строки документации для модуля в Питоне</h3> <p>Документация модуля описывает модуль и перечисляет все доступные функции и классы. Например, для модуля mymodule документация могла бы выглядеть следующим образом.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340964704527406" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340964704527406-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340964704527406-2">2</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340964704527406-3">3</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340964704527406-4">4</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340964704527406-5">5</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340964704527406-6">6</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340964704527406-7">7</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340964704527406-8">8</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340964704527406-9">9</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340964704527406-10">10</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340964704527406-11">11</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340964704527406-12">12</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340964704527406-13">13</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340964704527406-14">14</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340964704527406-1"><span class="crayon-s">"""</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340964704527406-2"><span class="crayon-s">Модуль для поиска элементов в массиве чисел.</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340964704527406-3"><span class="crayon-s">============================================</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340964704527406-4"> </div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340964704527406-5"><span class="crayon-s">Classes</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340964704527406-6"><span class="crayon-s">-------</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340964704527406-7"> </div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340964704527406-8"><span class="crayon-s">BinarySearch</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340964704527406-9"> </div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340964704527406-10"> </div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340964704527406-11"><span class="crayon-s">Functions</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340964704527406-12"><span class="crayon-s">---------</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340964704527406-13"><span class="crayon-s">linear</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340964704527406-14"><span class="crayon-s">"""</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0001 seconds] --> </div> <p>Строки документации для функции описывают саму функцию, параметры и возвращаемое значение. Напишем документацию к функции <strong>linear()</strong>.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340965014257668" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340965014257668-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340965014257668-2">2</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340965014257668-3">3</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340965014257668-4">4</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340965014257668-5">5</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340965014257668-6">6</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340965014257668-7">7</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340965014257668-8">8</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340965014257668-9">9</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340965014257668-10">10</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340965014257668-11">11</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340965014257668-12">12</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340965014257668-13">13</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340965014257668-14">14</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340965014257668-15">15</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340965014257668-16">16</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340965014257668-17">17</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340965014257668-18">18</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340965014257668-19">19</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340965014257668-20">20</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340965014257668-21">21</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340965014257668-1"><span class="crayon-r">def</span><span class="crayon-h"> </span><span class="crayon-e">linear</span><span class="crayon-sy">(</span><span class="crayon-v">arr</span><span class="crayon-sy">,</span><span class="crayon-h"> </span><span class="crayon-v">x</span><span class="crayon-sy">)</span><span class="crayon-o">:</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340965014257668-2"><span class="crayon-h"> </span><span class="crayon-s">"""Выполняет линейный поиск по массиву чисел.</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340965014257668-3"> </div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340965014257668-4"><span class="crayon-s"> Parameters</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340965014257668-5"><span class="crayon-s"> ----------</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340965014257668-6"><span class="crayon-s"> arr : {list, ndarray}</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340965014257668-7"><span class="crayon-s"> Массив чисел, по которому выполняется поиск.</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340965014257668-8"><span class="crayon-s"> </span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340965014257668-9"><span class="crayon-s"> x : int</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340965014257668-10"><span class="crayon-s"> Искомое число.</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340965014257668-11"> </div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340965014257668-12"> </div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340965014257668-13"><span class="crayon-s"> Returns</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340965014257668-14"><span class="crayon-s"> -------</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340965014257668-15"><span class="crayon-s"> i : int</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340965014257668-16"><span class="crayon-s"> Индекс искомого числа, если оно присутствует в массиве.</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340965014257668-17"> </div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340965014257668-18"><span class="crayon-s"> """</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340965014257668-19"><span class="crayon-h"> </span><span class="crayon-st">for</span><span class="crayon-h"> </span><span class="crayon-i">i</span><span class="crayon-h"> </span><span class="crayon-st">in</span><span class="crayon-h"> </span><span class="crayon-k ">range</span><span class="crayon-sy">(</span><span class="crayon-k ">len</span><span class="crayon-sy">(</span><span class="crayon-v">arr</span><span class="crayon-sy">)</span><span class="crayon-sy">)</span><span class="crayon-o">:</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340965014257668-20"><span class="crayon-h"> </span><span class="crayon-st">if</span><span class="crayon-h"> </span><span class="crayon-v">arr</span><span class="crayon-sy">[</span><span class="crayon-v">i</span><span class="crayon-sy">]</span><span class="crayon-h"> </span><span class="crayon-o">==</span><span class="crayon-h"> </span><span class="crayon-v">x</span><span class="crayon-o">:</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340965014257668-21"><span class="crayon-h"> </span><span class="crayon-st">return</span><span class="crayon-h"> </span><span class="crayon-v">i</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0003 seconds] --> </div> <p>Строки документации для класса описывают сам класс, а также перечисляют доступные атрибуты и методы. Каждый метод внутри класса сопровождается отдельной документацией.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340966511774486" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-2">2</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-3">3</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-4">4</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-5">5</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-6">6</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-7">7</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-8">8</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-9">9</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-10">10</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-11">11</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-12">12</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-13">13</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-14">14</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-15">15</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-16">16</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-17">17</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-18">18</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-19">19</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-20">20</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-21">21</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-22">22</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-23">23</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-24">24</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-25">25</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-26">26</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-27">27</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-28">28</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-29">29</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-30">30</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-31">31</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-32">32</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-33">33</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-34">34</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-35">35</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-36">36</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-37">37</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-38">38</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-39">39</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-40">40</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-41">41</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-42">42</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-43">43</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-44">44</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-45">45</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-46">46</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-47">47</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-48">48</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-49">49</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-50">50</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-51">51</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-52">52</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-53">53</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-54">54</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-55">55</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-56">56</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-57">57</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-58">58</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-59">59</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-60">60</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340966511774486-61">61</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size: … [Строка слишком длинная. Вы можете скачать файл] </tr> </table> </div> </div> <!-- [Format Time: 0.0011 seconds] --> </div> <p>Полностью снабженный документацией модуль выглядит следующим образом.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340967198057990" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da523409671 … [Строка слишком длинная. Вы можете скачать файл] </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size: … [Строка слишком длинная. Вы можете скачать файл] </tr> </table> </div> </div> <!-- [Format Time: 0.0013 seconds] --> </div> <p class="has-background" style="background-color:#ffe8c4">Замечу, что в данном случае мы использовали <strong>стиль документирования Numpy</strong> (NumPy documentation style). Он используется во многих известных пакетах: NumPy, SciPy, Pandas или, например, Scikit-Learn. При этом существуют и другие стили документирования.</p> <p>Сохраним этот файл под именем <strong>mymodule.py</strong>. Все, наш модуль готов. Если у вас не получилось создать этот файл, вы можете скачать его по ссылке ниже.</p> <div class="wp-block-file"><a id="wp-block-file--media-bbfc36b4-b2e7-4684-88ad-93a2007c1739" href="https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/mymodule.zip">mymodule.zip</a><a href="https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/mymodule.zip" class="wp-block-file__button wp-element-button" download aria-describedby="wp-block-file--media-bbfc36b4-b2e7-4684-88ad-93a2007c1739">Скачать</a></div> <h4 class="wp-block-heading" id="20-sozdanie-dokumentatsii-s-pomoshchyu-pyment">Создание документации с помощью Pyment</h4> <p>Дополнительно замечу, что шаблон или «каркас» документации можно создать с помощью специального пакета Pyment. Для этого:</p> <ol class="wp-block-list"> <li>скачайте пакет Pyment через <span id="urvanov-syntax-highlighter-672da52340969814080795" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">pip install pyment</span></span>;</li> <li>убедитесь, что командная строка указывает на ту папку, в которой находится ваш модуль <strong>mymodule.py</strong> (например, на Рабочий стол);</li> <li>введите команду <span id="urvanov-syntax-highlighter-672da5234096a879604106" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">pyment -w -o numpydoc mymodule.py</span></span>. В данном случае вы буквально просите pyment создать документацию в стиле Numpy в файле под названием <strong>mymodule.py</strong>;</li> <li>откройте файл в редакторе кода и начинайте заполнять шаблон.</li> </ol> <h3 class="wp-block-heading" id="21-zagruzka-i-import-modulya-v-google-colab">Загрузка и импорт модуля в Google Colab</h3> <p class="has-text-align-center has-white-color has-text-color has-background" style="background-color:#004235"><a href="https://colab.research.google.com/drive/1s43oY2Yj3sLjYVYEQcRq3qrjPfEvICsG?usp=sharing" target="_blank" rel="noreferrer noopener">Откроем блокнот к этому занятию</a>⧉</p> <p>Давайте <a href="https://www.dmitrymakarov.ru/python/files-04/#2-etap-1-podgruzka-faylov-v-google-colab">подгрузим файл</a> <strong>mymodule.py</strong> в сессионное хранилище Google Colab.</p> <figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="584" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/colab-mymodule-1024x584.png" alt="подгрузка собственного модуля на Питоне в Google Colab" class="wp-image-10802" style="width:691px;height:394px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/colab-mymodule-1024x584.png 1024w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/colab-mymodule-300x171.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/colab-mymodule-768x438.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/colab-mymodule-600x342.png 600w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/colab-mymodule.png 1125w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure> <p>Теперь мы можем работать с этим модулем так, как мы работали с функциями модуля random или классами библиотеки sklearn.</p> <p>Вначале импортируем функцию <strong>linear()</strong> из модуля <strong>mymodule</strong>.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da5234096b165328127" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234096b165328127-1">1</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234096b165328127-1"><span class="crayon-st">from</span><span class="crayon-h"> </span><span class="crayon-e">mymodule </span><span class="crayon-r">import</span><span class="crayon-h"> </span><span class="crayon-v">linear</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0001 seconds] --> </div> <p>Создадим список, по которому будет выполняться поиск, а также искомое число.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da5234096c030356495" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234096c030356495-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234096c030356495-2">2</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234096c030356495-1"><span class="crayon-v">arr</span><span class="crayon-h"> </span><span class="crayon-o">=</span><span class="crayon-h"> </span><span class="crayon-sy">[</span><span class="crayon-cn">3</span><span class="crayon-sy">,</span><span class="crayon-h"> </span><span class="crayon-cn">7</span><span class="crayon-sy">,</span><span class="crayon-h"> </span><span class="crayon-cn">0</span><span class="crayon-sy">,</span><span class="crayon-h"> </span><span class="crayon-cn">2</span><span class="crayon-sy">,</span><span class="crayon-h"> </span><span class="crayon-cn">5</span><span class="crayon-sy">]</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234096c030356495-2"><span class="crayon-v">target</span><span class="crayon-h"> </span><span class="crayon-o">=</span><span class="crayon-h"> </span><span class="crayon-cn">2</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0002 seconds] --> </div> <p>Вызовем функцию <strong>linear()</strong> и передадим ей список и целевое значение в качестве аргументов.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da5234096d115620552" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234096d115620552-1">1</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234096d115620552-1"><span class="crayon-e">linear</span><span class="crayon-sy">(</span><span class="crayon-v">arr</span><span class="crayon-sy">,</span><span class="crayon-h"> </span><span class="crayon-v">target</span><span class="crayon-sy">)</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0001 seconds] --> </div> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da5234096e147955171" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234096e147955171-1">1</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234096e147955171-1">3</div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0000 seconds] --> </div> <p>Теперь возьмем список большего размера и другое целевое значение.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da5234096f601155312" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234096f601155312-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234096f601155312-2">2</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234096f601155312-1"><span class="crayon-v">arr</span><span class="crayon-h"> </span><span class="crayon-o">=</span><span class="crayon-h"> </span><span class="crayon-sy">[</span><span class="crayon-cn">9</span><span class="crayon-sy">,</span><span class="crayon-h"> </span><span class="crayon-cn">3</span><span class="crayon-sy">,</span><span class="crayon-h"> </span><span class="crayon-cn">343</span><span class="crayon-sy">,</span><span class="crayon-h"> </span><span class="crayon-cn">5</span><span class="crayon-sy">,</span><span class="crayon-h"> </span><span class="crayon-cn">8</span><span class="crayon-sy">,</span><span class="crayon-h"> </span><span class="crayon-cn">1</span><span class="crayon-sy">,</span><span class="crayon-h"> </span><span class="crayon-cn">20111</span><span class="crayon-sy">,</span><span class="crayon-h"> </span><span class="crayon-cn">32</span><span class="crayon-sy">,</span><span class="crayon-h"> </span><span class="crayon-cn">11</span><span class="crayon-sy">,</span><span class="crayon-h"> </span><span class="crayon-cn">6</span><span class="crayon-sy">,</span><span class="crayon-h"> </span><span class="crayon-cn">4</span><span class="crayon-sy">]</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234096f601155312-2"><span class="crayon-v">target</span><span class="crayon-h"> </span><span class="crayon-o">=</span><span class="crayon-h"> </span><span class="crayon-cn">9</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0003 seconds] --> </div> <p>Импортируем модуль <strong>mymodule</strong> под псевдонимом <strong>mm</strong>.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340970993306964" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340970993306964-1">1</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340970993306964-1"><span class="crayon-r">import</span><span class="crayon-h"> </span><span class="crayon-e">mymodule </span><span class="crayon-st">as</span><span class="crayon-h"> </span><span class="crayon-v">mm</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0001 seconds] --> </div> <p>Воспользуемся бинарным поиском. Для этого вначале создадим объект класса <strong>BinarySearch</strong> и поместим его в переменную src.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340971512557039" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340971512557039-1">1</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340971512557039-1"><span class="crayon-v">src</span><span class="crayon-h"> </span><span class="crayon-o">=</span><span class="crayon-h"> </span><span class="crayon-v">mm</span><span class="crayon-sy">.</span><span class="crayon-e">BinarySearch</span><span class="crayon-sy">(</span><span class="crayon-sy">)</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0001 seconds] --> </div> <p>Прежде чем выполнить поиск нам необходимо отсортировать список чисел. Вызовем <strong>метод .srt()</strong> класса <strong>BinarySearch</strong>.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340972871865365" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340972871865365-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340972871865365-2">2</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340972871865365-3">3</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340972871865365-4">4</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340972871865365-5">5</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340972871865365-1"><span class="crayon-c"># передадим методу .srt() список arr для сортировки</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340972871865365-2"><span class="crayon-v">sorted_arr</span><span class="crayon-h"> </span><span class="crayon-o">=</span><span class="crayon-h"> </span><span class="crayon-v">srch</span><span class="crayon-sy">.</span><span class="crayon-e">srt</span><span class="crayon-sy">(</span><span class="crayon-v">arr</span><span class="crayon-sy">)</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340972871865365-3"> </div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340972871865365-4"><span class="crayon-c"># посмотрим на результат</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340972871865365-5"><span class="crayon-v">sorted_arr</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0001 seconds] --> </div> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340973363413279" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340973363413279-1">1</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340973363413279-1">[1, 3, 4, 5, 6, 8, 9, 11, 32, 343, 20111]</div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0000 seconds] --> </div> <p>Теперь воспользуемся <strong>методом .check()</strong>, чтобы проверить, присутствует ли в списке число девять.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340974057209730" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340974057209730-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340974057209730-2">2</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340974057209730-1"><span class="crayon-c"># напомню, что индекс числа 9 мы будем отсчитывать с нуля</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340974057209730-2"><span class="crayon-v">src</span><span class="crayon-sy">.</span><span class="crayon-e">check</span><span class="crayon-sy">(</span><span class="crayon-v">sorted_arr</span><span class="crayon-sy">,</span><span class="crayon-h"> </span><span class="crayon-v">target</span><span class="crayon-sy">)</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0001 seconds] --> </div> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340975295149213" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340975295149213-1">1</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340975295149213-1">6</div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0000 seconds] --> </div> <p>В отсортированном списке это число присутствует под индексом шесть.</p> <h3 class="wp-block-heading" id="22-prosmotr-dokumentatsii-modulya">Просмотр документации модуля</h3> <p>Вначале выведем документацию модуля в целом.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340976815547296" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340976815547296-1">1</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340976815547296-1"><span class="crayon-k ">print</span><span class="crayon-sy">(</span><span class="crayon-v">mm</span><span class="crayon-sy">.</span><span class="crayon-v">__doc__</span><span class="crayon-sy">)</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0001 seconds] --> </div> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340977125815066" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340977125815066-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340977125815066-2">2</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340977125815066-3">3</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340977125815066-4">4</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340977125815066-5">5</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340977125815066-6">6</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340977125815066-7">7</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340977125815066-8">8</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340977125815066-9">9</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340977125815066-10">10</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340977125815066-11">11</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340977125815066-12">12</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340977125815066-1">Модуль для поиска элементов в массиве чисел.</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340977125815066-2">============================================</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340977125815066-3"> </div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340977125815066-4">Classes</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340977125815066-5">-------</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340977125815066-6"> </div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340977125815066-7">BinarySearch</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340977125815066-8"> </div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340977125815066-9"> </div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340977125815066-10">Functions</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340977125815066-11">---------</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340977125815066-12">linear</div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0000 seconds] --> </div> <p>Посмотрим на функию linear().</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340978518556291" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340978518556291-1">1</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340978518556291-1"><span class="crayon-k ">print</span><span class="crayon-sy">(</span><span class="crayon-v">mm</span><span class="crayon-sy">.</span><span class="crayon-v">linear</span><span class="crayon-sy">.</span><span class="crayon-v">__doc__</span><span class="crayon-sy">)</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0001 seconds] --> </div> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340979184557390" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340979184557390-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340979184557390-2">2</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340979184557390-3">3</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340979184557390-4">4</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340979184557390-5">5</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340979184557390-6">6</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340979184557390-7">7</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340979184557390-8">8</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340979184557390-9">9</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340979184557390-10">10</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340979184557390-11">11</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340979184557390-12">12</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340979184557390-13">13</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340979184557390-14">14</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340979184557390-15">15</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340979184557390-1">Выполняет линейный поиск по массиву чисел.</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340979184557390-2"> </div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340979184557390-3"> Parameters</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340979184557390-4"> ----------</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340979184557390-5"> arr : {list, ndarray}</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340979184557390-6"> Массив чисел, по которому выполняется поиск.</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340979184557390-7"> </div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340979184557390-8"> x : int</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340979184557390-9"> Искомое число.</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340979184557390-10"> </div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340979184557390-11"> </div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340979184557390-12"> Returns</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340979184557390-13"> -------</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340979184557390-14"> i : int</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340979184557390-15"> Индекс искомого числа, если оно присутствует в массиве.</div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0000 seconds] --> </div> <p>И класс BinarySearch.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da5234097a973573780" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234097a973573780-1">1</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234097a973573780-1"><span class="crayon-k ">print</span><span class="crayon-sy">(</span><span class="crayon-v">mm</span><span class="crayon-sy">.</span><span class="crayon-v">BinarySearch</span><span class="crayon-sy">.</span><span class="crayon-v">__doc__</span><span class="crayon-sy">)</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0001 seconds] --> </div> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da5234097b389065116" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234097b389065116-1">1</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234097b389065116-1">Бинарный поиск по массиву чисел.</div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0000 seconds] --> </div> <p>Мы также можем посмотреть документацию отдельного метода внутри класса.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da5234097c626194556" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234097c626194556-1">1</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234097c626194556-1"><span class="crayon-k ">print</span><span class="crayon-sy">(</span><span class="crayon-v">mm</span><span class="crayon-sy">.</span><span class="crayon-v">BinarySearch</span><span class="crayon-sy">.</span><span class="crayon-v">srt</span><span class="crayon-sy">.</span><span class="crayon-v">__doc__</span><span class="crayon-sy">)</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0001 seconds] --> </div> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da5234097d141475340" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234097d141475340-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234097d141475340-2">2</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234097d141475340-3">3</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234097d141475340-4">4</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234097d141475340-5">5</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234097d141475340-6">6</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234097d141475340-7">7</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234097d141475340-8">8</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234097d141475340-9">9</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234097d141475340-10">10</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234097d141475340-11">11</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234097d141475340-12">12</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234097d141475340-1">Сортирует массив чисел в возрастающем порядке.</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234097d141475340-2"> </div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234097d141475340-3"> Parameters</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234097d141475340-4"> ----------</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234097d141475340-5"> arr : {list, ndarray}</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234097d141475340-6"> Массив для сортировки.</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234097d141475340-7"> </div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234097d141475340-8"> </div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234097d141475340-9"> Returns</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234097d141475340-10"> -------</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234097d141475340-11"> arr : {list, ndarray}</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234097d141475340-12"> Массив, отсортированный в возрастающем порядке.</div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0000 seconds] --> </div> <p>Напомню, что документацию можно также посмотреть с помощью <a href="https://www.dmitrymakarov.ru/python/numpy-09/#59-dokumentatsiya">функции help()</a>.</p> <h3 class="wp-block-heading" id="23-import-sobstvennogo-modulya-v-komandnoy-stroke">Импорт собственного модуля в командной строке</h3> <p>Модуль в Питоне не обязательно подгружать в Google Colab, его также можно импортировать локально в командной строке.</p> <p>Когда в интерактивном режиме мы пытаемся импортировать модуль с помощью команды <strong>import</strong>, Питон начинает искать этот модуль в конкретных папках. Посмотреть, что это за папки можно с помощью встроенного в базовый функционал модуля <strong>sys</strong>. В интерактивном режиме (команда <span id="urvanov-syntax-highlighter-672da5234097e593994612" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">py</span></span>) последовательно введите следующие команды.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da5234097f235817500" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234097f235817500-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234097f235817500-2">2</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234097f235817500-1">import sys</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234097f235817500-2">sys.path</div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0000 seconds] --> </div> <figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="994" height="500" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/sys.path_.png" alt="содержание переменной sys.path" class="wp-image-10798" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/sys.path_.png 994w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/sys.path_-300x151.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/sys.path_-768x386.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/sys.path_-600x302.png 600w" sizes="(max-width: 994px) 100vw, 994px" /></figure> <p class="has-background" style="background-color:#ffe8c4">Обратите внимание, что первой в списке <span id="urvanov-syntax-highlighter-672da52340980145180003" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">['']</span></span> указана текущая папка.</p> <p>Если ваш модуль не находится в одной из этих папок, импортировать его не получится. Здесь есть два варианта: либо переместить файл в одну из указанных папок, либо добавить новую папку в переменную <strong>path</strong>.</p> <h5 class="wp-block-heading" id="24-sposob-1-peremestit-fayl-v-papku-iz-spiska">Способ 1. Переместить файл в папку из списка</h5> <p>Текущая папка будет иметь адрес, похожий на <span id="urvanov-syntax-highlighter-672da52340981317769467" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">C:\Users\user</span></span> (замените <strong>user</strong> на имя вашей учетной записи). Введите этот адрес в Проводнике.</p> <figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="564" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/image-1024x564.png" alt="ввод адреса в Проводнике на Windows" class="wp-image-10799" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/image-1024x564.png 1024w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/image-300x165.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/image-768x423.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/image-600x330.png 600w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/image.png 1046w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure> <p>Переместите туда наш модуль <strong>mymodule.py</strong>. Теперь войдем в интерактивный режим (команда <span id="urvanov-syntax-highlighter-672da52340982836087699" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">py</span></span>) и импортируем модуль с помощью команды <span id="urvanov-syntax-highlighter-672da52340983833309244" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">import</span></span>. После этого создадим массив, целевую переменную и вызовем функцию <strong>linear()</strong>.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340984332325576" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340984332325576-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340984332325576-2">2</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340984332325576-3">3</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340984332325576-4">4</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340984332325576-1">import mymodule</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340984332325576-2">arr = [3, 7, 0, 2, 5]</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340984332325576-3">target = 2</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340984332325576-4">mymodule.linear(arr, target)</div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0000 seconds] --> </div> <figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1003" height="499" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/import-mymodule.png" alt="импорт модуля на Питоне в интерактивном режиме из командной строки" class="wp-image-10801" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/import-mymodule.png 1003w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/import-mymodule-300x149.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/import-mymodule-768x382.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/import-mymodule-600x299.png 600w" sizes="(max-width: 1003px) 100vw, 1003px" /></figure> <p>Как вы видите, мы смогли успешно импортировать наш модуль и использовать необходимую функцию.</p> <h5 class="wp-block-heading" id="25-sposob-2-dobavit-novyy-put-papku-v-peremennuyu-path">Способ 2. Добавить новый путь (папку) в переменную path</h5> <p>Добавим Рабочий стол в список <strong>sys.path</strong>. Для этого прекрасно подойдет <strong>метод .append()</strong>, который мы использовали для обычных <a href="https://www.dmitrymakarov.ru/python/list-tuple-set-07/#0-spiski">питоновских списков</a>.</p> <p>Например, добавим Desktop (Рабочий стол).</p> <figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="420" height="41" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/add-desktop-to-sys.png" alt="добавление папки в переменную sys.path" class="wp-image-12853" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/add-desktop-to-sys.png 420w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/add-desktop-to-sys-300x29.png 300w" sizes="(max-width: 420px) 100vw, 420px" /></figure> <p>Не забудьте заменить user на имя пользователя на вашем компьютере, а также обратите внимание на двойные обратные косые черты <span id="urvanov-syntax-highlighter-672da52340985301381711" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><span class="crayon-sy">\</span><span class="crayon-sy">\</span></span></span> в абсолютном пути к папке Desktop.</p> <figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="986" height="660" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/sys.path_.append.png" alt="содержание переменной sys.path после добавления папки" class="wp-image-10807" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/sys.path_.append.png 986w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/sys.path_.append-300x201.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/sys.path_.append-768x514.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/sys.path_.append-600x402.png 600w" sizes="(max-width: 986px) 100vw, 986px" /></figure> <p>Мы готовы импортировать наш модуль с Рабочего стола. Вернем файл <strong>mymodule.py</strong> на Рабочий стол, войдем в интерактивный режим (команда <span id="urvanov-syntax-highlighter-672da52340986168384581" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">py</span></span> и последовательно введем код ниже.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340987943681141" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340987943681141-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340987943681141-2">2</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340987943681141-3">3</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340987943681141-4">4</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340987943681141-1">import mymodule</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340987943681141-2">arr = [3, 7, 0, 2, 5]</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340987943681141-3">target = 2</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340987943681141-4">mymodule.linear(arr, target)</div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0000 seconds] --> </div> <figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="978" height="399" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/module-from-desktop.png" alt="импорт модуля из добавленной в sys.path папки" class="wp-image-10808" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/module-from-desktop.png 978w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/module-from-desktop-300x122.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/module-from-desktop-768x313.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/module-from-desktop-600x245.png 600w" sizes="(max-width: 978px) 100vw, 978px" /></figure> <p>Нам снова удалось импортировать необходимую нам <strong>функцию linear()</strong>.</p> <h2 class="wp-block-heading" id="26-interpretatsiya-i-kompilyatsiya">Интерпретация и компиляция</h2> <p>Небольшое отступление от темы занятия. В самом начале мы сказали, что вместе с базовым функционалом Питона мы импортируем еще и интерпретатор. Давайте, разберемся, что это такое.</p> <p class="has-background" style="background-color:#ffe8c4">Как вы помните, компьютер понимает только нули и единицы, но никак не код на Питоне. Перевести понятный человеку язык программирования на машинный можно двумя способами: через <strong>компилятор</strong> (compiler) и через <strong>интерпретатор</strong> (interpreter).</p> <p>Проведем следующую аналогию. Предположим, что у нас есть текст, скажем, на французском языке, и нам нужно понять, что в нем написано.</p> <h3 class="wp-block-heading" id="27-kompilyator">Компилятор</h3> <p>Первый вариант, отдать текст в бюро переводов. Там выполнят перевод всего документа и вернут текст на русском языке. Если в исходный текст внесут изменения, нам придется вновь заказывать его перевод. Можно сказать, что бюро переводов — это компилятор.</p> <p>Компилятор берет файл с понятным человеку исходным кодом, переводит его в нули и единицы и сохраняет получившийся машинный код в исполняемом (executable) файле (на Windows — это файл с расширением .exe).</p> <figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="147" src="https://www.dmitrymakarov.ru/wp-content/uploads/2024/05/compiler_pr-1024x147.jpg" alt="компилятор" class="wp-image-26696" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2024/05/compiler_pr-1024x147.jpg 1024w, https://www.dmitrymakarov.ru/wp-content/uploads/2024/05/compiler_pr-300x43.jpg 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2024/05/compiler_pr-768x110.jpg 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2024/05/compiler_pr-1536x220.jpg 1536w, https://www.dmitrymakarov.ru/wp-content/uploads/2024/05/compiler_pr-1200x172.jpg 1200w, https://www.dmitrymakarov.ru/wp-content/uploads/2024/05/compiler_pr-600x86.jpg 600w, https://www.dmitrymakarov.ru/wp-content/uploads/2024/05/compiler_pr.jpg 1791w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure> <p>После этого мы можем запустить файл .exe и увидеть результат работы программы.</p> <h3 class="wp-block-heading" id="28-interpretator">Интерпретатор</h3> <p>Интерпетатор действует иначе. Возвращаясь к аналогии с текстом на французском языке, вместо того чтобы отправлять документ в бюро переводов, мы просим человека, говорящего на этом языке на ходу, с листа передавать нам содержание текста.</p> <figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="137" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/interpreter-process-1024x137.jpg" alt="интерпретатор" class="wp-image-11059" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/interpreter-process-1024x137.jpg 1024w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/interpreter-process-300x40.jpg 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/interpreter-process-768x103.jpg 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/interpreter-process-1536x205.jpg 1536w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/interpreter-process-2048x274.jpg 2048w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/interpreter-process-1200x160.jpg 1200w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/interpreter-process-600x80.jpg 600w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure> <p>Другими словами, интерпретатор — это программа, которая позволяет обрабатывать код и сразу выдавать результат.</p> <p class="has-background" style="background-color:#ffe8c4">Как следствие, языки делятся на компилируемые и интерпретируемые. Питон относится к интерпретируемым языкам, а, например, С — к компилируемым.</p> <p>Впрочем, программа на Питоне может быть скомпилирована, например, с помощью пакета PyInstaller. </p> <p>Кроме того, возможно вы обратили внимание, что когда мы вызывали модуль mymodule в командной строке, то Питон автоматически создал папку под названием __pycache__.pyc. В ней содержится скомпилированный байт-код программы (промежуточный код между Питоном и машинным языком), который ускоряет последующий запуск нашего модуля.</p> <h2 class="wp-block-heading" id="29-paket-v-pitone">Пакет в Питоне</h2> <p>Поговорим про пакеты. Предположим, что вы создали довольно много полезных функций и классов и хранить их в одном модуле не слишком удобно. Самое время задуматься над созданием собственного пакета (package).</p> <figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="200" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/script-module-package-1024x200.jpg" alt="программа на Питоне (скрипт) - модуль - пакет" class="wp-image-11060" style="width:625px;height:122px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/script-module-package-1024x200.jpg 1024w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/script-module-package-300x59.jpg 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/script-module-package-768x150.jpg 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/script-module-package-1536x300.jpg 1536w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/script-module-package-1200x235.jpg 1200w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/script-module-package-600x117.jpg 600w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/03/script-module-package.jpg 1888w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure> <p>Примечание. Некоторые пакеты (например, Numpy или Pandas) принято называть библиотеками. При этом с технической точки зрения пакет и библиотека — это одно и то же.</p> <h3 class="wp-block-heading" id="30-sozdanie-sobstvennogo-paketa">Создание собственного пакета</h3> <p>В качестве упражнения создадим несложный пакет на Питоне и поместим его в тестовый репозиторий TestPyPI. Это своего рода «песочница», в которой можно научиться создавать пакеты перед их загрузкой в «большой» репозиторий PyPI.</p> <p class="has-background" style="background-color:#ffe8c4">Обратите внимание, PyPI и TestPyPI — это разные сайты, для которых требуются разные учетные записи. </p> <p>Добавлю, что по большей части этот раздел создан на основе примера, приведенного в <a href="https://packaging.python.org/en/latest/tutorials/packaging-projects/" target="_blank" rel="noreferrer noopener">документации Питона</a>⧉.</p> <h4 class="wp-block-heading" id="31-shag-1-sozdanie-uchetnoy-zapisi">Шаг 1. Создание учетной записи</h4> <p>В первую очередь зарегистрируйтесь на сайте <a href="https://test.pypi.org/" target="_blank" rel="noreferrer noopener">https://test.pypi.org/</a>⧉.</p> <h4 class="wp-block-heading" id="32-shag-2-sozdanie-faylov">Шаг 2. Создание файлов</h4> <p>Теперь создайте пакет example_package (по сути, набор папок и файлов) со следующей структурой.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340988312487533" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340988312487533-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340988312487533-2">2</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340988312487533-3">3</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340988312487533-4">4</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340988312487533-5">5</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340988312487533-1">base/</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340988312487533-2">└── src/</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340988312487533-3"> └── example_package/</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340988312487533-4"> ├── __init__.py</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340988312487533-5"> └── example_module.py</div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0000 seconds] --> </div> <p>В пакет мы поместим модуль <strong>example_module.py</strong>. В модуле объявим функцию для возведения числа в квадрат <strong>square()</strong>.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da5234098a070751901" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-2">2</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-3">3</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-4">4</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-5">5</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-6">6</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-7">7</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-8">8</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-9">9</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-10">10</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-11">11</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-12">12</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-13">13</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-14">14</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-15">15</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-16">16</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-17">17</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-18">18</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-19">19</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-20">20</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-21">21</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-22">22</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-23">23</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-24">24</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-25">25</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-26">26</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234098a070751901-27">27</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234098a070751901-1"><span class="crayon-s">"""</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234098a070751901-2"><span class="crayon-s">Модуль для выполнения арифметических операций.</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234098a070751901-3"><span class="crayon-s">============================================</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234098a070751901-4"><span class="crayon-s"> </span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234098a070751901-5"><span class="crayon-s">Functions</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234098a070751901-6"><span class="crayon-s">---------</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234098a070751901-7"><span class="crayon-s">square</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234098a070751901-8"><span class="crayon-s">"""</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234098a070751901-9"> </div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234098a070751901-10"> </div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234098a070751901-11"><span class="crayon-r">def</span><span class="crayon-h"> </span><span class="crayon-e">square</span><span class="crayon-sy">(</span><span class="crayon-v">number</span><span class="crayon-sy">)</span><span class="crayon-o">:</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234098a070751901-12"><span class="crayon-h"> </span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234098a070751901-13"><span class="crayon-h"> </span><span class="crayon-s">"""Возводит число в квадрат.</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234098a070751901-14"><span class="crayon-s"> </span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234098a070751901-15"><span class="crayon-s"> Parameters</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234098a070751901-16"><span class="crayon-s"> ---------- </span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234098a070751901-17"><span class="crayon-s"> number : int</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234098a070751901-18"><span class="crayon-s"> Возводимое во вторую степень число.</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234098a070751901-19"><span class="crayon-s"> </span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234098a070751901-20"><span class="crayon-s"> </span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234098a070751901-21"><span class="crayon-s"> Returns</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234098a070751901-22"><span class="crayon-s"> -------</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234098a070751901-23"><span class="crayon-s"> int</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234098a070751901-24"><span class="crayon-s"> Квадрат числа.</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234098a070751901-25"><span class="crayon-s"> """</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234098a070751901-26"><span class="crayon-h"> </span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234098a070751901-27"><span class="crayon-h"> </span><span class="crayon-st">return</span><span class="crayon-h"> </span><span class="crayon-v">number</span><span class="crayon-h"> </span><span class="crayon-o">*</span><span class="crayon-o">*</span><span class="crayon-h"> </span><span class="crayon-cn">2</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0002 seconds] --> </div> <p>Также создадим пустой файл <strong>__init__.py</strong>. Он необходим для того, чтобы папка распознавалась именно как питоновский пакет.</p> <p class="has-background" style="background-color:#ffe8c4">Все последующие инструкции в командной строке будут выполняться из папки base/.</p> <p>Например, если папка base/ находится на Рабочем столе, то перейти в нее можно с помощью команды <span id="urvanov-syntax-highlighter-672da5234098b342519779" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">cd Desktop\base</span></span>.</p> <figure class="wp-block-image size-full is-resized"><img loading="lazy" decoding="async" width="838" height="365" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/cd_desktop_base.png" alt="переход в папку base в командной строке" class="wp-image-12030" style="width:682px;height:297px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/cd_desktop_base.png 838w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/cd_desktop_base-300x131.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/cd_desktop_base-768x335.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/cd_desktop_base-600x261.png 600w" sizes="(max-width: 838px) 100vw, 838px" /></figure> <h5 class="wp-block-heading" id="33-dopolnitelnye-fayly">Дополнительные файлы</h5> <p>Теперь давайте немного усложним структуру и добавим новые файлы.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da5234098c065966106" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234098c065966106-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234098c065966106-2">2</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234098c065966106-3">3</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234098c065966106-4">4</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234098c065966106-5">5</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234098c065966106-6">6</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234098c065966106-7">7</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234098c065966106-8">8</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234098c065966106-9">9</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234098c065966106-1">base/</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234098c065966106-2">├── LICENSE.txt</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234098c065966106-3">├── pyproject.toml</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234098c065966106-4">├── README.md</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234098c065966106-5">├── setup.py</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234098c065966106-6">└── src/</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234098c065966106-7"> └── example_package/</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234098c065966106-8"> ├── __init__.py</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234098c065966106-9"> └── example_module.py</div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0000 seconds] --> </div> <ol class="wp-block-list"> <li>В файл <strong>pyproject.toml</strong> поместим следующий код:</li> </ol> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da5234098d839739345" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234098d839739345-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da5234098d839739345-2">2</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234098d839739345-3">3</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234098d839739345-1">[build-system]</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da5234098d839739345-2">requires = ["setuptools>=42"]</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234098d839739345-3">build-backend = "setuptools.build_meta"</div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0000 seconds] --> </div> <p> <span id="urvanov-syntax-highlighter-672da5234098e321689033" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">build-system.requires</span></span> указывает на пакеты, необходимые для создания дистрибутива (то есть готового к распространению пакета), <span id="urvanov-syntax-highlighter-672da5234098f528206595" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">build-system.build-backend</span></span> прописывает, какой объект будет использован для его создания.</p> <ol start="2" class="wp-block-list"> <li>В <strong>setuptools.py</strong> содержится информация о пакете. Там же прописывается, какие файлы следует использовать при создании дистрибутива.</li> </ol> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340990156518098" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-2">2</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-3">3</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-4">4</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-5">5</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-6">6</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-7">7</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-8">8</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-9">9</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-10">10</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-11">11</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-12">12</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-13">13</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-14">14</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-15">15</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-16">16</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-17">17</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-18">18</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-19">19</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-20">20</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-21">21</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-22">22</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-23">23</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-24">24</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-25">25</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340990156518098-26">26</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340990156518098-1"><span class="crayon-r">import</span><span class="crayon-h"> </span><span class="crayon-e">setuptools</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340990156518098-2"> </div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340990156518098-3"><span class="crayon-st">with</span><span class="crayon-h"> </span><span class="crayon-k ">open</span><span class="crayon-sy">(</span><span class="crayon-s">"README.md"</span><span class="crayon-sy">,</span><span class="crayon-h"> </span><span class="crayon-s">"r"</span><span class="crayon-sy">,</span><span class="crayon-h"> </span><span class="crayon-v">encoding</span><span class="crayon-o">=</span><span class="crayon-s">"utf-8"</span><span class="crayon-sy">)</span><span class="crayon-h"> </span><span class="crayon-st">as</span><span class="crayon-h"> </span><span class="crayon-v">fh</span><span class="crayon-o">:</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340990156518098-4"><span class="crayon-h"> </span><span class="crayon-v">long_description</span><span class="crayon-h"> </span><span class="crayon-o">=</span><span class="crayon-h"> </span><span class="crayon-v">fh</span><span class="crayon-sy">.</span><span class="crayon-e">read</span><span class="crayon-sy">(</span><span class="crayon-sy">)</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340990156518098-5"> </div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340990156518098-6"><span class="crayon-v">setuptools</span><span class="crayon-sy">.</span><span class="crayon-e">setup</span><span class="crayon-sy">(</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340990156518098-7"><span class="crayon-h"> </span><span class="crayon-v">name</span><span class="crayon-o">=</span><span class="crayon-s">"example-package-DmitryMakarov"</span><span class="crayon-sy">,</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340990156518098-8"><span class="crayon-h"> </span><span class="crayon-v">version</span><span class="crayon-o">=</span><span class="crayon-s">"0.0.1"</span><span class="crayon-sy">,</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340990156518098-9"><span class="crayon-h"> </span><span class="crayon-v">author</span><span class="crayon-o">=</span><span class="crayon-s">"Dmitry Makarov"</span><span class="crayon-sy">,</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340990156518098-10"><span class="crayon-h"> </span><span class="crayon-v">author_email</span><span class="crayon-o">=</span><span class="crayon-s">"dm.v.makarov@gmail.com"</span><span class="crayon-sy">,</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340990156518098-11"><span class="crayon-h"> </span><span class="crayon-v">description</span><span class="crayon-o">=</span><span class="crayon-s">"Simple arithmetic package"</span><span class="crayon-sy">,</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340990156518098-12"><span class="crayon-h"> </span><span class="crayon-v">long_description</span><span class="crayon-o">=</span><span class="crayon-v">long_description</span><span class="crayon-sy">,</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340990156518098-13"><span class="crayon-h"> </span><span class="crayon-v">long_description_content_type</span><span class="crayon-o">=</span><span class="crayon-s">"text/markdown"</span><span class="crayon-sy">,</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340990156518098-14"><span class="crayon-h"> </span><span class="crayon-v">url</span><span class="crayon-o">=</span><span class="crayon-s">"https://github.com"</span><span class="crayon-sy">,</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340990156518098-15"><span class="crayon-h"> </span><span class="crayon-v">project_urls</span><span class="crayon-o">=</span><span class="crayon-sy">{</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340990156518098-16"><span class="crayon-h"> </span><span class="crayon-s">"Bug Tracker"</span><span class="crayon-o">:</span><span class="crayon-h"> </span><span class="crayon-s">"https://github.com"</span><span class="crayon-sy">,</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340990156518098-17"><span class="crayon-h"> </span><span class="crayon-sy">}</span><span class="crayon-sy">,</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340990156518098-18"><span class="crayon-h"> </span><span class="crayon-v">classifiers</span><span class="crayon-o">=</span><span class="crayon-sy">[</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340990156518098-19"><span class="crayon-h"> </span><span class="crayon-s">"Programming Language :: Python :: 3"</span><span class="crayon-sy">,</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340990156518098-20"><span class="crayon-h"> </span><span class="crayon-s">"License :: OSI Approved :: MIT License"</span><span class="crayon-sy">,</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340990156518098-21"><span class="crayon-h"> </span><span class="crayon-s">"Operating System :: OS Independent"</span><span class="crayon-sy">,</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340990156518098-22"><span class="crayon-h"> </span><span class="crayon-sy">]</span><span class="crayon-sy">,</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340990156518098-23"><span class="crayon-h"> </span><span class="crayon-v">package_dir</span><span class="crayon-o">=</span><span class="crayon-sy">{</span><span class="crayon-s">""</span><span class="crayon-o">:</span><span class="crayon-h"> </span><span class="crayon-s">"src"</span><span class="crayon-sy">}</span><span class="crayon-sy">,</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340990156518098-24"><span class="crayon-h"> </span><span class="crayon-v">packages</span><span class="crayon-o">=</span><span class="crayon-v">setuptools</span><span class="crayon-sy">.</span><span class="crayon-e">find_packages</span><span class="crayon-sy">(</span><span class="crayon-v">where</span><span class="crayon-o">=</span><span class="crayon-s">"src"</span><span class="crayon-sy">)</span><span class="crayon-sy">,</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340990156518098-25"><span class="crayon-h"> </span><span class="crayon-v">python_requires</span><span class="crayon-o">=</span><span class="crayon-s">">=3.6"</span><span class="crayon-sy">,</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340990156518098-26"><span class="crayon-sy">)</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0008 seconds] --> </div> <p>Вначале мы импортируем пакет setuptools. После этого открываем файл README.md и помещаем его содержимое в переменную longdescription.</p> <p>Затем вызываем функцию setuptools.setup() и передаем ей целый ряд параметров. При создании собственного пакета замените значения следующих параметров:</p> <ul class="wp-block-list"> <li>Название пакета (name). Оно должно быть уникальным. Для того чтобы обеспечить уникальность названия, проще всего добавить к нему свой логин на сайте https://test.pypi.org/ в формате «название-пакета-логин»;</li> </ul> <ul class="wp-block-list"> <li>Также вы можете заменить поля author и author_email.</li> </ul> <p>Менять остальные поля, в принципе, не обязательно.</p> <ol start="3" class="wp-block-list"> <li>Файл <strong>README.md</strong></li> </ol> <p>В файле README.md содержатся описание пакета, примеры и технические детали проекта. Расширение .md указывает на то, что этот файл сохранен в формате markdown и поддерживает форматирование текста.</p> <p class="has-background" style="background-color:#ffe8c4">В документации на сайте <a href="https://www.markdownguide.org/cheat-sheet/" target="_blank" rel="noreferrer noopener">www.markdownguide.org</a>⧉ вы найдете рекомендации по использованию языка markdown.</p> <p>В нашем файле мы напишем следующий текст.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340991068453118" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340991068453118-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340991068453118-2">2</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340991068453118-3">3</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340991068453118-4">4</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340991068453118-5">5</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340991068453118-1"># Тестовый пакет</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340991068453118-2"> </div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340991068453118-3">Файл README.md может содержать описание, примеры и технические детали пакета.</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340991068453118-4"> </div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340991068453118-5">Формат .md (markdown) поддерживает форматирование текста. Например, **полужирный шрифт** или *курсив*. Более полный перечень можно найти по [ссылке](https://guides.github.com/features/mastering-markdown/)</div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0000 seconds] --> </div> <ol start="4" class="wp-block-list"> <li>Файл <strong>LICENSE.txt</strong></li> </ol> <p>Остается создать файл с лицензией LICENSE.txt. Мы будем использовать лицензию открытого и свободного программного обеспечения MIT (Массачусетского технологического института).</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340992670122460" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340992670122460-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340992670122460-2">2</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340992670122460-3">3</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340992670122460-4">4</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340992670122460-5">5</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340992670122460-6">6</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340992670122460-7">7</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340992670122460-8">8</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340992670122460-9">9</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340992670122460-10">10</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340992670122460-11">11</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340992670122460-12">12</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340992670122460-13">13</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340992670122460-14">14</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340992670122460-15">15</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340992670122460-16">16</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340992670122460-17">17</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340992670122460-18">18</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340992670122460-19">19</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340992670122460-20">20</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340992670122460-21">21</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340992670122460-1">MIT License</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340992670122460-2"> </div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340992670122460-3">Copyright (c) 2022 Dmitry Makarov</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340992670122460-4"> </div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340992670122460-5">Permission is hereby granted, free of charge, to any person obtaining a copy</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340992670122460-6">of this software and associated documentation files (the "Software"), to deal</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340992670122460-7">in the Software without restriction, including without limitation the rights</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340992670122460-8">to use, copy, modify, merge, publish, distribute, sublicense, and/or sell</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340992670122460-9">copies of the Software, and to permit persons to whom the Software is</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340992670122460-10">furnished to do so, subject to the following conditions:</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340992670122460-11"> </div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340992670122460-12">The above copyright notice and this permission notice shall be included in all</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340992670122460-13">copies or substantial portions of the Software.</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340992670122460-14"> </div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340992670122460-15">THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340992670122460-16">IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340992670122460-17">FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340992670122460-18">AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340992670122460-19">LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340992670122460-20">OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE</div><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340992670122460-21">SOFTWARE.</div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0001 seconds] --> </div> <h4 class="wp-block-heading" id="34-shag-3-sozdanie-distributiva">Шаг 3. Создание дистрибутива</h4> <p>Скачаем инструменты, необходимые для создания дистрибутива.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340993963622022" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340993963622022-1">1</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340993963622022-1">pip install build</div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0000 seconds] --> </div> <p>Теперь из папки base/ введите команду <span id="urvanov-syntax-highlighter-672da52340994478486986" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;">py -m build</span></span>. После ее выполнения должно появиться уведомление об успешном создании дистрибутива пакета.</p> <figure class="wp-block-image size-full is-resized"><img loading="lazy" decoding="async" width="886" height="503" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/build-dist.png" alt="создание дистрибутива собственного тестового пакета на Питоне" class="wp-image-12032" style="width:692px;height:392px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/build-dist.png 886w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/build-dist-300x170.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/build-dist-768x436.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/build-dist-600x341.png 600w" sizes="(max-width: 886px) 100vw, 886px" /></figure> <p>Сам дистрибутив появится в папке base/.</p> <figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="541" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/dist-in-explorer-1024x541.png" alt="дистрибутив тестового пакета" class="wp-image-12033" style="width:748px;height:394px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/dist-in-explorer-1024x541.png 1024w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/dist-in-explorer-300x159.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/dist-in-explorer-768x406.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/dist-in-explorer-600x317.png 600w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/dist-in-explorer.png 1150w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure> <h4 class="wp-block-heading" id="35-shag-4-podgruzka-distributiva">Шаг 4. Подгрузка дистрибутива</h4> <p>Скачаем инструмент для подгрузки twine.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340995569174810" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340995569174810-1">1</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340995569174810-1">pip install twine</div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0000 seconds] --> </div> <p>И выполним подгрузку посредством следующей команды</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340996844574505" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340996844574505-1">1</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340996844574505-1">py -m twine upload --repository testpypi dist/*</div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0000 seconds] --> </div> <p class="has-background" style="background-color:#ffe8c4">Пароль при вводе отображаться не будет (ни в явном, ни в скрытом виде). Просто введите нужные символы и нажмите Enter.</p> <p>Должен появиться вот такой результат.</p> <figure class="wp-block-image size-full is-resized"><img loading="lazy" decoding="async" width="892" height="517" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/uploading-package.png" alt="подгрузка собственного пакета на TestPyPI" class="wp-image-12034" style="width:707px;height:409px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/uploading-package.png 892w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/uploading-package-300x174.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/uploading-package-768x445.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/uploading-package-600x348.png 600w" sizes="(max-width: 892px) 100vw, 892px" /></figure> <p>Как вы видите, подгруженный пакет доступен по адресу: <a href="https://test.pypi.org/project/example-package-DmitryMakarov/0.0.1/" target="_blank" rel="noreferrer noopener">https://test.pypi.org/project/example-package-DmitryMakarov/0.0.1/</a>⧉. Мы создали свой первый пакет.</p> <h3 class="wp-block-heading" id="36-ustanovka-i-ispolzovanie-paketa">Установка и использование пакета</h3> <p>Если вы захотите воспользоваться этим пакетом, то в командной строке введите команду, которая представлена на первой странице пакета.</p> <figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="887" height="666" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/testpypi.png" alt="страница тестового пакета на Test.PyPI.org" class="wp-image-12051" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/testpypi.png 887w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/testpypi-300x225.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/testpypi-768x577.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/testpypi-600x451.png 600w" sizes="(max-width: 887px) 100vw, 887px" /></figure> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340997925685764" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340997925685764-1">1</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340997925685764-1">pip install -i https://test.pypi.org/simple/ example-package-DmitryMakarov==0.0.1</div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0000 seconds] --> </div> <p>Результат исполнения этой команды вы видите ниже.</p> <figure class="wp-block-image size-full is-resized"><img loading="lazy" decoding="async" width="894" height="369" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/installation-output.png" alt="установка собственного тестового пакета через pip" class="wp-image-12036" style="width:699px;height:288px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/installation-output.png 894w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/installation-output-300x124.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/installation-output-768x317.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/installation-output-600x248.png 600w" sizes="(max-width: 894px) 100vw, 894px" /></figure> <p>Теперь мы можем пользоваться нашим пакетом. В интерактивном режиме (команду <strong>py</strong>) импортируем модуль example_module из пакета example_package и вызовем функцию square(), передав ей, например, число два.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da52340998384782575" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da52340998384782575-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da52340998384782575-2">2</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da52340998384782575-1">from example_package import example_module</div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da52340998384782575-2">example_module.square(2)</div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0000 seconds] --> </div> <figure class="wp-block-image size-full is-resized"><img loading="lazy" decoding="async" width="892" height="384" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/imported-module-result.png" alt="использование пакета, установленного из TestPyPI" class="wp-image-12037" style="width:696px;height:299px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/imported-module-result.png 892w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/imported-module-result-300x129.png 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/imported-module-result-768x331.png 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/04/imported-module-result-600x258.png 600w" sizes="(max-width: 892px) 100vw, 892px" /></figure> <p>В целом создание «взрослого» пакета на PyPI следует похожей схеме.</p> <h2 class="wp-block-heading" id="37-podvedem-itog">Подведем итог</h2> <p>Сегодня мы расширили наше представление о том, как запускать код на Питоне. Если раньше мы использовали только Google Colab, то теперь можем создавать собственные программы, модули и пакеты.</p> <h3 class="wp-block-heading" id="38-voprosy-dlya-zakrepleniya">Вопросы для закрепления</h3> <p class="has-black-color has-text-color has-background" style="background-color:#ffe8c4">Вопрос. Чем программа (скрипт) отличается от модуля?</p> <div class="wp-block-ub-content-toggle" id="ub-content-toggle-c5b683b9-e69e-4973-9cf9-466a437bd93e" data-mobilecollapse="true" data-desktopcollapse="true"> <div class="wp-block-ub-content-toggle-accordion" id="ub-content-toggle-panel-block-a2dc1cc9-427d-4aa3-a502-8d2efa765dc0"> <div class="wp-block-ub-content-toggle-accordion-title-wrap"" aria-controls="ub-content-toggle-panel-0-c5b683b9-e69e-4973-9cf9-466a437bd93e" tabindex="0"> <p class="wp-block-ub-content-toggle-accordion-title ub-content-toggle-title-c5b683b9-e69e-4973-9cf9-466a437bd93e">Посмотреть правильный ответ</p><div class="wp-block-ub-content-toggle-accordion-toggle-wrap left"><span class="wp-block-ub-content-toggle-accordion-state-indicator wp-block-ub-math-plus"></span> </div></div><div role="region" aria-expanded="false" class="wp-block-ub-content-toggle-accordion-content-wrap ub-hide" id="ub-content-toggle-panel-0-c5b683b9-e69e-4973-9cf9-466a437bd93e"> <p>Ответ: технически и то, и другое — файл с расширением .py, при этом скрипт не предполагает его использования в других программах, а модуль предназначен именно для этого.</p> </div></div> </div> <p class="has-black-color has-text-color has-background" style="background-color:#ffe8c4">Вопрос. Зачем добавлять Питон в переменнаую окружения PATH в ОС Windows?</p> <div class="wp-block-ub-content-toggle" id="ub-content-toggle-1ccce574-f88a-45f6-8de4-67c29031266f" data-mobilecollapse="true" data-desktopcollapse="true"> <div class="wp-block-ub-content-toggle-accordion" id="ub-content-toggle-panel-block-634f689f-d45c-486a-b8a7-7dd478c06f51"> <div class="wp-block-ub-content-toggle-accordion-title-wrap"" aria-controls="ub-content-toggle-panel-0-1ccce574-f88a-45f6-8de4-67c29031266f" tabindex="0"> <p class="wp-block-ub-content-toggle-accordion-title ub-content-toggle-title-1ccce574-f88a-45f6-8de4-67c29031266f">Посмотреть правильный ответ</p><div class="wp-block-ub-content-toggle-accordion-toggle-wrap left"><span class="wp-block-ub-content-toggle-accordion-state-indicator wp-block-ub-math-plus"></span> </div></div><div role="region" aria-expanded="false" class="wp-block-ub-content-toggle-accordion-content-wrap ub-hide" id="ub-content-toggle-panel-0-1ccce574-f88a-45f6-8de4-67c29031266f"> <p>Ответ: мы добавляем Питон в переменную PATH ОС Windows, чтобы в командной строке мы могли исполнять Питон в интерактивном режиме.</p> </div></div> </div> <p class="has-black-color has-text-color has-background" style="background-color:#ffe8c4">Вопрос. Что такое переменная path модуля sys в Питоне?</p> <div class="wp-block-ub-content-toggle" id="ub-content-toggle-883f8f7e-b08e-43e1-99e2-cf6ffde097a0" data-mobilecollapse="true" data-desktopcollapse="true"> <div class="wp-block-ub-content-toggle-accordion" id="ub-content-toggle-panel-block-45f5326d-0bb8-479d-9f34-b818c46207a6"> <div class="wp-block-ub-content-toggle-accordion-title-wrap"" aria-controls="ub-content-toggle-panel-0-883f8f7e-b08e-43e1-99e2-cf6ffde097a0" tabindex="0"> <p class="wp-block-ub-content-toggle-accordion-title ub-content-toggle-title-883f8f7e-b08e-43e1-99e2-cf6ffde097a0">Посмотреть правильный ответ</p><div class="wp-block-ub-content-toggle-accordion-toggle-wrap left"><span class="wp-block-ub-content-toggle-accordion-state-indicator wp-block-ub-math-plus"></span> </div></div><div role="region" aria-expanded="false" class="wp-block-ub-content-toggle-accordion-content-wrap ub-hide" id="ub-content-toggle-panel-0-883f8f7e-b08e-43e1-99e2-cf6ffde097a0"> <p>Ответ: в переменной path модуля sys указаны те папки компьютера, в которых интерпретатор Питона будет искать файл для его импорта. Эта переменная отличается от переменной PATH в операционной системе.</p> </div></div> </div> <div id="ub_divider_93531865-5cb3-4cef-8a5d-5844dc608abf" class="wp-block-ub-divider ub-divider-orientation-horizontal"><hr class="ub_divider" ></hr></div> <h3 class="wp-block-heading" id="39-otvety-na-voprosy">Ответы на вопросы</h3> <p><strong>Вопрос</strong>. Что такое <span id="urvanov-syntax-highlighter-672da52340999558808238" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><span class="crayon-st">if</span><span class="crayon-h"> </span><span class="crayon-v">__name__</span><span class="crayon-h"> </span><span class="crayon-o">==</span><span class="crayon-h"> </span><span class="crayon-s">'__main__'</span><span class="crayon-o">:</span></span></span>?</p> <p><strong>Ответ</strong>. Перед тем как исполнить код (например, в командной строке), интерпретатор Питона объявляет несколько переменных. Одна из них называется <span id="urvanov-syntax-highlighter-672da5234099b588968059" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><span class="crayon-v">__name__</span></span></span>. Этой переменной присваивается значение <em>__main__</em>. Создадим файл <strong>script.py</strong> со следующим кодом и запустим его в командной строке.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da5234099c994122451" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234099c994122451-1">1</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234099c994122451-1"><span class="crayon-k ">print</span><span class="crayon-sy">(</span><span class="crayon-v">__name__</span><span class="crayon-sy">)</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0001 seconds] --> </div> <figure class="wp-block-image size-full is-resized"><img loading="lazy" decoding="async" width="982" height="531" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/script_main.jpg" alt="значение переменной __name__ при исполнении кода напрямую" class="wp-image-14058" style="width:673px;height:364px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/script_main.jpg 982w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/script_main-300x162.jpg 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/script_main-768x415.jpg 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/script_main-600x324.jpg 600w" sizes="(max-width: 982px) 100vw, 982px" /></figure> <p>Теперь создадим еще один файл и назовем его <strong>module.py</strong>. Если вызвать его напрямую, то разумеется переменная <span id="urvanov-syntax-highlighter-672da5234099d350615065" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><span class="crayon-v">__name__</span></span></span> также будет иметь значение <em>__main__</em>.</p> <p>При этом если импортировать файл <strong>module.py</strong> внутри <strong>script.py</strong>, то значение переменной <span id="urvanov-syntax-highlighter-672da5234099e334768277" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><span class="crayon-v">__name__</span></span></span> файла <strong>module.py</strong> изменится на его название (то есть слово module). Создадим файл <strong>module.py</strong> со следующим кодом.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da5234099f069709592" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da5234099f069709592-1">1</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da5234099f069709592-1"><span class="crayon-k ">print</span><span class="crayon-sy">(</span><span class="crayon-v">__name__</span><span class="crayon-sy">)</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0001 seconds] --> </div> <p>Заменим код в файле <strong>script.py</strong> и исполним его.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da523409a0578380678" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da523409a0578380678-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da523409a0578380678-2">2</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da523409a0578380678-3">3</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da523409a0578380678-1"><span class="crayon-r">import</span><span class="crayon-h"> </span><span class="crayon-e">module</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da523409a0578380678-2"> </div><div class="crayon-line" id="urvanov-syntax-highlighter-672da523409a0578380678-3"><span class="crayon-k ">print</span><span class="crayon-sy">(</span><span class="crayon-v">__name__</span><span class="crayon-sy">)</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0001 seconds] --> </div> <figure class="wp-block-image size-full is-resized"><img loading="lazy" decoding="async" width="993" height="422" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/script_main_import.jpg" alt="значение переменной __name__ при исполнении импортированного файла" class="wp-image-14059" style="width:661px;height:280px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/script_main_import.jpg 993w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/script_main_import-300x127.jpg 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/script_main_import-768x326.jpg 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/script_main_import-600x255.jpg 600w" sizes="(max-width: 993px) 100vw, 993px" /></figure> <p>Как мы получили такой результат? Сначала был импортирован код из файла <strong>module.py</strong>, внутри которого переменной <span id="urvanov-syntax-highlighter-672da523409a1741731337" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><span class="crayon-v">__name__</span></span></span> было присвоено значение module. Именно это значение мы видим на первой строке вывода. Затем было выведено значение переменной <span id="urvanov-syntax-highlighter-672da523409a2448014469" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><span class="crayon-v">__name__</span></span></span> файла <strong>script.py</strong> (то есть <em>__main__</em>).</p> <p class="has-background" style="background-color:#ffe8c4">Вероятно, чтобы лучше понять как работает приведенный в ответе код, имеет смысл самостоятельно прописать и исполнить каждый из примеров.</p> <p>Теперь давайте изменим код файла <strong>module.py</strong>.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da523409a3532247161" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da523409a3532247161-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da523409a3532247161-2">2</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da523409a3532247161-3">3</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da523409a3532247161-4">4</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da523409a3532247161-1"><span class="crayon-st">if</span><span class="crayon-h"> </span><span class="crayon-v">__name__</span><span class="crayon-h"> </span><span class="crayon-o">==</span><span class="crayon-h"> </span><span class="crayon-s">'__main__'</span><span class="crayon-o">:</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da523409a3532247161-2"><span class="crayon-h"> </span><span class="crayon-k ">print</span><span class="crayon-sy">(</span><span class="crayon-s">'This runs as the main file'</span><span class="crayon-sy">)</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da523409a3532247161-3"><span class="crayon-st">else</span><span class="crayon-o">:</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da523409a3532247161-4"><span class="crayon-h"> </span><span class="crayon-k ">print</span><span class="crayon-sy">(</span><span class="crayon-s">'This runs as an imported file'</span><span class="crayon-sy">)</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0001 seconds] --> </div> <p>(1) Запустим его как основной файл напрямую из командной строки.</p> <figure class="wp-block-image size-full is-resized"><img loading="lazy" decoding="async" width="995" height="416" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/module_main.jpg" alt="if __name__ == '__main__'" class="wp-image-14060" style="width:668px;height:279px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/module_main.jpg 995w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/module_main-300x125.jpg 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/module_main-768x321.jpg 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/module_main-600x251.jpg 600w" sizes="(max-width: 995px) 100vw, 995px" /></figure> <p>(2) Теперь импортируем его в <strong>script.py</strong> (код файла <strong>module.py</strong> оставим без изменений).</p> <figure class="wp-block-image size-full is-resized"><img loading="lazy" decoding="async" width="994" height="419" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/script_main_import_if.jpg" alt="if __name__ == '__main__' внутри импортированного файла" class="wp-image-14061" style="width:660px;height:278px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/script_main_import_if.jpg 994w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/script_main_import_if-300x126.jpg 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/script_main_import_if-768x324.jpg 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/script_main_import_if-600x253.jpg 600w" sizes="(max-width: 994px) 100vw, 994px" /></figure> <p>Как вы видите, в импортированном файле <strong>module.py</strong> переменная <span id="urvanov-syntax-highlighter-672da523409a4743636056" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><span class="crayon-v">__name__</span></span></span> не содержит значения <em>__main__</em>, поэтому исполнилось выражение после else. В <strong>script.py</strong> переменная <span id="urvanov-syntax-highlighter-672da523409a5280978881" class="urvanov-syntax-highlighter-syntax urvanov-syntax-highlighter-syntax-inline crayon-theme-familiar-my-copy crayon-theme-familiar-my-copy-inline urvanov-syntax-highlighter-font-consolas" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important;"><span class="crayon-pre urvanov-syntax-highlighter-code" style="font-size: 16px !important; line-height: 22px !important;font-size: 16px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><span class="crayon-v">__name__</span></span></span> по-прежнему имеет значение <em>__main__</em>.</p> <p>Зачем может быть нужно такое условие? Если вы пишете код, который в первую очередь предназначен для импорта (то есть модуль), будет разумно не вызывать содержащиеся в нем функции автоматически. В этом случае вызов функций можно заключить в обсуждаемое условие.</p> <p>Изменим файл <strong>module.py</strong>.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da523409a6801410141" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da523409a6801410141-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da523409a6801410141-2">2</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da523409a6801410141-3">3</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da523409a6801410141-4">4</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da523409a6801410141-5">5</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da523409a6801410141-1"><span class="crayon-r">def</span><span class="crayon-h"> </span><span class="crayon-e">foo</span><span class="crayon-sy">(</span><span class="crayon-sy">)</span><span class="crayon-o">:</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da523409a6801410141-2"><span class="crayon-h"> </span><span class="crayon-k ">print</span><span class="crayon-sy">(</span><span class="crayon-s">'This is an imported function'</span><span class="crayon-sy">)</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da523409a6801410141-3"> </div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da523409a6801410141-4"><span class="crayon-st">if</span><span class="crayon-h"> </span><span class="crayon-v">__name__</span><span class="crayon-h"> </span><span class="crayon-o">==</span><span class="crayon-h"> </span><span class="crayon-s">'__main__'</span><span class="crayon-o">:</span></div><div class="crayon-line" id="urvanov-syntax-highlighter-672da523409a6801410141-5"><span class="crayon-h"> </span><span class="crayon-e">foo</span><span class="crayon-sy">(</span><span class="crayon-sy">)</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0002 seconds] --> </div> <p>Теперь внутри <strong>script.py</strong> вначале просто импортируем файл <strong>module.py</strong>.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da523409a7176428135" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da523409a7176428135-1">1</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da523409a7176428135-1"><span class="crayon-r">import</span><span class="crayon-h"> </span><span class="crayon-v">module</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0001 seconds] --> </div> <figure class="wp-block-image size-full is-resized"><img loading="lazy" decoding="async" width="992" height="316" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/import_module.jpg" alt="функция с условием if __name__ == '__main__'" class="wp-image-14062" style="width:652px;height:207px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/import_module.jpg 992w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/import_module-300x96.jpg 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/import_module-768x245.jpg 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/import_module-600x191.jpg 600w" sizes="(max-width: 992px) 100vw, 992px" /></figure> <p>При вызове модуля ничего не произошло. Так и должно быть. Для того чтобы вызвать <strong>функцию foo()</strong> нам нужно обратиться к ней напрямую. Изменим файл <strong>script.py</strong> и исполним его.</p> <div class="wp-block-urvanov-syntax-highlighter-code-block"><!-- Urvanov Syntax Highlighter v2.8.37 --> <div id="urvanov-syntax-highlighter-672da523409a8980425293" class="urvanov-syntax-highlighter-syntax crayon-theme-familiar-my-copy urvanov-syntax-highlighter-font-consolas urvanov-syntax-highlighter-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style=" margin-top: 15px; margin-bottom: 15px; margin-left: 15px; margin-right: 15px; font-size: 16px !important; line-height: 22px !important;"> <div class="urvanov-syntax-highlighter-plain-wrap"></div> <div class="urvanov-syntax-highlighter-main" style=""> <table class="crayon-table"> <tr class="urvanov-syntax-highlighter-row"> <td class="crayon-nums " data-settings="show"> <div class="urvanov-syntax-highlighter-nums-content" style="font-size: 16px !important; line-height: 22px !important;"><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da523409a8980425293-1">1</div><div class="crayon-num crayon-striped-num" data-line="urvanov-syntax-highlighter-672da523409a8980425293-2">2</div><div class="crayon-num" data-line="urvanov-syntax-highlighter-672da523409a8980425293-3">3</div></div> </td> <td class="urvanov-syntax-highlighter-code"><div class="crayon-pre" style="font-size: 16px !important; line-height: 22px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><div class="crayon-line" id="urvanov-syntax-highlighter-672da523409a8980425293-1"><span class="crayon-r">import</span><span class="crayon-h"> </span><span class="crayon-e">module</span></div><div class="crayon-line crayon-striped-line" id="urvanov-syntax-highlighter-672da523409a8980425293-2"> </div><div class="crayon-line" id="urvanov-syntax-highlighter-672da523409a8980425293-3"><span class="crayon-v">module</span><span class="crayon-sy">.</span><span class="crayon-e">foo</span><span class="crayon-sy">(</span><span class="crayon-sy">)</span></div></div></td> </tr> </table> </div> </div> <!-- [Format Time: 0.0001 seconds] --> </div> <figure class="wp-block-image size-full is-resized"><img loading="lazy" decoding="async" width="989" height="311" src="https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/import_function_directly.jpg" alt="вызов функции с условием if __name__ == '__main__'" class="wp-image-14063" style="width:652px;height:205px" srcset="https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/import_function_directly.jpg 989w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/import_function_directly-300x94.jpg 300w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/import_function_directly-768x242.jpg 768w, https://www.dmitrymakarov.ru/wp-content/uploads/2022/06/import_function_directly-600x189.jpg 600w" sizes="(max-width: 989px) 100vw, 989px" /></figure> <p>На следующем занятии, как мы и планировали, мы посмотрим, как можно исполнять код на Питоне в программе <a href="https://www.dmitrymakarov.ru/python/jupyter-notebook-14/">Jupyter Notebook</a>.</p> </div> <!-- .content --> </div> <!-- .post --> <footer class="site-footer section-inner"> <!--<p class="copyright">© 2024 <a href="https://www.dmitrymakarov.ru" class="site-name">Машинное обучение</a></p>--> </footer> <!-- footer --> </main> <script type="text/javascript" src="//cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js?ver=6.6.2" id="mathjax-js"></script> <script type="text/javascript" src="https://www.dmitrymakarov.ru/wp-content/plugins/ultimate-blocks/src/blocks/content-toggle/front.build.js?ver=3.2.2" id="ultimate_blocks-content-toggle-front-script-js"></script> <script type="text/javascript" src="https://www.dmitrymakarov.ru/wp-content/plugins/ultimate-blocks/src/blocks/table-of-contents/front.build.js?ver=3.2.2" id="ultimate_blocks-table-of-contents-front-script-js"></script> <script type="text/javascript" src="https://www.dmitrymakarov.ru/wp-includes/js/imagesloaded.min.js?ver=5.0.0" id="imagesloaded-js"></script> <script type="text/javascript" src="https://www.dmitrymakarov.ru/wp-includes/js/masonry.min.js?ver=4.2.2" id="masonry-js"></script> <script type="text/javascript" id="mcluhan_global-js-extra"> /* <![CDATA[ */ var mcluhan_ajaxpagination = {"ajaxurl":"https:\/\/www.dmitrymakarov.ru\/wp-admin\/admin-ajax.php","query_vars":"{\"page\":\"\",\"pagename\":\"python\\\/script-13\"}"}; /* ]]> */ </script> <script type="text/javascript" src="https://www.dmitrymakarov.ru/wp-content/themes/mcluhan/assets/js/global.js?ver=2.1.1" id="mcluhan_global-js"></script> </body> </html>