Что написать на питоне
Перейти к содержимому

Что написать на питоне

  • автор:

60 Python Projects with Source Code

60 Python Projects with Source code solved and explained for free

Python has been in the top 10 popular programming languages for a long time, as the community of Python programmers has grown a lot due to its easy syntax and library support. In this article, I will introduce you to 60 amazing Python projects with source code solved and explained for free.

Python Projects with Source Code

Python Projects For Beginners:

If you’re a newbie to Python where you’ve just learned lists, tuples, dictionaries, and some basic Python modules like the random module, here are some Python projects with source code for beginners for you:

Advance Python Projects:

If you have learned the fundamental Python libraries and some of the external libraries, you should now know how to install external libraries and work with them. So if you are at that level now, you can work on all the advanced Python projects with source code mentioned below:

So these were some very useful Python projects with source code for both a beginner and someone in advance level of Python. I hope you liked this article on Python Projects with source code solved and explained. Feel free to ask your valuable questions in the comments section below.

Лучшие Проекты Для Начинающих Python-Разработчиков

Чтобы научиться ходить – надо ходить, чтобы научиться подтягиваться – надо подтягиваться, чтобы научиться решать задачи по физике – надо решать задачи по физике. Так говорил преподаватель физики в моём университете, и эта аналогия применима и к программированию.

Можно сколько угодно упираться в сухую теорию, но без применения своих знаний на практике научиться программировать невозможно. В этой статье я подобрал несколько проектов для начинающих python-разработчиков. Эти проекты помогут закрепить теорию, применить полученные знания на практике и набить руку в написании кода. Некоторые из них даже можно добавить в будущее портфолио. Я объясню, чем хорош каждый проект, какие навыки и темы он позволяет проработать, а также сориентирую какие библиотеки и технологии можно использовать для его реализации.

Цель данного «топа» – это не создание самого оригинального портфолио и не перечисление уникальных проектов. Цель статьи разобраться в простых вещах, технологиях и темах, которые помогут развить практические навыки программирования. Поэтому не стоит ждать здесь сборку Оптимуса Прайма, программирование Звезды смерти и создание двигателя на китовом жире. Мы пройдёмся по простым, но в тоже время базовым вещам. Ведь как говорил один мой приятель: «Всё великое начинается с малого».

Парсер

Первый проект в списке – парсер сайтов. Это программа, которая просматривает код веб-сайта и получает оттуда какую-то информацию.

Предположим, есть сайт «Авито». Мы можем сделать программу, которая будет «как бы заходить» на Авито; просматривать объявления из раздела «Аренда квартир в Москве» (через программный код на страницах); и записывать в текстовый файл информацию из этих объявлений.

Пусть скрипт пишет в файл ссылку на объявление, контактный телефон, цену и описание. Затем этот файл сортируется по цене аренды, и на выходе мы сможем выбрать самые дешёвые квартиры. Такая программа и будет являться парсером или, как их часто называют, веб-скрапером.

В тренировочно-образовательных целях необходимо всё сделать максимально вручную, но без фанатизма. Поэтому используем модуль requests для работы с сетевыми запросами (для получения кода сайта, регистрации, авторизации). Библиотека BeautifulSoup понадобится для разбора и выдергивания информации из HTML-кода сайта, который мы получили с помощью requests.

Разработка парсера заставит разобраться с тем, что такое, зачем нужны и как работают сетевые протоколы HTTP/HTTPS. Придётся выяснить, что такое HTTP-запрос – из чего он состоит; как работать с GET, POST, PUT, DELETE-запросами; чем они отличаются; как формировать заголовки запросов. Предстоит покопаться со статус-кодами, URL-адресами, схемами авторизации, сессиями, редиректами, прокси и куки-файлами. Параллельно познакомиться с форматом JSON и вникнуть в HTML/CSS-код, семантику и DOM-модель веб-страницы.

Работа с сетевыми протоколами – это фундаментальные computer science навыки, без которых называть себя полноценным программистом немного не справедливо.

Мне кажется, пример с квартирами на Авито идеально подходит для пробы пера. Поэтому попробуйте написать скрипт, который создаст файл с информацией о всех трехкомнатных квартирах, которые продают в твоем городе, по цене, скажем, дороже 3 000 000 рублей.

На скелет подобного проекта можно нарастить мяса в виде подключения базы данных, многопоточного выполнения или вообще превратить парсер в пул Telegram-ботов, о которых мы и поговорим дальше.

Каждый мужчина должен посадить сына, вырастить дом и построить дерево, а каждый питонист должен сделать хотя бы одного бота для социальной сети или мессенджера.

Бот – это простой проект, но в тоже время, он даст новичку навыки работы со сторонними библиотеками, асинхронностью и, что самое главное, опыт работы со сторонним API.

Однако прежде придётся разобраться, что такое API, вникнуть в понятие синхронности/асинхронности, потренировать понимание ООП, если сделать бота классом, а не просто набором функций.

Масштабировать сложность проекта можно до бесконечности. Например, прикрутить базу данных или заставить бота присылать уведомления, когда изменяются цены в интернет-магазине. Если бот как-то взаимодействует с файлами на компьютере, то придётся параллельно освоить и работу с файловой системой.

В ходе разработки возникнут вопросы: как хранить в проекте секретные данные (токены, пароли), и как разделить бизнес логику приложения. Веcь код, отвечающий за работу непосредственно с площадкой, стоит вынести в один модуль, а код обработки полученных данных в другой модуль. Этим всё не ограничится. В процессе всплывёт ещё много других подводных камней. А это ценный практический опыт, который нам и нужен.

