In this introductory tutorial, you'll learn all about how to perform definite iteration with Python for loops. You’ll see how other programming languages implement definite iteration, learn about iterables and iterators, and tie it all together to learn about Python’s for loop.
I recently had the opportunity to partner with Sundeep Agarwal, the author of Python re(gex)? to create a bundle with my second book, Python 201: Intermediate Python. The Python Regex book covers Regular Expressions in Python. While only 50 pages in length, it has lots of examples that you can use to learn all about using Regular Expressions in your own code. You can check out the Github repo and see what kind of code is in the book. You can find the bundle on Leanpub.
I am currently working on a new book entitled Creating GUI Applications with wxPython that you can support on Kickstarter. This is the current table of contents for the book: Chapter 1 – Intro to wxPython Chapter 2 – Creating an Image Viewer Chapter 3 – Enhancing the Image Viewer Chapter 4 – Creating a Database Viewer Chapter 5 – Database Editing with wxPython Chapter 6 – Calculator Chapter 7 – Archiver (tarball creation utility) Chapter 8 – MP3 Tag Editor Chapter 9 – XML Editor Chapter 10 – NASA Image Downloader / Search Tool Chapter 11 – PDF Merger / Splitter There will also be a chapter on creating executables and installers for your application and a couple of appendixes. I am doing a second stretch goal to add up to 3 additional chapters to the book. Check out the Kickstarter for more information.
“CVAX — когда вы забатите довольно воровать настоящий лучший”. Надпись, оставленная американскими инженерами для советских коллег в топологии микропроцессора. Реверс-инжиниринг микросхем — головная боль производителей с самых первых лет существования микроэлектроники. Вся советская электроника в какой-то момент была построена на нем, а сейчас с гораздо большим размахом тем же самым занимаются в Поднебесной, да и не только в ней. На самом деле, реверс-инжиниринг абсолютно легален в США, Евросоюзе и многих других местах, с целью (цитирую американский закон) “teaching, analyzing, or evaluating the concepts or techniques embodied in the mask work or circuitry”. Самое частое легальное применение реверс-инжиниринга — патентные и лицензионные суды. Промышленный шпионаж тоже распространен, особенно с учетом того, что электрические схемы (особенно аналоговые) часто являются ключевой интеллектуальной собственностью и редко патентуются — как раз для того, чтобы избежать раскрытия IP и участия в патентных судах в качестве обвиняющей стороны. Разумеется, оказавшись в ситуации, когда нужно защитить свою интеллектуальную собственность, не патентуя ее, разработчики и производители стараются придумать способы предотвращения копирования своих разработок. Другое не менее (а то и более) важное направление защиты микросхем от реверс-инжиниринга — обеспечение безопасности информации, хранимой в памяти. Такой информацией может быть как прошивка ПЛИС (то есть опять-таки интеллектуальная собственность разработчика), так и, например, пин-код от банковской карты или ключ шифрования защищенной флэшки. Чем больше ценной информации мы доверяем окружающему миру, тем важнее защищать эту информацию на всех уровнях работы обрабатывающих ее систем, и хардварный уровень — не исключение.
In this step-by-step Python tutorial, you learn how to get started with The Jupyter Notebook, an open source web application that you can use to create and share documents that contain live code, equations, visualizations, and text.
This week we welcome Lorena Mesa (@loooorenanicole) as our PyDev of the Week! Lorena is an organizer for the PyLadies Chicago group and a director at the Python Software Foundation. You can check out some of the things that she is up to on her blog or via her Github page. Let’s spend a few moments getting to know her better! Can you tell us a little about yourself (hobbies, education, etc): Hmmm … I have been told that I’m a bit eclectic. So let’s start with the basics, in my day to day gig I am a proud member of GitHub’s software intelligence systems team as a data engineer. In my etc hours I do such things as co-organize PyLadies Chicago and serve as a Director for the Python Software Foundation. Things I do for fun? I’m an avid runner having taken on the Chicago Marathon 13 times now. Why? I encourage you to read Haruki Murakami’s “What I talk about when I talk about running” before you ask me that.Jazz, italo disco, and loud 1980s ballads are equal parts guilty pleasure for me. Meaning of course I’ve been learning the sax and getting pretty good at it lately. (Yes, I can play Careless Whispers).I’m learning Klingon – https://www.kli.org/. You can find my random musings when I post on my personal blog at lorenamesa.com on such things as traveling, tech, and other tidbits. Continue reading PyDev of the Week: Lorena Mesa →
In this screencast, we will learn how to turn your Python code into a Windows executable file using the PyInstaller project. You can also read the chapter this video is based on here or get the book on Leanpub Python 101
Рассказывает Адам Гейтджи, разработчик в LinkedIn Learning
Привет, Хабр! По поводу случившегося на днях послабления режима, возмущения в комментариях одного соседнего поста о том, что статьи про микроконтроллеры — сплошь мигание светодиодом, а также безвременной гибели моего стандалон-блога, восстанавливать который мне пока лень, переложу сюда полезный материал об одном прискорбно мало освещаемом прессой трюке в работе с ядрами Cortex-M — проверке произвольных адресов на валидность. Одна из весьма полезных и при этом почему-то в готовом виде нигде не описанных возможностей на микроконтроллерах Cortex-M (всех) — это возможность проверки корректности адреса в памяти. С её помощью можно определять размеры флэша, ОЗУ и EEPROM, определять наличие на конкретном процессоре конкретной периферии и регистров, прибивать упавшие процессы при сохранении общей работоспособности ОС и т.п.
In this tutorial on Python's "requests" library, you'll see some of the most useful features that requests has to offer as well as how to customize and optimize those features. You'll learn how to use requests efficiently and stop requests to external services from slowing down your application.
The Kickstarter campaign for my latest book has been going quite well, so I thought it would be fun to share some sample chapters of the book with you. You can check out the first couple of chapters here as a PDF. I have also been doing some experiments with regards to some of the ideas that were given about other chapters for the book for the stretch goals of the Kickstarter. I haven’t made any concrete decisions as of yet, but I do think that interacting with the NASA website’s API sounds fun and appears easy to do as well. I will research the feasibility of the other ideas too. Thanks so much for your support!
In this tutorial, you'll learn how you can work with files in Python by using built-in modules to perform practical tasks that involve groups of files, like renaming them, moving them around, archiving them, and getting their metadata.
Рассказывает Уилл Кёрсен, data scientist в Cortex Intel
Привет! Я Дима, и я довольно давно и плотно сижу на Python. Сегодня хочу показать вам отличия двух асинхронных фреймворков — Tornado и Aiohttp. Расскажу историю выбора между фреймворками в нашем проекте, чем отличаются корутины в Tornado и в AsyncIO, покажу бенчмарки и дам немного полезных советов, как забраться в дебри фреймворков и успешно оттуда выбраться.
This tutorial will give you a firm grasp of Python’s approach to async IO, which is a concurrent programming design that has received dedicated support in Python, evolving rapidly from Python 3.4 through 3.7 (and probably beyond).
Если кто не знает мне интересно программирование на ассемблере для микроконтроллеров STM32… И все бы хорошо, да только программировать особо негде… Те среды которые есть в настоящий момент заточены больше для языка Си и программирование в них на ассемблере не сильно отличается от программирования в блокноте, ну может быть только многооконность удобна, да еще компиляция (если настроить все так как любит среда). Некоторое время назад (всего 2 года прошло) я сетовал о том что нужен программист для ее написания, но дело с тех пор не сдвинулось… Поэтому вспомнив знаменитую поговорку: «Если гора не идет к Магомеду, Магомед идет к горе» — решил в итоге начать писать самостоятельно… Дальше под катом (будут картинки!!)
In this screencast, we will learn how to turn your Python code into a Windows executable file using the cx_Freeze project. You can also read the chapter this video is based on here or get the book on Leanpub Python 101
Хранение паролей всегда было головной болью. В классическом варианте у вас есть пользователь, который очень старается не забыть жутко секретный «qwerty123» и информационная система, которая хранит хеш от этого пароля. Хорошая система еще и заботливо солит хеши, чтобы отравить жизнь нехорошим людям, которые могут украсть базу с хешированными паролями. Тут все понятно. Какие-то пароли храним в голове, а какие-то засовываем в зашифрованном виде в keepass. Все меняется, когда мы убираем из схемы человека, который старательно вводит ключ с бумажки. При взаимодействии двух информационных систем, на клиентской стороне в любом случае должен храниться пароль в открытом для системы виде, чтобы его можно было передать и сравнить с эталонным хешем. И вот на этом этапе админы обычно открывают местный филиал велосипедостроительного завода и начинают старательно прятать, обфусцировать и закапывать секретный ключ в коде скриптов. Многие из этих вариантов не просто бесполезны, но и опасны. Я попробую предложить удобное и безопасное решение этой проблемы для python. И чуть затронем powershell.
In this Python tutorial, we'll look at what concurrency is and why you might want to use it. We'll see a simple, non-concurrent approach and then look into why you'd want threading, asyncio, or multiprocessing.
I am pleased to announce my latest book project, Creating GUI Applications with wxPython which I am running a Kickstarter campaign for. Creating GUI Applications with wxPython is a book that will teach you how to use wxPython to create applications by actually creating several mini-programs. I have found that while learning how the various widgets work in wxPython is valuable, it is even better to learn by creating a simple application that does something useful. The code in this book will be targeted for Python 3 only using wxPython 4. For more information, please check out the Kickstarter.
This week we welcome Lance Bragstad (@LanceBragstad) as our PyDev of the Week! Lance is a core developer of the OpenStack project. You can find out more about his passions via his website or his Github profile. Let’s spend some time getting to know Lance! Can you tell us a little about yourself (hobbies, education, etc): In 2012, I graduated with a degree in Computer Science from North Dakota State University, located in Fargo (yup, like the movie). Since then I’ve become more and more passionate about open-source software. I spend most of my time in the OpenStack ecosystem. Besides being passionate about open-source software, I’m an avid outdoorsman. My wife and I train for running events together. I also donate time as a volunteer firefighter for our community of about 700 people. Continue reading PyDev of the Week: Lance Bragstad →
Вступление В последнее время активно изучаю язык программирования Python. Особенно меня заинтересовало использование Python в распознавании и классификации лиц. В статье я попробую применить распознавание лиц для сериала «Теория Большого взрыва».
Check out the just-launched video course, Introduction to Ansible on Talk Python Training. This is the perfect course for you if you want to learn to configure servers and deploy web apps... (read more)
In this tutorial, you’ll get comfortable with Django migrations and learn how to create database tables without writing any SQL, how to automatically modify your database after you changed your models, and how to revert changes made to your database.
In this screencast, we will learn how to turn your Python code into a Windows executable file using the bbfreeze project. You can also read the chapter this video is based on here or get the book on Leanpub Python 101 Related Reading A bbfreeze Tutorial – Build a Binary Series!
In this guide, you'll look at Python type checking. Traditionally, types have been handled by the Python interpreter in a flexible but implicit way. Recent versions of Python allow you to specify explicit type hints that can be used by different tools to help you develop your code more efficiently.
This week we welcome Kushal Das (@kushaldas) as our PyDev of the Week! Kushal is a core developer of the Python programming language and a co-author of PEP 582. You can learn more about Kushal by checking out his blog or his Github profile. Let’s take a few moments to get to know Kushal better! blog Can you tell us a little about yourself (hobbies, education, etc): I am a staff member of Freedom of the Press Foundation. We are a non-profit that protects, defends, and empowers public-interest journalism in the 21st century. We work on encryption tools for journalists and whistleblowers, documentation of attacks on the press, training newsrooms on digital security practices, and advocating for the the public’s right to know. I am also part of various Free Software projects through out my life. I am a core developer of CPython, and a director of the Python Software Foundation. I am part of the core team of the Tor project. I am a regular contributor to Fedora Project for over a decade now. I co-ordinate https://dgplug.org along with a large group of friends and fellow contributors in various projects. We spend time together in learning new things and helping out each other on the #dgplug IRC channel on Freenode server. Feel free to visit the channel and say “Hi” to us. I try to write about the things I learn regularly on my blog. Continue reading PyDev of the Week: Kushal Das →
The wxPython GUI toolkit has a very rich and powerful Grid widget that I have written about previously on this blog. It allows you to create sheets of cells similar to those in Microsoft Excel. There is also a neat mixin that allows you to apply a custom renderer to the labels on the columns and rows of the grid. Let’s take a look at that and see how it works: import wx import wx.grid as grid import wx.lib.mixins.gridlabelrenderer as glr class MyGrid(grid.Grid, glr.GridWithLabelRenderersMixin): def __init__(self, *args, **kw): grid.Grid.__init__(self, *args, **kw) glr.GridWithLabelRenderersMixin.__init__(self) class MyColLabelRenderer(glr.GridLabelRenderer): def __init__(self, bgcolor): self._bgcolor = bgcolor def Draw(self, grid, dc, rect, col): dc.SetBrush(wx.Brush(self._bgcolor)) dc.SetPen(wx.TRANSPARENT_PEN) dc.DrawRectangle(rect) hAlign, vAlign = grid.GetColLabelAlignment() text = grid.GetColLabelValue(col) self.DrawBorder(grid, dc, rect) self.DrawText(grid, dc, rect, text, hAlign, vAlign) class MyPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) grid = MyGrid(self, size=(100, 100)) grid.CreateGrid(numRows=10, numCols=10) for col in range(0, 10, 3): grid.SetColLabelRenderer( col+0, MyColLabelRenderer('#e0ffe0')) grid.SetColLabelRenderer( col+1, MyColLabelRenderer('#e0e0ff')) grid.SetColLabelRenderer( col+2, MyColLabelRenderer('#ffe0e0')) main_sizer = wx.BoxSizer(wx.VERTICAL) main_sizer.Add(grid, 1, wx.EXPAND) self.SetSizer(main_sizer) class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title='Custom Grid Renderers') panel = MyPanel(self) self.Show() if __name__ == '__main__': app = wx.App(False) frame = MyFrame() app.MainLoop() Let’s break this down a bit. You will notice at the top of the code that we need to import the Grid widget separately in wxPython. We also need to import a mixin called GridWithLabelRenderersMixin. We subclass the Grid class and add in the mixin and then initialize both. Next we create a subclass of GridLabelRenderer, which is also from the mixin. This allows us to create a spacing Draw method that will give us the ability to apply different colors or fonts to the labels in our Grid. In this case, I just made it so that we could change the color of the text in the labels. The last piece of code that we are interested in is in the MyPanel class where we actually instantiate the Grid and change the color of the background of the labels in the columns. Here is what the grid ended up looking like: Custom Grid Column Renderers Wrapping up The wxPython toolkit has dozens of pre-built widgets that you can use to create cross-platform user interfaces. The wxPython demo has a much more involved example than this article does that you might also find interesting. If you haven’t given wxPython a try, you really should go get it. It is pip installable from PyPI and compatible with Python 3.
In this screencast, we will learn how to turn your Python code into a Windows executable file using py2exe. You can also read the chapter this video is based on here or get the book on Leanpub Python 101