Загрузка (то есть деплой) бота на хостинг по типу Heroku или Google App Engine – уже отдельная история, которая также прокачает твои технические навыки.

Если хочется сделать бота ВКонтакте, то смотрим в сторону библиотек vkwave и vkbottle. Они современные, асинхронные и простые в использовании. Синхронный и уже местами забагованный vk_api использовать не советую.

Для Telegram рекомендую полностью асинхронный Aiogram.

В качестве альтернативы можно использовать модуль pytelegrambotapi. Он попроще и поддерживает как синхронный, так и асинхронный режим работы.

В случае с Discord ботами самым популярным является модуль discord.py (c 9 000 звёзд на GitHub). Он асинхронный, хорошо документирован и прост в освоении. По принципу использования и написания кода похож на Aiogram и vkwave.

Если разобраться, как работать с одной из перечисленных библиотек, то с другими проблем уже не возникнет. Этот принцип справедлив для многих модулей и фреймворков не только языка Python. Об этом я ещё скажу дальше.

Идея проекта попроще: бот, который по запросу присылает случайный фильм из файла или БД.

Вариант посложнее: бот для учёта финансов. Пишешь ему сообщение сколько денег потратил и на что. Он записывает всё в Google-таблицу, БД или Excel-таблицу и ведёт какую-нибудь статистику.

Можно сделать бота, который следит за ценами. Отправляешь ему ссылку на товар. Если на этот товар появляется скидка, бот присылает уведомление.

В случае с ботами всё ограничивается лишь вашей усидчивостью и фантазией. Ковыряйтесь на здоровье!

Веб-приложение (интернете магазин)

Если браться за создание сайта, то это должен быть не блог, не клон Instagram, не онлайн предсказатель будущего, а именно интернет-магазин.

Придётся разобраться с админ-панелью сайта, регистрацией, авторизацией, личным кабинетом, избранными товарами, корзиной, категориями товаров, подключением базы данных, миграциями, разграничением прав доступа, пагинацией, сессиями и кучей всего другого.

В качестве усложнения проекта можно добавить систему оплаты, скидочные промокоды, раздел с лидерами продаж, кеширование, отправку чека на почту или рекомендательную систему, основанную на in-memory СУБД Redis или вообще модели машинного обучения.

А если вы совсем без тормозов, то прикрутите REST API сайта. Для этого потребуется дополнительно вникнуть в вопросы сериализации JSON-объектов, работе с сетевыми протоколами и прочему.

Разработка веб-сайта познакомит вас с паттерном проектирования MVC (модель-представление-контроллер), HTML/CSS и, возможно, JavaScript кодом.

Основываясь на своём опыте, скажу, что для освоения веб-разработки лучше варианта чем Django нет. Django большой фреймворк, в котором по умолчанию есть модули для всего, что я перечислял выше. Кроме того, он базируется на классическом, упомянутом ранее шаблоне MVC (правда там он называется MVT, но не суть).

Изучая Django придётся научиться работать с маршрутизацией, моделями данных, миграциями, контроллерами, шаблонизаторами HTML и ORM (это специальная штука, которая позволяет работать с базой данных без SQL запросов, а через питоновские объекты). Много предстоит поработать с ООП, потому что все модели данных представлены классами. Часто приходится использовать наследование.

Важно, что практически все современные популярные питоновские и не только фреймворки устроены точно также, как Django. Если вы разберётесь с Django, понять, как работает PHPшный Laravel, Jav’овый Spring или Ruby on Rails не составит труда.

Django ORM практически идентичен Eloquent из Laravel, шаблонизаторы тоже плюс/минус у всех похожи, модели и миграции отличаются чисто косметически.

Потом, для расширения кругозора, можно ещё взглянуть на микрофреймворк Flask.

Выбирайте предметную область, которая вам интересна. Любите компьютерные игры – создаём магазин игр, тащитесь по топовому шмоту – вот вам магазин одежды. Короче стараемся получить максимум удовольствия. И едем дальше.

Разработка приложений с графическим интерфейсом не является основной сферой применения Python. Однако это не значит, что GUI на нем не пишут совсем.

GUI на PyQT5

GUI на PyQT5

В качестве тренировочного опыта, лично я бы остановился на создании Аудио проигрывателя для компьютера. На функционал не скупимся. Добавляем возможность работать с плейлистами, управление воспроизведением (старт, стоп, пауза, перемотка), стоит добавить анимацию звуковой дорожки, ползунки громкости и т.д. Про уникальный дизайн также не забываем.

Для графики рекомендую использовать фреймворк PyQt, а для работы с аудио библиотеку Pygame.

PyQt – более фундаментальный и сложный графический фреймворк, чем tkinter или pysimplegui. Поэтому обратить внимание стоит именно на него. Тут по аналогии с MVC веб-фреймворками. Разберись с базовыми принципами и дальше проблем не будет. Под базой здесь я подразумеваю концепцию событий (сигналов) и обработчиков событий (слотов).

PyQt также поможет прокачаться в понимании ООП, потому что все графические объекты представлены классами, а наследование используется повсеместно.

Внешний вид элементов в PyQt задаётся в графическом Дизайнере ручками или с помощью CSS-свойств в коде, что делает разработку проще.

По PyQt в Интернете много уроков, есть даже отдельные книги, что также плюс.

Отмечу, что многие графические приложения основаны на шаблоне проектирования MVP (модель-представление-представитель). Это вариация шаблона MVC на котором базируются веб-приложения.

Pygame – простая и популярная библиотека для работы с мультимедиа объектами. Позволяет работать с аудио, видофайлами, а если в ней хорошо разобраться, можно и 2D игру сделать.

Data Science-приблуды

Сферы искусственного интеллекта и Data Science занимают большую часть сообщества Python-разработчиков. Да, проекты подобного рода специфичны и вникать в них всем необязательно. Но не упомянуть о них я не мог.

Анализ данных – гигантская область, в которую входит математика, computer science и программирование. Разбор всех этих тем выходит за рамки данной статьи и заслуживает отдельного цикла.

Как по мне интересный проект – анализ настроения пользователя по его комментарию на форуме, или на вполне конкретном сайте, например, Кинопоиске. Оригинальностью проект не блещет. Но покопаться придётся.

Это задача из сферы обработки естественного языка (Natural Language Processing или NLP). Для работы с NLP стоит обратить внимание на библиотеки: NLTK, TextBlob, spacy, Gensim и CoreNLP. Пара слов о каждой.

NLTK – основная библиотека для NLP, позволяет обрабатывать тексты для классификации, токенизации, стемминга, разметки, фильтрации, работать с семантическими рассуждениями и многим другим. В первую очередь знакомиться именно с этой библиотекой.

TextBlob – обёртка над NLTK, которая предоставляет простой интерфейс для этой библиотеки. Иногда ею просто удобнее пользоваться.

spacy – модуль, который помогает решать спектр задач: от определения частей речи и выделения именованных сущностей, до создания собственных моделей анализа.

Gensim – библиотека тематического моделирования. Позволяет обрабатывать тексты, работать с векторными моделями слов (например, Word2Vec или FastText) и создавать тематические модели текстов.

CoreNLP – модуль для распознавания свойств текста.

Пока далеко не ушли от кино. Вспомним одну из классических задач машинного обучения – разработку системы рекомендаций. Рекомендательная система – это программа, которая будет угадывать предпочтения пользователя в плане выбора фильма. Для её написания придется научиться работать с такими базовыми библиотеками для любого data scientist’а как Pandas, Numpy, Matplotlib и Scikit.

Pandas нужен для обработки данных, NumPy для математических вычислений, Matplotlib позволяет визуализировать данные, то есть строить диаграммы и графики, а Scikit содержит модели машинного обучения и инструменты для работы с ними.

Следующий большой класс задач – компьютерное зрение. Не мудрствуя лукаво, создаём приложение, которое по фото или видео определяет наличие/отсутствие маски на лице человека. Самая ходовая библиотека компьютерного зрения – это OpenCV. Её и предстоит изучать. Также стоит ознакомиться со сверточными нейронными сетями и концепцией deep learning в целом. Обучающие data-сеты для любого из указанных проектов можно спокойно найти в Интернете.

В этом топе, как и в большинстве интернет-подборок, не оказалось из рядя вон уникальных проектов. Почему так? Почему большинство python-каналов переполнено роликами по написанию однотипных ботов, парсеров и скриптов? Все просто! Все перечисленное – это базовые вещи, отвечающие за понятные базовые навыки, через развитие которых необходимо пройти каждому python -разработчику.

Чтобы найти что-то по-настоящему оригинальное, предлагаю поделиться вашими идеями интересных pet-проектов в комментариях.

Знаете, учиться всегда тяжело. А по началу очень тяжело. Но я в тебя верю! Господь тоже в тебя верит! Но на всякий случай, для подстраховки, он создал тебе в помощь Google. Не забывай про это.

Какие программы можно создать с помощью Python

Какие программы можно создать с помощью Python

Блог

Для начала нужно отметить, что Python – это универсальный язык программирования, какие программы можно создать с помощью Python? С его помощью можно создать почти все. Этот язык имеет в своем арсенале большое количество библиотек, фреймворков, собственный компилятор. Также нельзя забывать, что крупные корпорации поддерживают этот язык, что обуславливает спрос на него в среде программистов. Среди преимуществ можно выделить гибкость, простоту и быстроту, поэтому многие разработчики, особенно начинающие, выбирают Python.

Какие программы можно создать с помощью Python?

Простой калькулятор

 Какие программы можно создать с помощью Python? Калькулятор

Какие программы можно создать с помощью Python 7

С помощью Python вы можете написать простое приложение для выполнения математических операций – калькулятор. Это первый шаг в GUI-программирование, в данном случае речь идет о создании интуитивно понятых интерфейсов в графическом формате. В рамках разработки нужно познакомиться с возможностями модуля tkinter, он встроен в последние версии Python.

Создание блокчейна

 Какие программы можно создать с помощью Python? Блокчейн

Какие программы можно создать с помощью Python 8

Технологии криптошифрования универсальны, их можно использовать не только в качестве финансового инструмента, но и для решения задач в других областях. Если вы интересуйтесь блокчейном, то Python может помочь вам создать собственный. С помощью фреймворков, лучше всего для решения поставленной задачи подходит Flask, разработчики могут использовать HTTP-запросы как способ взаимодействия со своим блокчейном, для этого нужно подключение к интернету, что дает возможность создавать конечные точки для различных функций блокчейна.

Синтаксический анализ данных из социальных сетей

Для работы с анализом данных можно использовать любую открытую площадку в интернете, в качестве примера можно рассмотреть социальную сеть Twitter. С помощью модулей пользователь может отсортировать и структурировать информацию, представляющую для него интерес. Посредством применения Tweepy можно отфильтровать публикации пользователей, указав нужные параметры. GraphQL позволит представить результат работы в виде интерфейса в графическом формате. Стоит отметить что оптимизация задач для SMM-cспециалиста является привычным делом, любые рутинные задачи можно оптимизировать с помощью Python.

Аудио и видео приложения

Аудио и видео приложения с помощью Python

Какие программы можно создать с помощью Python 9

Язык Python может быть использован для создания приложений, предназначенных для создания музыки и других типов аудио, и приложений в видео формате. С учетом того факта, что на просторах интернета представлено большое количество контента в аудио и видео формате, пользователь может использовать Python для того, чтобы проанализировать этот контент. Ряд библиотек рассматриваемого языка, в качестве примера можно рассмотреть PyDub и OpenCV, помогают завершить процесс разработки приложения.

Разработка игрового приложения

Питон

Какие программы можно создать с помощью Python 10

Многие игры, такие как EVE Online и Battlefield 2, создавались с использованием Python. Возможности языка позволяют осуществлять надстройку в играх, и определить функции, поэтому его популярность среди разработчиков игр повышается.

Приложения для системного администрирования

Такие приложение выступают в качестве незаменимых помощников с точки зрения осуществления управленческих процессов. Питон хорошо подходит для создания приложений системного администрирования, так как с его помощью системные администраторы могут налаживать взаимодействие с операционной системой. Это дает возможность взаимодействовать с ОС, в которой на данный момент времени работает Python.

Бизнес-приложения

Приложение, разработанное на Python, поддерживает практическую гибкость. По этой причине рассматриваемый язык помогает успешно решать задачи, связанные с созданием приложений ERP и коммерции в электронном формате. Вы можете написать классные и функциональные бизнес-приложения под любые бизнес-процессы.

Создание микроблога

На данный момент времени блоги стали распространенным явлением среди пользовательской аудитории, его начинают вести те люди, которые хотят выражать свое мнение о происходящих в мире событиях. Развитие социальных сетей оказало большое влияние на популяризацию микро блогов. Писать блоги на питоне можно абсолютно любые.

Веб-разработка

С учетом того факта, что код Python прост и понятен, он заметно упрощает создание веб-служб и услуг, связанные с разработкой ПО, результатом этого является повышение эффективности процесса. Нельзя забывать, что Python совместим с другими языками, что определяет его гибкость и универсальность. Python в вебе активно используется веб-разработчиками для создания сайтов и различных веб-ресурсов.

Обработка изображений и оптическое распознавание символов

распознавание символов с помощью Python

Какие программы можно создать с помощью Python 11

Питон может быстро и эффективно находить объекты и осуществлять обработку изображений. Наличие большого количества библиотек, таких как PyTesseract для OCR (оптическое распознавание символов), TensorFlow для обнаружения объектов и Python Imaging Library (PIL) для обработки изображений помогает разработчикам создавать приложения.

Под решение каких задач не подходит Python?

С помощью Python не получится написать операционную систему, так как у этого языка существуют проблемы с взаимодействием с низкоуровневыми устройствами. Одним из вариантов решения этой проблемы является MicroPython.

Основатель сайта. Специализируюсь на веб-дизайне, веб-разработке и обожаю технологии. Рассказываю об актуальных профессиях.

93+ Python Programming Examples

In this article, you will find a comprehensive list of Python code examples that cover most of the basics.

  • Preparing for a coding interview.
  • Preparing for an examination.
  • Exploring what programming is.
  • Teaching Python and wants to find useful examples

Without further ado, let’s get coding!

1. Print ‘Hello World!’ in the Console

The simplest and probably the most common example of Python is the “Hello world” program.

Here is how it looks:

2. Ask User Their Name and Greet Them

To ask for user input in Python, use the input() function.

For instance, you can store user input to a variable and use that variable in a greeting.

Here is the code:

3. Create a List of Names in Python

To create a list in Python, add comma-separated values between braces.

For instance, here is a list of names in Python:

4. Merge Two Lists

Given two or more lists in Python, you may want to merge them into a single list.

This is easy in Python. Use the + operator you would use when summing up numbers. In the case of lists, this merges the lists into one.

5. Loop Through a List of Names and Print Each

A powerful feature of Python lists is that they are iterable.

In other words, you can easily loop through the items on the list to do something for them.

For example, let’s create a list of names and print each name into the console:

6. Get Rid of Spaces in Python String

To get rid of spaces in a Python string, replace all blank spaces with an empty string.

You can do this with the replace() method.

7. Calculate the Number of Spaces in a String

A Python string has a built-in method count() . You can use it to count how many times a substring occurs in a string.

For instance, let’s calculate how many blank spaces there are in a string:

8. Check If a String Is a Palindrome

  • reverse the string and compare it with the original string.

9. Find a Substring in a String

To find a specific substring inside a string in Python, use the built-in find() method of a string.

10. Add Two Numbers

  • Create a function that takes two number arguments
  • Sum up the arguments
  • Return the result

11. Find Maximum of Two Numbers in Python

To find the maximum value between two (or more) numbers in Python, use the built-in max() function.

12. Find the Minimum of Two Numbers in Python

To find the minimum value between two (or more) numbers in Python, use the built-in min() function.

13. Find the Average of a List of Numbers in Python

  1. The number of elements.
  2. The sum of all the elements.

Given these, you can calculate the average by sum/length .

In Python, you can do it like this:

14. Check If a Year Is a Leap Year in Python

  • Is divisible by 4…
  • And not divisible by 100…
  • Unless also divisible by 400.

In Python, you can write a function that implements these three checks to find if a given year is a leap year.

15. Find The Maximum Value of a Python Dictionary

To find the maximum value of a dictionary, you need:

  1. To access all the values of the dictionary using the dict.values() method.
  2. Find the greatest value using max() function.

16. Merge Two Python Dictionaries

To merge two dictionaries in Python, use the double-asterisk notation to unpack the dictionary items into one dictionary.

For example, here is a function that does it for you:

17. Check If a Key Exists in a Python Dictionary

To check if a key exists in a dictionary, you can use the in operator.

18. Delete an Element from a Python Dictionary

To delete an entry from a dictionary, use the del operator.

19. Find the Distance Between Two 2D Points in Python

To calculate the distance between two points, use the Pythagorean theorem.

For example, here is a function that calculates the distance between two 2D points.

Notice that there is a built-in function dist() in the math module that does the exact same for you:

20. Read a File Line by Line in Python

  1. Open a file behind a path.
  2. Read and store the lines of the file.
  3. Close the file.

To do this, use a context manager. A context manager automatically closes the file once processing has been completed.

To open the file with a context manager, use the with statement.

Given a file example.txt in the same folder that looks like this:

You can read the file line by line with a context manager using the following code:

21. Check If a File Contains a Specific Word

  1. Open the file behind the path.
  2. Read the contents of the file in memory.
  3. Test if a specific word is found in the content.
  4. Close the file.

To do this, use a context manager. A context manager automatically closes the file once processing has been completed.

To open the file with a context manager, use the with statement.

Given a file called example.txt with contents like this:

You can check if a specific word exists in that file with this piece of code:

22. Count the Frequency of a Word in a File

  1. Open the file behind the path.
  2. Read the contents of the file in memory.
  3. Count the number of occurrences of a string.
  4. Close the file.

To do this, use a context manager. A context manager automatically closes the file once processing has been completed.

To open the file with a context manager, use the with statement.

Given a file called example.txt with contents like this:

You can check many times the word “test” occurs in a file by:

23. Swap Two Values without a Third

This is one is a classic examination question.

Is there a way to swap two variables without a third helper variable?

The answer is yes. You can use tuple unpacking to achieve this.

24. Check If a Given Number Is a Prime Number

A prime number is any positive non-zero number that is only divisible by itself or by 1.

For example, 11 is a prime number.

To create a Python program that finds if a number is a prime number, you need to:

  1. Have a target number.
  2. Ensure the number is more than 1.
  3. Loop through all the numbers that are less than half the target number.
  4. Check if any number divides the target evenly.

For example, to check if 11 is a prime number, you need to check if any of the following numbers divides it evenly: 2, 3, 4, 5.

Here is a Python program that checks if a given number is a prime number:

25. Calculate Simple Interest in Python

Simple Interest is calculated using the following formula:

SI = (P × R × T) / 100

  • P = Principal amount of money.
  • R = Rate of Interest (e.g. 7%).
  • T = Time period.

The principal is the sum of money that remains constant every year in the case of simple interest.

Here is a Python program to figure out the simple interest:

This returns the earnings during the period. To get the total amount of money, add this result to the principal amount.

26. Ask a Word from the User and Reverse It

In Python, you can reverse a string by calling string[::-1] .

For example, to ask the user a word and reverse it, use the following piece of code:

27. Ask User a Sequence of Numbers and Reverse Them

  1. Ask user for comma-separated number input.
  2. Split the resulting string by commas. This creates a list of strings that represent numbers.
  3. Convert the list of number strings to a list of integers.
  4. Call the built-in reversed() function on the list of integers to reverse the order.

Here is the code for you:

28. Calculate BMI Index in Python

BMI or Body Measurement Index measures leanness or corpulence given height and weight.

The formula for BMI index given height in centimeters and weight in kilos is:

BMI = weight / (height/100)²

Here is a Python program that asks the user for weight and height and outputs their BMI:

29. Emit a Beep Sound in Python

On Windows, you can use the winsound module of Python to make a beeping sound.

For example, here is a program that produces a single high-pitch beep that lasts one second:

30. Copy One File to Another in Python

Given a file called example.txt in your project’s folder, you can copy-paste its contents to another.txt file using shutil module’s copyfile function.

31. Compute the Factorial of an Integer in Python

In mathematics, factorial is marked with an exclamation mark. Factorial means to multiply the number by all numbers from 1 to the number.

The factorial tells you how many ways there is to arrange n elements.

For example, to figure out how many ways there are to arrange 5 persons in a line, calculate the factorial of five: 5! = 5*4*3*2*1 = 120.

Here is a Python program that calculates the factorial given a number input. It starts with the target number. Then it subtracts one from the target and multiplies the target by this number. It does this until number 1 is reached.

32. Find the Longest Word in a List

Python has a built-in function max() . If you call this function on a list of values, by default it returns the greatest element.

  • In the case of numbers, it returns the largest number.
  • In the case of strings, it returns the string with the highest ASCII value. Not the one with the greatest length!

To make the max() function return the longest string, you need to specify the max() function a second argument, key=len . This shows the max() function that we are interested in the maximum length, not the maximum ASCII value.

33. Create Pyramid from Asterisks ‘*’

An asterisk pyramid may not be the most useful example, but it surely tests your understanding of loops and maths in Python.

To create a pyramid, you need to start with 1 asterisk. On the next line you have 3, then 5,7, and so on. In other words, the number of asterisks is 2*i + 1 , where i is the row number (or the height) of the pyramid.

Now you got the number of asterisks.

Then you need to know how many spaces you need to the left of the asterisks to make it look like a pyramid.

In the first row, the number of spaces is the same as the height of the pyramid. Then on the second row, it is one less. On the third one less again. So you need to add one less space for each row of asterisks. In other words, the number of spaces is h-i-1, where h is the pyramid height and i is the row number.

See also how to create a diamond pattern with asterisks.

34. Find the Intersection of Two Lists in Python

An intersection between two groups refers to the common elements among the groups.

To find the intersection between two lists:

  1. Loop through the other of the lists.
  2. Store the elements that are in the other list as well.
  3. Return the stored elements.

You can use a for loop, but let’s use a more compact expression called list comprehension. This is a shorthand of the for loop:

35. Convert Celcius to Fahrenheit with Python

To convert temperatures from Celcius to Fahrenheit, use the following formula:

F = (9/5) * celcius + 32

  1. Takes a temperature measured in Celcius.
  2. Returns temperature in Fahrenheit with the help of the above formula.

Here is the code:

36. Convert Kilograms to Pounds in Python

To convert weight from kilos to pounds, use the following formula:

p = kilos * 2.2048

  1. Takes a mass in kilos.
  2. Returns the weight in pounds with the help of the above formula.

Here is the code:

37. Count the Frequency of Each Letter in a String

  1. Define a target string.
  2. Create an empty character-to-frequency dictionary.
  3. Loop through the characters of the string.
  4. Add 1 to the frequency dictionary for each character.
  5. Return the dictionary.

Here is how it looks in code:

38. Count the Number of Seconds in a Year

In a year, there are roughly 365.25 days.

In a day there are 24 hours.

In an hour there are 60 minutes.

In a minute there are 60 seconds.

Thus, the number of seconds in a year is:

seconds = 365.25 * 24 * 60 * 60 = 31 557 600

You can calculate this in Python with:

39. Find the Number of Days Between Two Datesin Python

To work with dates in Python, use the datetime module.

  1. Create two datetime.date objects.
  2. Subtract the more recent date from the more past date.
  3. Call .days() method on the resulting date object to get the result.

In Python, it looks like this:

40. Generate Random Numbers Between a Range in Python

In Python, there is a built-in module for generating random numbers called random.

To generate random integers between an interval, call random.randint() method by providing it the max and min values.

41. Get a Random Element from a List

The built-in random module comes in with a useful method called choice() . This method randomly selects an element from an iterable.

For example, to pick a random name at a list of strings:

42. Check If a Number Is Odd/Even

A number is even if it is evenly divisible by 2. In other words, if there is no remainder after division.

To check if a number is odd, check if it is not divisible by 2.

Here is a Python script that checks if the number 3 is odd or even:

43. Print a Multiplication Table of an Integer

A multiplication table is a table from where it is easy to check what times what gives what.

  1. Select a target number.
  2. Loop from 1 to 10 and multiply the target number by each number in this range.
  3. Print the result to the console.

44. Print without New Line

By default, printing on a new line adds a new line in Python.

To overcome this, you need to join the printable items together separated by a blank space.

To do this, use the str.join() method in a blank space. This joins the elements of a list separated by a blank space.

Then you can print this whole string. As it is one string, it naturally gets printed on one line.

45. Find a Sum of any Number of Numbers

A Python function can accept any number of arguments. To do this, you need to use an asterisk in front of the argument name. This tells the Python interpreter that there is going to be an arbitrary number of arguments.

For example, let’s create a function that adds up any numbers you pass it:

46. Find ASCII Value of a Character in Python

Each character and string in Python has an ASCII value behind the scenes. This value is just an integer ID of that character.

To figure out the ASCII value of a given character, use the built-in ord() function on it.

47. Find Factors of a Number

A factor of a number means a number divided by the factor leaves no remainder.

For example, factors of number 12 are 1, 2, 3, 4, and 6.

  1. Loop through numbers from 1 all up to the target number.
  2. Check if the number divides the target evenly.
  3. Store each factor into a list.
  4. Finally, return the factors list.

Here is how it looks in Python:

48. Simulate Coin Toss in Python

To simulate a coin toss, you need to randomly choose values of 0 or 1.

In Python’s random module, there is a function called choice() . This chooses a value from an iterable randomly.

To simulate coin toss, give this function a list that has 0 and 1. Then based on whether you got 0 or 1, display “Heads” or “Tails” in the console.

Here is how it looks in code:

49. Add Two Matrices in Python

Matrices are arrays of numbers that are arranged in rows and columns.

To add two matrices, you need to perform element-wise addition as described here.

In Python, you can represent matrices with lists of lists (nested lists). In this case, you can implement the matrix addition with the following piece of code:

In this implementation, the 5th row is a list comprehension for loop. It represents a nested for loop where each matrix row and column is iterated through.

50. Transpose a Matrix in Python

A matrix transpose means the matrix is flipped over its diagonal.

In other words, each position (i, j) is replaced with (j, i) in the matrix.

In Python, you can use nested lists to represent matrices. When doing this, you can compute a transpose for the matrix with the following code:

In this implementation, the 5th row is a list comprehension for loop. It represents a nested for loop where each matrix row and column is iterated through.

51. Multiply Two Matrices in Python

To multiply two matrices, you need to implement the matrix multiplication algorithm.

  1. Take a row from matrix A and a column on matrix B.
  2. Multiply the corresponding elements by one another.
  3. Sum up the results of the multiplications.
  4. Add the result to the result matrix at a corresponding position.
  5. Repeat until no rows are left.

An image is worth a thousand words, so here is one: Image Source: Math is fun

Here is how the algorithm looks in code:

In this implementation, the 3rd row is a list comprehension for loop. It is a nested loop where there are three inner for loops that implement the algorithm described above.

52. Track the Index in a For Loop

Sometimes when you perform a for loop, you wish there was an easy way to track the index of the current element. By default, this is not possible.

But using the built-in enumerate() function, you can relate each list element with an index.

This makes it easy for you to loop through the list and know the index at each loop.

Here is how it looks in code:

Learn more about enumerate() function in Python.

53. Flatten a Nested Python List

Given a list of lists, you can easily flatten the list to a 1D list with a for loop.

  1. Loop through the list of lists.
  2. For each list, place each element in the list in a result list.
  3. Return the list.

Instead of using a nested for loop, you can use a one-liner list comprehension to make the code shorter. In case you find it hard to read, you can convert the comprehension back to a nested for loop.

Anyway, here is the implementation:

54. Convert String to Date in Python

Python has a built-in datetime module for dealing with date objects reliably.

  1. Import the datetime from datetime.
  2. Create a date string in some format.
  3. Convert the string to a date object with the given format.

55. Count the Frequency of Items in a List

  1. Have a list full of elements.
  2. Create a frequency dictionary to map item -> item frequency.
  3. Loop through the list.
  4. On each element, increment its counter in the frequency dictionary.

Here is how it looks in code:

56. Add a Word to the End of an Existing File

  1. Open the file in write mode.
  2. Write a string to the file.
  3. Close the file.

You can use a context manager to open the file. This means you don’t have to worry about closing the file.

Given a list named example.txt with the following contents:

You can write a new string to the end of it with a context manager like this:

57. Parse the File Extension from a File Name

  1. The path.
  2. The extension.

To get the extension, just access the second element of the list.

Here is how it looks in code:

58. Parse the File Name from the Path

To get the name of the file from a path, use os.path.basename() function.

59. A Function That Takes a Default Argument

In Python, you can give function default arguments. This means you can call the function with or without an argument.

As this task does not state what kind of function to create, you can use your imagination.

For instance, let’s create a function greet() that says “Hello, there” by default. But once a name is given, the function greets the name.

60. Count the Number of Files in the Present Directory

  1. Use os.listdir(«.») to list everything in the present directory.
  2. Call os.path.isfile() function for each item to verify it is a file.
  3. Return/print the result.

61. Check the File Size in Python

To check the file size of a specific file, use the os.path.getsize() function.

62. Calculate the Power of a Number

In Python, you can compute the power with the double-asterisk operator.

For example, 10^3 can be calculated with:

63. Snake-Casify Strings in Python

Snake case means a writing style where each blank space is replaced by an underscore _.

To create a Python program that converts a string into a snake case, replace each space with a “_”.

This is possible using the built-in replace() method of a string.

64. Camel-Casify Strings in Python

Camel case means writing style where there are no spaces between words. Instead, each word begins with a capital first letter and is connected to the next word.

  1. Split the words into a list by blank space.
  2. Convert each string into a title case (first letter capital).
  3. Join the parts without spaces.

Here is how it looks:

65. Get All Combinations of a List

To get combinations of length r in a list, use itertools.combinations() function.

  1. Loop through numbers from 1 to the length of the list.
  2. Create a combination of the given length and add it to the results list.

Here is a script that computes all combinations of the list [1, 2, 3]:

66. Remove Duplicates from a List

  1. Have a list of items.
  2. Create an empty result list.
  3. Loop through the list of items.
  4. Add each item to the result list if it is not already there.
  5. Return the result.

Here is how it looks in code:

67. Python Program to Replace Characters of a String

Python string has a built-in method called replace() .

  1. A character to be replaced.
  2. A character to be inserted as the replacement.

You can use this method to replace the characters of that string.

For example, let’s replace all “s” characters with “z”:

68. Round Floats to Two Decimals

Python comes in with a built-in function round().

  1. A number to round.
  2. The number of desired decimal places.

The function rounds the number to the given decimal places.

For example, let’s round pi to 2 decimals:

69. Accept Any Number of Keyword Arguments

A keyword argument in Python is a function argument that has a name label attached to it.

An example call to a function with a keyword argument can look like this:

Let’s for example implement a function that takes student info as its argument. You can give it as many keyword arguments as you wish. As a result, it prints the student’s data in a nicely formatted fashion.

Here is the example code:

70. Sum a List

  1. Initialize the result at 0.
  2. Loop through the list of numbers.
  3. Add each number to the result.
  4. Return the result.

Here is the code:

71. Split a String

Python string has a built-in method called split() . This function takes one argument which is the delimiter according to which you want to split the string.

Here are some examples:

72. Get Current Time in Python

You can use Python’s built-in datetime module to obtain the current time.

  1. Import the datetime from datetime module.
  2. Get the current date object.
  3. Grab the time from the current date in a specific format.

Here is how it looks in code:

73. Add Quotes in a String

  1. Use double quotation marks as the string markers and single quotation marks as the quotes.
  2. Use single quotes as the string marker and double quotation marks as the quotes.

Here are both ways in code:

Learn more about quotes and strings in Python.

74. Document a Function Using a Docstring

In Python, you have a special syntax for documenting your code. This is called a docstring.

A docstring is a triple-quote string that can be spread across multiple lines.

The purpose of the docstring is to provide useful information about a function, class, or module. In Python, it is possible to call help() on any function, class, or module. When you do this, the docstring description is printed into the console.

Here is an example:

75. Python Program to Parse a JSON String

To convert a JSON object into a Python dictionary, use json.loads() function. Remember to import the json module before doing this.

Here is an example:

76. Generate a Textual Representation of an Object

When you print an object in Python, you may get a verbose result like this:

But this is not readable and you can make no sense of it.

To fix this, implement a special method called __str__ in your class.

For example, let’s create a Student class. Furthermore, let’s make printing student objects produce a readable result by implementing the __str__ method.

77. Read a File Into a List

  1. Open a file.
  2. Initialize an empty list to store the lines.
  3. Read the lines one by one and store each line on the list.
  4. Close the file.

A great way to deal with files is using context managers. A context manager auto-closes the file after being used. This saves you a little bit of overhead and lines of code. A context manager is used with the with statement.

Given a file called example.txt with the following contents:

You can read the lines in this file to a list with a context manager as follows:

78. Check If a Number Is an Armstrong Number

An Armstrong number is a number whose digits to the power of the length of the number equals the number.

For instance, 1634 is an Armstrong number because: 1^4 + 6^4 + 3^4 + 4^4.

  1. Have a target number.
  2. Initialize an empty sum.
  3. Go through each digit, raise it to the length power, and add to the result.
  4. Check if the result equals the original number.

Here is how it looks in code:

79. Capitalize a String

Python string comes with a built-in upper() method. This method capitalizes the whole string.

80. Break Out of a For Loop

Breaking a loop means jumping out of a loop before the loop is exhausted.

Here is an example of a function that checks if the number matches the target. When it does, the loop is escaped:

Learn more about the break and other control flow statements here.

81. Check a Condition with One Line of Code

In Python, you can replace short if-else statements with one-liners. This is possible using a ternary conditional operator.

Here is an example of how:

82. Calculate Remainder in Division

In Python, you can use the % operator to calculate the remainder in the division.

For example, dividing 11 slices of pizza with 3 guests means 2 leftover slices.

83. Unpack a List to Separate Variables

In Python, it is possible to unpack iterables.

This means you can tear apart iterables to separate variables by comma separating the variables and using assignment operator on the iterable.

84. Square a List of Numbers

  1. Have a list of numbers.
  2. Initialize an empty result list.
  3. Loop through each number.
  4. Raise each number to the second power.
  5. Add the result to the result list.

Here is how it looks in code:

85. Filter Even Numbers

  1. Have a list of numbers.
  2. Initialize an empty result list.
  3. Loop through each number.
  4. Check if the number is even.
  5. Add the result to the result list.

Here is how it looks in code:

Learn more about list filtering in Python here.

86. Join Two or More Strings

Python string comes with a built-in join() method.

This function takes one argument, which is the separator character.

For example, to join strings with empty space as a separator:

Learn more about joining strings and other string methods from here.

87. Remove Specific Values from a List

You can use the filter() function to filter out values based on a criterion.

  1. A filtering function. This is usually a lambda expression.
  2. An iterable, such as a list to be filtered.

The filter() function applies the filtering function on each element of the list to produce the result.

For example, let’s filter out integers from a list:

88. Add Values to the Beginning of a List

  1. A target index.
  2. A string to be placed into the target index.

You can use the insert() method to add an element to the beginning of a list.

Learn more about adding and removing values from Python lists here.

89. Calculate HCF in Python

The Highest Common Factor (HCF) of two numbers is the highest number that evenly divides both numbers.

For example, the HCF of 12 and 36 is 12.

  1. Take two numbers.
  2. Determine the smallest number of the two.
  3. Loop through numbers from 1 to the smallest number.
  4. Check on each value if it factors the greatest number.
  5. Keep track of the highest such number.
  6. At the end of the loop, return the highest factor.

Here is a Python program to find the HCF between two numbers:

90. Show N Fibonacci Numbers

A Fibonacci sequence is a series of numbers where the next number is the sum of the previous two.

For example, 0,1,1,2,3,5,8,13,21,34.

To find a Fibonacci sequence of length n in Python:

91. Python Program to Calculate Age

  1. Subtract the beginning year from the current year.
  2. Remove 0 if the month/day of the beginning date precedes the current month/day.

Here is how it looks in code:

The above program knows how to handle leap years too. Check out this article to learn more.

92. Simulate Throwing a Dice in Python

When you throw a dice, you get 1, 2, 3, 4, 5, or 6.

To simulate dice toss in Python, randomize a number between 1 and 6. You can achieve this using the random module’s randint() function.

Here is how it looks in code:

93. Find Out How Far Is the Horizon

This involves a bit of basic trigonometry.

  1. Earth’s radius + your height.
  2. Earth’s radius.
  3. The distance to the horizon.

Here is how you can implement the equation in your Python program:

94. Calculate the Area of a Circle

The area of a circle is given by A = pi * r^2 .

To write a Python program to calculate the area of a circle, import pi from math module and calculate the area with the above formula:

95. Find the Volume of a Cube

Given a cube of side length a, the volume V = a^3 .

Here is a Python code example on how to calculate the volume of a cube:

96. Measure Elapsed Time

  1. Store the start time in memory.
  2. Run a piece of code.
  3. Store the end time into memory.
  4. Calculate the time difference between the start and end.

Here is how it looks in code:

97. Check If a Set Is a Subset of Another Set in Python

In set theory, set A is a subset of B if all the elements in set A are also in set B.

In Python, you can use the built-in issubset() method to check if a set A is a subset of set B.

Learn more about sets and the issubset() method here.

98. Find N Longest Strings in a Python List

  1. Sort the list of strings based on length.
  2. Pick the n last elements of the sorted list. These are the longest strings.

Here is how it looks in code:

99. Clone a Python List Independently

To take an independent copy of a list, use the deepcopy() method from the copy module.

100. Break List Into N-Sized Chunks

  1. Create an empty result list.
  2. Loop through the original list by taking the chunk-sized steps.
  3. At each step, add the current element and the next i elements to the result list.
  4. When there are no values left, return the list.

Here is how it looks in code:

Conclusion

That is a lot of Python examples. I hope you find it useful where ever you go.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *