Monday, May 31, 2021

Python Pool: [Solved] IOError errno 2 no such file or directory

Like any programming language, an error in python occurs when a given code fails to follow the syntax rules. When a code does not follow the syntax, python cannot recognize that segment of code, so it throws an error. Errors can be of different types, such as runtime error, syntax error, logical error, etc. IOError errno 2 no such file or directory is one such type of error. Let us first understand each individual term of the error.

Note : Starting from Python 3.3, IOError is an aliases of OSError

What is IOError?

An IOError is thrown when an input-output operation fails in the program. The common input-output operations are opening a file or a directory, executing a print statement, etc. IOError is inherited from the EnvironmentError. The syntax of IOError is:

IOError : [Error number] ‘Reason why the error occurred’: ‘name of the file because of which the error occurred’

Examples of IOError are :

  • Unable to execute the open() statement because either the filename is incorrect or the file is not present in the specified location.
  • Unable to execute the print() statements because either the disk is full or the file cannot be found
  • The permission to access the particular file is not given.

What is errno2 no such file or directory?

The ‘errorno 2 no such file or directory‘ is thrown when you are trying to access a file that is not present in the particular file path or its name has been changed.

This error is raised either by ‘FileNotFoundError’ or by ‘IOError’. The ‘FileNotFoundError’ raises ‘errorno 2 no such file or directory‘ when using the os library to read a given file or a directory, and that operation fails.

The ‘IOError’ raises ‘errorno 2 no such file or directory‘ when trying to access a file that does not exist in the given location using the open() function.

Handling ‘IOError [errorno 2] no such file or directory’

‘IOError errorno 2 no such file or directory‘ occurs mainly while we are handling the open() function for opening a file. Therefore, we will look at several solutions to solve the above error.

We will check if a file exists, raise exceptions, solve the error occurring while installing ‘requirements.txt,’ etc.

Checking if the file exists beforehand

If a file or a directory does not exist, it will show ‘IOError [errorno 2] no such file or directory’ while opening it. Let us take an example of opening a file named ‘filename.txt’.

The given file does not exist and we shall see what happens if we try to execute it.

f = open('filename.txt')

Since the above text file does not exist, it will throw the IOError.

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    f = open('filename.txt')
IOError: [Errno 2] No such file or directory: 'filename.txt'

To avoid the above error from being thrown, we will use several methods which will first check if the file exists or not. It will execute the open() function only if the file exists.

We have two modules containing functions for checking if a file exists.

  1. OS Module
  2. Pathlib Module

Using the OS Module

In the os module, there are three functions which can be used:

  • os.path.isfile()
  • os.path.isdir()
  • os.path.exists()

To solve the IOError, we can use either of the above function in a condition statement. We will pass the pathname of the file as an argument to the above functions.

If the file or the directory exists, the function shall return True else False. Bypassing either of the above functions as the conditional statement ensures that python will open a file only if it exists, thus preventing an error from occurring.

We will use os.path.isfile() when we want to check if a file exists or not, os.path.isdir() to check if a directory exists or not and os.path.exists() to check if a path exists or not.

Since we want to check for a file, we can use either the os.path.isfile() function or os.path.exists() function. We shall apply the function to the above example.

import os

path_name = "filename.txt"

if os.path.isfile(path_name):
  print("File exists")
  f = open(path_name)
  #Execute other file operations here
  f.close()
  
else:
  print("File does not exist! IOError has occured")

First, we have imported the os module. Then we have a variable named ‘path_name‘ which stores the path for the file.

We passed the path_name as an argument to the os.path.isfile() function. If the os.path.isfile() function returns a true value. Then it will print “File exists” and execute the other file operations.

If the file does not exist, then it will print the second statement in the else condition. Unlike the previous case, here, it will not throw an error and print the message.

File does not exist! IOError has occured

Similarly, we can also use os.path.exists() function.

Using the pathlib module

The pathlib module contains three functions – pathlib.Path.exists(), pathlib.Path.is_dir() and pathlib.Path.is_file().

We will use pathlib.Path.is_file() in this example. Just like the os module, we will use the function in an if conditional statement.

It will execute the open() function only if the file exists. Thus it will not throw an error.

from pathlib import Path
path_name = "filename.txt"
p = Path(path_name)
if p.is_file():
  print("File exists")
  f = open(path_name)
  #Execute other file operations here
  f.close()
  
else:
  print("File does not exist! IOError has occured")

Since the file does not exist, the output is :

File does not exist! IOError has occured

Using try – except block

We can also use exception handling for avoiding ‘IOError Errno 2 No Such File Or Directory’. In the try block, we will try to execute the open() function.

If the file is present, it will execute the open() function and all the other file operations mentioned in the try block. But, if the file cannot be found, it will throw an IOError exception and execute the except block.

try:
    f = open("filename.txt")
    #Execute other operations
    f.close()
except IOError as io:
    print(io)

Here, it will execute the except block because ‘filename.txt’ does not exist. Instead of throwing an error, it will print the IOError.

[Errno 2] No such file or directory: 'filename.txt'

We can also print a user defined message in the except block.

try:
    f = open("filename.txt")
    #Execute other operations
    f.close()
except IOError:
    print("File does not exist. IOError has occured")

The output will be:

File does not exist. IOError has occured

IOError errno 2 no such file or directory in requirements.txt

Requirements.txt is a file containing all the dependencies in a project and their version details.

Basically, it contains the details of all the packages in python needed to run the project. We use the pip install command to install the requirements.txt file. But it shows the ‘IOError errno 2 no such file or directory’ error.

!pip install -r requirements.txt

The thrown error is:

ERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt'

To solve the above error, we use the pip freeze command. When we use pip freeze, the output will contain the package along with its version.

The output will be in a configuration that we will use with the pip install command.

pip freeze > requirements.txt

Now, we will try to execute the pip install command again. It will no longer throw errors and all the packages will be installed successfully.

Opening file in ‘w+’ mode

While trying to open a text file, the default mode will be read mode. In that case, it will throw the ‘IOError Errno 2 No Such File Or Directory’ error.

f = open("filename.txt")
f.close()
print("Successful")

The output is:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    f = open("filename.txt")
IOError: [Errno 2] No such file or directory: 'filename.txt'

To solve the error, we can open the file in ‘w+’ mode. This will open the file in both – reading and writing mode. If the file does not exist, it will create a new file, and if the file exists, it will overwrite the contents of the file. This way, it will not throw an error.

f = open("filename.txt", 'w+')
f.close()
print("Successful")

The output is:

Successful

Apart from all the above methods, there are some ways to ensure that the IOError does not occur. You have to ensure that you are giving the absolute path as the path name and not simply the name of the file.

Also, see to that there are no escape sequences in the path name of this file.

For example : In path_name = "C:\name.txt ", it will consider the '\n' from '\name.txt' as an escape sequence. 

So, it will not be able to find the file 'name.txt'.

Also, Read

FAQ’s on IOError Errno 2 No Such File Or Directory

What is the difference between FileNotFoundError and IOError

Both the errors occur when you are trying to access a file that is not present in the particular file path, or its name has been changed. The difference between the two is that FileNotFoundError is a type of OSError, whereas IOError is a type of Environment Error.


This sums up everything about IOError Errno 2 No Such File Or Directory. If you have any questions, do let us know in the comments below.

Until then, Keep Learning!

The post [Solved] IOError errno 2 no such file or directory appeared first on Python Pool.



from Planet Python
via read more

AI Pool: Difference between SAME and VALID padding schemes

In TensorFlow or in Keras padding takes 2 arguments 'same' and 'valid' . What does it mean? Why don't we have other options?...

from Planet Python
via read more

AI Pool: Memory usage in keras

I'm using Keras 2.0 and can't use the GPU when my model is in the training process. It gives me out of memory. How can I use GPU during the training process?...

from Planet Python
via read more

AI Pool: What is AVX Cpu support in tensorflow

I'm getting an error like this cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2 what does it mean?...

from Planet Python
via read more

AI Pool: Keras save and load model

How to save and load a Keras model? I am using Keras 2.*...

from Planet Python
via read more

AI Pool: Save/Load tensorflow model

What is the best way to save a TensorFlow model, so I can load it fastly and easily?...

from Planet Python
via read more

Difference between SAME and VALID padding schemes

In TensorFlow or in Keras padding takes 2 arguments 'same' and 'valid' . What does it mean? Why don't we have other options?...

from Planet SciPy
read more

Memory usage in keras

I'm using Keras 2.0 and can't use the GPU when my model is in the training process. It gives me out of memory. How can I use GPU during the training process?...

from Planet SciPy
read more

What is AVX Cpu support in tensorflow

I'm getting an error like this cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2 what does it mean?...

from Planet SciPy
read more

Keras save and load model

How to save and load a Keras model? I am using Keras 2.*...

from Planet SciPy
read more

Save/Load tensorflow model

What is the best way to save a TensorFlow model, so I can load it fastly and easily?...

from Planet SciPy
read more

Real Python: Python News: What's New From May 2021?

If you want to get up to speed on what happened in the world of Python in May 2021, then you’ve come to the right place to get your news!

May was a month of big events. The Pallets Projects, home to popular frameworks like Flask and Click, released new major versions of all six of its core projects. The Python Software Foundation (PSF) hosted PyCon US 2021, a virtual conference that delivered an authentic in-person experience.

Let’s dive into the biggest Python news from the past month!

Free Download: Get a sample chapter from CPython Internals: Your Guide to the Python 3 Interpreter showing you how to unlock the inner workings of the Python language, compile the Python interpreter from source code, and participate in the development of CPython.

Microsoft Becomes the Third PSF Visionary Sponsor

In last month’s news roundup, we covered how Google and Bloomberg Engineering became the first two PSF Visionary Sponsors. At the end of April, the PSF also announced that Microsoft increased its support to the Visionary level.

Microsoft is directing its financial support to the Python Packaging Working Group:

As part of our $150K financial sponsorship of the PSF, we will be focusing our funds to the Packaging Working Group to help with development costs for further improvements to PyPI and the packaging ecosystem. With recently disclosed security vulnerabilities, trusted supply chain is a critical issue for us and the Python community, and we are excited to help contribute to long-term improvements. (Source)

In addition to its Visionary sponsor status, Microsoft also has five Python core developers on staff that contribute to Python part-time: Brett Cannon, Steve Dower, Guido van Rossum, Eric Snow, and Barry Warsaw.

For more information about Microsoft’s support for Python and the PSF, check out its official announcement.

Check out Steve Dower’s account to get an inside scoop on how Microsoft’s position toward Python has changed over the years. You can also listen to Brett Cannon share his experience with Python at Microsoft on the Real Python Podcast.

Pallets Releases New Major Versions of All Core Projects

Two years of hard work from the Pallets team and its many open source contributors has culminated in the release of new major versions for all six of its core projects:

All six projects have dropped support for Python 2 and Python 3.5, making Python 3.6 the minimum supported version. Previously deprecated code has been removed, and some new deprecations have been added.

Some of the major changes affecting all six projects include:

Read the full article at https://realpython.com/python-news-may-2021/ »


[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]



from Planet Python
via read more

Python News: What's New From May 2021?

If you want to get up to speed on what happened in the world of Python in May 2021, then you’ve come to the right place to get your news!

May was a month of big events. The Pallets Projects, home to popular frameworks like Flask and Click, released new major versions of all six of its core projects. The Python Software Foundation (PSF) hosted PyCon US 2021, a virtual conference that delivered an authentic in-person experience.

Let’s dive into the biggest Python news from the past month!

Microsoft Becomes the Third PSF Visionary Sponsor

In last month’s news roundup, we covered how Google and Bloomberg Engineering became the first two PSF Visionary Sponsors. At the end of April, the PSF also announced that Microsoft increased its support to the Visionary level.

Microsoft is directing its financial support to the Python Packaging Working Group:

As part of our $150K financial sponsorship of the PSF, we will be focusing our funds to the Packaging Working Group to help with development costs for further improvements to PyPI and the packaging ecosystem. With recently disclosed security vulnerabilities, trusted supply chain is a critical issue for us and the Python community, and we are excited to help contribute to long-term improvements. (Source)

In addition to its Visionary sponsor status, Microsoft also has five Python core developers on staff that contribute to Python part-time: Brett Cannon, Steve Dower, Guido van Rossum, Eric Snow, and Barry Warsaw.

For more information about Microsoft’s support for Python and the PSF, check out its official announcement.

Check out Steve Dower’s account to get an inside scoop on how Microsoft’s position toward Python has changed over the years. You can also listen to Brett Cannon share his experience with Python at Microsoft on the Real Python Podcast.

Pallets Releases New Major Versions of All Core Projects

Two years of hard work from the Pallets team and its many open source contributors has culminated in the release of new major versions for all six of its core projects:

All six projects have dropped support for Python 2 and Python 3.5, making Python 3.6 the minimum supported version. Previously deprecated code has been removed, and some new deprecations have been added.

Some of the major changes affecting all six projects include:

Read the full article at https://realpython.com/python-news-may-2021/ »


[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]



from Real Python
read more

EuroPython: EuroPython 2021: Session List Available

Our program work group (WG) has been working hard over the last week to select sessions for EuroPython 2021, based on your talk voting and our diversity criteria.

We’re now happy to announce the initial list with more than 100 sessions, brought to you by more than 100 speakers.

altEuroPython 2021 Session List

More than 130 sessions

In the coming weeks, we will complete the session list, adding keynotes, sponsored talks and training sessions. Once finalized, we expect to have more than 130 sessions waiting for, including three lightning talk slots, six keynotes, a recruiting session and several free sponsored training sessions.

The program workgroup will start working on the schedule, which should be ready in about two weeks.

Conference Tickets

Conference tickets are available on our registration page. We have several ticket types available to make the conference affordable for everyone and we're also offering financial aid to increase our reach even more.

As always, all proceeds from the conference will go into our grants budget, which we use to fund financial aid for the next EuroPython edition, special workshops and other European conferences and projects:

EuroPython Society Grants Program

We hope to see lots of you at the conference in July. Rest assured that we’ll make this a great event again — even within the limitations of running the conference online.

Enjoy,
EuroPython 2021 Team
EuroPython Society
EuroPython 2021 Website



from Planet Python
via read more

Codementor: How to Make a Phone Call in Python Using Plivo’s Voice API

How to Make a Phone Call in Python Using Plivo’s Voice API

from Planet Python
via read more

Mike Driscoll: PyDev of the Week: Jaime Buelta

This week we welcome Jaime Buelta (@jaimebuelta) as our PyDev of the Week! Jaime has written several books on automation with Python as well as on Docker. You can see some of his books over on Amazon.

You can also catch up with Jaime by visiting his website.

Let’s spend a few moments getting to know Jaime better!

Can you tell us a little about yourself (hobbies, education, etc):

I am a Spanish developer currently working as Software Architect in Double Yard, Dublin in projects bringing AI solutions to the educational world, which is an interesting challenge. I’ve been in tech for the last 20 years and worked in many industries, including aerospace, financial or gaming industry. I got a break for a couple of years where I set up a comic book store, which only lasted a couple of years.

I got a degree in telecommunications engineering in Alcalá de Henares University, near my hometown in Madrid. In Spain this degree was the traditional way to get into computer sciences, in a similar way that in other universities was through electrical engineering. Since I got my first computer, a ZX Spectrum, I’ve always been interested in computers.For my first professional years I was mainly developing in C, which is a great way of being frustrated while you learn how the machine works.

About hobbies, I play the guitar, though not as often as I used to. I am recently trying to get into making podcasts, a medium that I think is really interesting and I’ve been a long time fan. I also like very unsurprising things for a developer like Star Trek. What can I say? I guess I’m such a geek!

Why did you start using Python?

I started learning Python around 2008. It started more as a side project, I was looking for a new language to learn, tried a bit of Java because of my work, but I didn’t like it. I had heard a lot of nice things about Python, and I started learning in my spare time. My first Python code was pretty much “C written with Python syntax”

I really loved it, and started introducing it to more and more things in my job. One of the first things that I was able to do was pretty crazy macros inside Open Office (now Libre Office), which has an internal Python interpreter. The code was truly crazy, and probably much worse to what I would write today, I was experimenting a lot with the capacities of Python, but I was able to do a lot of data processing with spreadsheets.

I got so interested in it that I started looking for jobs that will allow me to work full time as a Python developer, which I did in 2010 when I moved to Dublin. And since then it has been the main language that I’ve used professionally. Still loving it!

What other programming languages do you know and which is your favorite?

C still has a place in my heart, though I haven’t used it much in recent years. I’ve done my fair bit of bash and Javascript and also used more sparingly languages like Ruby or Erlang. These days, using Kubernetes, feels like YAML files are their own language.

Python is still my favourite by a large margin.

What projects are you working on now?

Currently, I am working in a project to create a proctoring solution for online exams. During the last year this has been an area that has exploded in interest, due the COVID pandemic, so we’ve been quite busy. I’m working now closely with teams that do areas where I don’t have that much experience, like doing clients for Mac and Windows, while most of my expertise has been server side. Also there are AI components, which is another area that was totally new for me. So I’m learning a lot at the moment!

I also maintain a small utility that I created to search in the command line, called ffind. Most of development in the last couple of years has been to be sure that’s compatible with newer versions of Python, and improving the tests and CI pipeline. It was something that I created to scratch my own itch and I use it everyday and I’m quite proud of it, even if it’s tiny.

Which Python libraries are your favorite (core or 3rd party)?

To me, the greatest Python library ever is requests. It’s such a joy to use for HTTP requests, the documentation is fantastic and the API is great to use. It’s the gold standard in third-party libraries, and that we all should aim to do if creating an external library.

I also like a lot Django REST framework, which is very useful for creating RESTful applications through Django. And another really useful one is sh, which allows to replace bash scripts with Python in a much simpler way.

The “batteries-included” libraries are very useful as well. I like argparse as well, it’s very easy to create a simple CLI for scripts.

If you had to pick one of the books you have authored as your favorite, which would you pick and why?

While I like them all, obviously, I think that I will have to pick “Hands-On Docker for Microservices with Python”. I think that I was able to get a lot of lessons that I learned about structuring systems and working with scalable systems. It covers a lot of things that interest me greatly, like RESTful services, containers, running clusters in production and creating healthy operations practices. I think I was able to talk about some of the things that took me a while to realise, so I hope it helps others to make the process a bit faster.

What have you learned from being an author?

That writing is hard! Sorry, I knew that from before… My grandfather was a writer and I got an idea from an early age on how much effort goes into writing something. Also, being Spanish my first language, it makes the process arduous.

Other than that, another thing that becomes obvious is that you learn a lot by doing the process of structuring what to write down, creating examples, etc. It really forces you to understand what you are explaining.

Is there anything else you’d like to say?

I have a blog that I update from time to time at https://wrongsideofmemphis.com/ , in case someone wants to take a look.

Thanks for doing the interview, Jaime!

The post PyDev of the Week: Jaime Buelta appeared first on Mouse Vs Python.



from Planet Python
via read more

Sunday, May 30, 2021

Python Pool: Know Everything About PythonWin IDE

PythonWin is the name of the IDE (Interactive Development Environment) for the Windows extension. It gets installed by default whenever you install Python for windows extension.

Thus, for all the python programs running on the Windows operating system, PythonWin acts as a graphical user interface for running the programs. In addition, it has several features in its environment, which makes debugging and editing python code an easier task.

What is an IDE?

IDE stands for Interactive Development Environment. Since PythonWin is an IDE, it is essential to know first what exactly is an IDE. An IDE is a single software that contains all the features for building applications.

The features contained inside an IDE are code editor, debugger, building tools, and compiler. By using an IDE, we don’t have to configure each tool separately. Thus, enabling us to develop applications at a faster rate.

Apart from PythonWin, python has different IDEs such as PyCharm, Visual Studio Code, Jupyter Notebook, Google Colab, Sublime Text, etc.

Installing PythonWin

To install PythonWin on a windows computer, you need to download ‘Python for Windows Extensions‘ from SourceForge.

The link for the download is : https://sourceforge.net/projects/pywin32/

The SourceForge page would appear something like this:

Downlon pythonwin

Click on the Download option and select the latest suitable version for your computer. First, you need to ensure that the PythonWin version is compatible with the version of the python software downloaded on your computer.

After that, the download will start right away.

After installing, a window will appear for the PythonWin setup. Click on Next.

pythonwin installation-1

Then, it will ask for the location of the directory in which the Python software is installed. If you have already installed it, it will find the location by default. Again click on Next.

pythonwin 2

The installation will start.

installing pythonwin third step

Now, click on Finish.

Finishing the installation of pythonwin

Now if you will search for PythonWin on the windows start menu, you can see that it has been installed on your local computer.

searching for the ide

Opening PythonWin

After installing the software, when you will open the PythonWin application, it would look something like this:

opening pythonwin

As you can see, the software’s toolbar and menu bar are visible on the top of the screen. The interactive window is where we will type the python commands and run them. The three arrows (>>>) here indicate the command prompt.

Executing a Code

We will try to execute running a print statement in PythonWin. We will print the statement “Programming in PythonWin“. For that, you have to type:

print(“Programming in PythonWin”) next to the ‘>>>’ symbol. The statement will be printed as the output.

pythonwin executing code

Creating a New script

To create a new script, go to the ‘File‘ option present in the toolbar. Then, click on the first option – ‘New‘ or you can press the control key + N.

A window will appear. Click on ‘Python Script‘ from the given options and select ‘OK.’

A new window titled ‘Script1‘ will appear as the new script.

pythonwin creating script

Let us try to run some code in this new script.

We will try to perform simple addition of two numbers. We will take two numbers ‘a’ and ‘b’ from the user and print their addition.

wring code

Now, to execute the code, we will have to first save the script. To save the script, click on File from the toolbar. Click on the ‘Save’ option or press the control key + S. A window pops up.

Give the script a name and click on the ‘Save‘ button. Here, we have given it the name ‘Script1‘ with the .py‘ extension.

Running the New Script

To run that script, click on the ‘Run‘ icon present on the top. A window named ‘Run Script‘ will appear.

The window will mention the location of the script file. It has two other fields: ‘ Arguments‘ and ‘Debugging.’ By default, the debugging field will be set to ‘No debugging.’ Click on ‘OK.’

Now, since the above code accepts input from the user, it will first ask for the user to Enter first number. Enter an input number and click on OK.

pythonwin running script

Then, enter the second number and click on OK.

pythonwin executing script

In the interactive window, the output will be printed. In this case, the output is

'Their summation is : 15'. 
pythonwin running script

To open a given file, you can either press ‘ctrl + O” or go to ‘File‘ and select ‘Open.’ Now, select the location of the script file from the window pop up and click on ‘Open‘. The script file will open.

Debugging with PythonWin

PythonWin is known for its debugging features which help in writing a code efficiently. Debugging refers to the process of finding and removing errors and bugs from a code.

PythonWin has several debugging tools which help in identifying and resolving errors. Debugging shall execute our code line by line for any error.

PythonWin has a check option that will find any syntax errors if present in the code. At the bottom of the window, it will list the syntax error along with the line in which it occurred.

For example, in the ‘Script1’ program, we will remove one parenthesis from the first input statement. Then, on using the check tool, it will display ‘Syntax Error‘ at the bottom of the window.

debugging in IDE
The error says 'Invalid Syntax'. 

In case of multiple errors, it will show one error at a time, line by line. After typing the missing parenthesis, the error will be resolved. At the bottom, it will show the message that it was successfully able to check the file.

Now, we will see the debugging tools available in PythonWin. From the ‘View‘ option in the toolbar, click on tools. There, check on the ‘Debugging‘ option.

pythhonwin debugging

You will see an entire toolbar containing debugging tools appears.

pythonwin Menu Bar

‘Watch’ tool: It helps in keeping track of the changes occurring in the variables.

‘Step’ tools: These three tools step through the list by debugging one line at a time.

‘Breakpoint’ tool: Used to set a breakpoint to fulfil a condition.

FAQ’s

What is ArcGIS in reference to PythonWin?

ArcGIS is a library in python containing a powerful set of tools for analysis and visualization. We can use the PythonWin IDE for ArcGIS.
To use PythonWin on ArcGIS, go to ArcGIS Pro Python’s command prompt. Type the ‘idle’ in the command prompt, and this would load the graphical user interface of the PythonWin idle.

What is the difference between PythonWin and IDLE?

PythonWin is an IDE. IDLE stands for Integrated development and learning environment.
PythonWin is a software development package containing tools such as Debugger, editor, compiler, and building tools.
At the same time, IDLE consists of basic packages and concepts of an IDE. The purpose of IDLE is for learning and education.


That sums up PythonWin. If you have any questions, let us know in the comments below.

Till then, Happy Learning!

The post Know Everything About PythonWin IDE appeared first on Python Pool.



from Planet Python
via read more

Mike C. Fletcher: PycraftServer Plugin

So the boys (and their cousin) are both into Minecraft again, so I've been refining the Pycraft code quite a bit. We no longer use the RaspberryJuice plugin, but instead have a custom Bukkit plugin that does Java reflection/introspection to auto-generate the API. That lets us do a lot more, manipulate inventories, read and write large sets of blocks, and generally act like a first-class client of the Bukkit API. (Bukkit is a common core api shared between Bukkit, Spigot and Paper servers).

The core idea is still the same, let coder parents setup a Dockerised container with plugins that let you connect Pocket Edition and Java Edition Minecraft to the same server, without needing any mucking about on the clients (e.g. you don't need to install a mod-pack on the client), and let you create "magic" by writing (Python) code.

The chat interface means you can do things like:

echo([circle(center=user.position+(0,i,0),material='obsidian') for i in range(8)])

right in the Minecraft chat and get an 8m high round tower, or you can write extensions in Python modules and load them into the namespace for use at runtime.

Code is up on github if you'd like to play with it (or play with the backend extension).



from Planet Python
via read more

Matthew Wright: How to iterate over DataFrame rows (and should you?)

One of the most searched for (and discussed) questions about pandas is how to iterate over rows in a DataFrame. Often this question comes up right away for new users who have loaded some data into a DataFrame and now want to do something useful with it. The natural way for most programmers to think … Continue reading How to iterate over DataFrame rows (and should you?)

The post How to iterate over DataFrame rows (and should you?) appeared first on wrighters.io.



from Planet Python
via read more

BreadcrumbsCollector: Debunking myth “I can’t properly test my project because it uses 3rd party API”

Welcome to the second post from the GRASP series. GRASP stands for General Responsibility Assignment Software Principles. It is a great aid for Object-Oriented Design (but not really exclusive for OOP!). It is all about putting responsibilities in code structures such as classes/methods/modules in such a way it “makes sense”.

The challenge

A couple of days ago I participated in a certain Slack discussion. A developer complained he finds the quality of the project he works with low. Two main factors are fragile codebase (when a seemingly insignificant change in one part breaks some other stuff) and almost no tests. The more senior devs told the developer that they can’t test the app for real because it has integrations with 3rd party APIs.

I cannot be sure whether this is the whole story or actually the most burning problems. However, I can definitely debunk a myth that 3rd party integrations make it impossible to test the logic of one’s application.

Testing the application logic != testing end-to-end

Before we jump into any code or modelling techniques, let’s first clarify what’s possible and what’s not. Obviously, we often won’t be able to automate end-to-end tests that are using the production version of a 3rd party service. In order to do any testing, one has to have the capability to:

  • set a system in the desired state
  • guarantee isolation between tests
  • make calls to the system
  • make assertions about the system’s state or responses
  • (optionally) reset system’s state

External systems are not controlled by us and can be unpredictable at times. The only way to get them in the desired state would be to issue calls just like our application does in production. It can have consequences that require a manual intervention to undo.

For the purpose of this article, let’s consider a flight reservation system.

# Get a list of available flights from a given airport to a given airport, on a given date for two adults
requests.get(".../api/flights?from=JFK&to=LCJ&adults=2date_start=2021-07-01")

# create a booking for a chosen flight etc
requests.post(".../api/booking", json={...})

We could use the production 3rd party service to find a flight, then book it. But even the first step is not as simple as it looks like. Flights change over time, airports get closed etc. Such tests are not deterministic and over time give headache due to maintenance burden. To conclude, 3rd party integration contributes to instability and makes the application more unpredictable.

If we cannot test the application end-to-end, what’s left? Testing the application itself!

The solution – Protected Variations to the rescue!

GRASP’s response to a problem of instability is to create a stable interface around them. This principle is called Protected Variations. Don’t get distracted by the word “interface”. It doesn’t necessarily mean one has to use abstract base classes or create an actual interface if we use another programming language.

Protected Variations only suggest one should write a wrapper around flight service API. It can be a class, a function (if it is just a single entry point) or a module with functions inside. That wrapper or I should rather say interface, has to be stable.

Stable interface

Stability doesn’t stand for immutable code. It rather means that one should do whatever they can to formalize the contract. That involves:

  • using type hints
  • passing DTOs (e.g. dataclasses) as arguments,
  • getting DTOs out
  • use dedicated types (e.g. enums) to be more expressive,
  • avoid leaking information or nomenclature from the API that is not used throughout the project,

Type hints and DTOs are here to enable static code analysis (e.g. mypy). See my other posts about mypy and how it can help. Regarding the implementation of DTOs in Python, here’s an excellent article on the subject: 7 ways to implement DTOs in Python and what to keep in mind

@dataclass
class OneWayFlightsSearch:
    origin: AirportIataCode
    destination: AirportIataCode
    adults: int
    preferred_start: datetime


@dataclass
class FlightSearchResult:
    booking_token: BookingToken
    total_price: Money
    number_of_stops: int
    legs: List[Leg]

Regarding dedicated data types, we can get more expressive (and type-safe!). You can see a few examples in a snippet above – we have a type for price (Money) or airports – AirportIataCode. Theoretically, we could also create a custom type for the number of adults or stops (only positive integers are valid, not just any!).

Our interface accepts and returns these:

class FlightsApi:
    def search_one_way(self, criteria: OneWayFlightsSearch) -> List[FlightSearchResult]:
        ...
        response = requests.get("...")
        ...
        return results  # list of FlightSearchResult

You get the picture of formalizing the contract. One may argue it’s a lot of work and additional code. Well, yes it is – but we are not playing code golf. We are taming the instability with appropriate countermeasures.

Stable interface – benefits

What that stability gives us? Surprisingly plenty.

  • we get a stable point to mock/patch in tests (so we can write acceptance tests of the application! 🎉),
  • we avoid leaking unnecessary details or information we don’t need from a 3rd party,
  • we can focus on modelling application logic.

Note the most important thing here – it’s the application logic that should dictate how input/output DTOs look like and what data we return. Not the 3rd party. If we get back raw strings and our application uses dedicated data types, convert it. If some piece of data is returned from the API but we don’t need it in the application – don’t pack it into DTO.

Other known incarnations of Protected Variations

Adapter Design Pattern

The interface could be seen as an example of Adapter design pattern as described in Design Patterns: Elements of Reusable Object-Oriented Software book. We could move towards referential implementation by introducing an abstract base class. Even without it, the responsibility of our interface is the same – we adapt 3rd party service to the application.

Hexagonal Architecture (AKA Ports & Adapters) or the Clean Architecture

Hexagonal Architecture is an architectural pattern that fosters separating 3rd party inputs and outputs (ports and adapters from the alternative name). A similar approach is promoted by Uncle Bob’s Clean Architecture. It just uses a different name – it is respectively called interface and interface adapter. Umm, did I mention naming building blocks in IT sucks?

Nonetheless, for more information about the Clean Architecture see my first blog post on the subject and 2021 refreshed version.

RDD Stereotypes – Interfacer

Our interface also matches a definition of Interfacer – OOP Stereotype, as understood by Responsiblity-Driven Design:

Interfacer – transforms information and requests between distinct parts of our system

Object Design: Roles, Responsibilities and Collaborations by Rebecca Wirfs-Brock

Testing strategy

Acceptance tests

Now that we have wrapped a source of instability in our application we can write all acceptance scenarios we need. In these tests, we are going to use test-doubles instead of our interface. You can find an introduction to test double types in this article.

Thanks to DTOs and other means of formalizing the contract, we can replace the FlightsApi in tests in a much more reliable way.

Example (simple) scenarios:

  • when FlightsApi returns no results, we display an error message
  • when FlightsApi booking fails we give money back.

Interface tests

While the application logic can (and should) be tested using more blocks, the wrapper will be tested mostly in isolation from the rest of the system. We would rather focus on checking if the interface obeys the contract (e.g. returns expected DTOs, raises proper exceptions classes in special conditions etc).

To help ourselves with testing, we may use responses or VCR.py libraries – they will help us write tests against actual responses from the API that we’ll freeze and reuse. As a result, these tests will be deterministic.

What if 3rd party service changes API?

If your company is merely one of many clients and the API has been published for a long time then the likelihood of a breaking change is rather low. I would not worry too much about that.

However, if the API is e.g. provided by another team in your company, you may look into contract testing – to make sure your applications understand each other.


What would you say for OOP/Design course in Python?

Object-Oriented Design, GRASP, RDD, Design Patterns, Tactical DDD etc. – there are many guidelines on how to design the code and structure projects. Unfortunately, there are not many good resources on that topic for Python. Not to mention a comprehensive learning resource that combines all of them. Blog posts won’t cut it hence I thought of creating a course on the subject. Will that be interesting to you?

If you would like to know when I finish the course, sign up. You won’t get any message from me other than relevant to the course – i.e. when it is released + a discount code for trusting me before even seeing the table of contents.

.mailpoet_hp_email_label{display:none!important;}#mailpoet_form_3 .mailpoet_form { } #mailpoet_form_3 .mailpoet_column_with_background { padding: 10px; } #mailpoet_form_3 .mailpoet_form_column:not(:first-child) { margin-left: 20px; } #mailpoet_form_3 .mailpoet_paragraph { line-height: 20px; margin-bottom: 20px; } #mailpoet_form_3 .mailpoet_segment_label, #mailpoet_form_3 .mailpoet_text_label, #mailpoet_form_3 .mailpoet_textarea_label, #mailpoet_form_3 .mailpoet_select_label, #mailpoet_form_3 .mailpoet_radio_label, #mailpoet_form_3 .mailpoet_checkbox_label, #mailpoet_form_3 .mailpoet_list_label, #mailpoet_form_3 .mailpoet_date_label { display: block; font-weight: normal; } #mailpoet_form_3 .mailpoet_text, #mailpoet_form_3 .mailpoet_textarea, #mailpoet_form_3 .mailpoet_select, #mailpoet_form_3 .mailpoet_date_month, #mailpoet_form_3 .mailpoet_date_day, #mailpoet_form_3 .mailpoet_date_year, #mailpoet_form_3 .mailpoet_date { display: block; } #mailpoet_form_3 .mailpoet_text, #mailpoet_form_3 .mailpoet_textarea { width: 200px; } #mailpoet_form_3 .mailpoet_checkbox { } #mailpoet_form_3 .mailpoet_submit { } #mailpoet_form_3 .mailpoet_divider { } #mailpoet_form_3 .mailpoet_message { } #mailpoet_form_3 .mailpoet_form_loading { width: 30px; text-align: center; line-height: normal; } #mailpoet_form_3 .mailpoet_form_loading > span { width: 5px; height: 5px; background-color: #5b5b5b; }#mailpoet_form_3{border-radius: 0px;text-align: left;}#mailpoet_form_3 form.mailpoet_form {padding: 20px;}#mailpoet_form_3{width: 100%;}#mailpoet_form_3 .mailpoet_message {margin: 0; padding: 0 20px;}#mailpoet_form_3 .mailpoet_paragraph.last {margin-bottom: 0} @media (max-width: 500px) {#mailpoet_form_3 {background-image: none;}} @media (min-width: 500px) {#mailpoet_form_3 .last .mailpoet_paragraph:last-child {margin-bottom: 0}} @media (max-width: 500px) {#mailpoet_form_3 .mailpoet_form_column:last-child .mailpoet_paragraph:last-child {margin-bottom: 0}}

Thanks! Check your inbox or spam folder to confirm signing up


Summary

This was a second article about GRASP which introduced a Protected Variations. The latter is a crucial design principle that helps manage sources of instability and variability in the projects by wrapping them with a stable interface.

It may take a moment to figure out where to exactly draw the line, but it is an investment with great returns. It will work great for projects where 3rd party APIs are used as collaborators for our application. Typical examples are payment providers, some booking services and similar.

Our goal in this design exercise was not to produce something that looks great in a blog post (blogware?!) but rather a practical design that keeps instability at bay. Eventually, as developers, we are to deliver solutions and make sure we can keep doing it over time.

Further reading

The post Debunking myth “I can’t properly test my project because it uses 3rd party API” appeared first on Breadcrumbs Collector.



from Planet Python
via read more

Zero to Mastery: Python Monthly 💻🐍 May 2021

18th issue of Python Monthly! Read by 20,000+ Python developers every month. This monthly Python newsletter is focused on keeping you up to date with the industry and keeping your skills sharp, without wasting your valuable time.

from Planet Python
via read more

PyPy: #pypy IRC moves to Libera.Chat

Following the example of many other FOSS projects, the PyPy team has decided to move its official #pypy IRC channel from Freenode to Libera.Chat: irc.libera.chat/hpy

The core devs will no longer be present on the Freenode channel, so we recommend to join the new channel as soon as possible.

wikimedia.org has a nice guide on how to setup your client to migrate from Freenode to Libera.Chat.



from Planet Python
via read more

Saturday, May 29, 2021

Python Software Foundation: The 2021 Python Language Summit: What Is the stdlib?

Brett Cannon gave a presentation at the 2021 Python Language Summit about the standard library in order to start a conversation about whether it's time to write a PEP that more clearly defines it.

Brett Cannon

 

What Is the stdlib?

He succinctly described the stdlib as "a collection of modules that ship with CPython (usually)." This was the most accurate definition he could give, considering how big it is, how varied its contents are, and how long it has been around.

He didn't offer an answer to the question about whether or not there should be a new informational PEP to define clear goals for the stblib, but he wanted core developers to engage with the question. There are a variety of opinions on the stdlib, but it could be beneficial to come to some kind of agreement about:

  • What it should be
  • How to manage it
  • What it should focus on
  • How to decide what will or will not be added to it

He shared that he semi-regularly sees requests for adding a TOML parser to the stdlib. When he considers requests, he asks himself:

  • Should a module be added?
  • How should such a decision be made?
  • What API should it have?
  • Is there a limit to how big the stdlib should get?

So far, there haven't been basic guidelines for answering these kind of questions. As a result, decisions have been made on a case-by-case basis.

How Big Is the stdlib?

He did some data digging in March of 2021 and shared his findings. Here are the broad strokes:

  • python -v -S -c pass imports 14 modules.
  • The are 208 top-level modules in the standard library.
  • The ratio of modules to people registered to vote in the last Steering Council election is 2.3, but not all of those people are equally available to help maintain the stdlib.

What Should the stdlib Cover?

Some people have suggested that the stdlib should be focused on helping users bootstrap pip and no more. Others have said that it should focus on system administration or other areas. Considering that there are thirty-one thematic groupings in the index, the people who maintain the stdlib don't seem to have come to a collective decision either. The groupings cover everything from networking to GUI libraries to REPLs and more.

The stdlib has been around for a long time, and we need to be careful about breaking people's code, so the goal is not to deprecate what is already there but to consider guidelines for making additions.

How Do We Decide What Goes Into the stdlib?

He compared PEP 603 and graphlib to show how this question has been answered in different ways in the past. The goal of PEP 603 was to add the class frozenmap to the collections module. However, the graphlib module was only ever discussed in an issue and never got a PEP before it was added to the stdlib. There is no standardized approach for making these kinds of decisions, so he would like to know what approaches core developers think would be most appropriate.

What Is the Maintenance Cost?

The PR queue is already long, which can be overwhelming for maintainers and discouraging for contributors.

The following modules aren't used in any of the top 4000 projects:

  • mailcap
  • binhex
  • chunk
  • nis

Seventy-six modules are used in less than 1% of the 4000 most downloaded projects on PyPI. That's over 36% of all the modules in the stdlib. This raises some questions:

  • Do we want to continue to ship these modules?
  • What does this tell us about what the community finds useful in the stdlib?
  • How can that inform future guidelines about what to include in the stdlib?

Based on the data from March 2021, there were:

  • 37 modules with no open PRs
  • 1,451 PRs involving the stdlib, which made up the bulk of all the PRs
The module with the highest number of PRs was asyncio, which had only 50. That's only 3% of all of the open PRs at the time. 
 
The standard library has a significant maintenance cost, but core developers can formulate a plan to get the most out of the maintenance that goes into the stdlib by deciding what it should focus on. They can discuss these issues and work towards resolving them this year.


from Planet Python
via read more

AI Pool: How to freeze tensorflow graph partly?

Couldn't find a way to freeze the TensorFlow graph partly. I just need to freeze a part of the weights of the network....

from Planet Python
via read more

AI Pool: How to convert numbers to one hot vectors?

I want to train a Keras model and I use NumPy to convert numbers to a one-hot vector. why Keras does not provide the implementation inside the training process?...

from Planet Python
via read more

AI Pool: softmax_cross_entropy_with_logits issue with keras

I'm using Keras with TensorFlow backend and using cross-entropy as the loss function. I saw that TensorFlow requires pre softmax as an input for the loss, but I put the output of the softmax in Keras . What is the right way to use it?...

from Planet Python
via read more

AI Pool: Give some suggestions to avoid overfitting

I'm training a neural network that basically does binary classification, but it overfits too fast. After 4-5 epochs it's already in overfitting. What is the reason for it? How to avoid fast overfitting?...

from Planet Python
via read more

AI Pool: Is there a way to visualize Keras model?

I'm designing a neural network model and would like to plot the architecture with weights and shapes. How to do that?...

from Planet Python
via read more

How to freeze tensorflow graph partly?

Couldn't find a way to freeze the TensorFlow graph partly. I just need to freeze a part of the weights of the network....

from Planet SciPy
read more

How to convert numbers to one hot vectors?

I want to train a Keras model and I use NumPy to convert numbers to a one-hot vector. why Keras does not provide the implementation inside the training process?...

from Planet SciPy
read more

softmax_cross_entropy_with_logits issue with keras

I'm using Keras with TensorFlow backend and using cross-entropy as the loss function. I saw that TensorFlow requires pre softmax as an input for the loss, but I put the output of the softmax in Keras . What is the right way to use it?...

from Planet SciPy
read more

Give some suggestions to avoid overfitting

I'm training a neural network that basically does binary classification, but it overfits too fast. After 4-5 epochs it's already in overfitting. What is the reason for it? How to avoid fast overfitting?...

from Planet SciPy
read more

Is there a way to visualize Keras model?

I'm designing a neural network model and would like to plot the architecture with weights and shapes. How to do that?...

from Planet SciPy
read more

Weekly Python StackOverflow Report: (cclxxvii) stackoverflow python report

These are the ten most rated questions at Stack Overflow last week.
Between brackets: [question score / answers count]
Build date: 2021-05-29 18:33:34 GMT


  1. Remove any empty list present in the list - [10/7]
  2. Numpy empty list type inference - [7/2]
  3. ModuleNotFoundError: No module named 'grp' on windows - [6/1]
  4. How to configure fields in Django forms.Form? - [6/1]
  5. Vectorization or efficient way to calculate Longest Increasing subsequence of tuples with Pandas - [6/1]
  6. Python pandas: fast way to flatten JSON into rows by a surrogate key - [6/1]
  7. Convert a dataframe to a list of tuples - [5/4]
  8. How to build a heatmap? - [5/2]
  9. "No message found for this issue" when running pipeline with SonarQube - [5/0]
  10. Is there a way to use the previous calculated row value with the sum of a different column in a Pandas Dataframe? - [4/4]


from Planet Python
via read more

The No Title® Tech Blog: Just updated - both Optimize Images and Optimize Images X

This time, we are releasing both Optimize Images and Optimize Images X at the same time. The original CLI version now uses temporary files with in-memory buffers, which prevents unnecessary I/O, and also displays more detailed and more useful version information. Optimize Images X, the GUI version, is now compatible with Python3.7+ and has the ability to open or preview a selected image.



from Planet Python
via read more

Best MLOps Tools for Your Computer Vision Project Pipeline

The lifecycle of an app or software system (also known as SDLC) has several main stages:  Planning,  Development,  Testing,  Deployment, Then again, back to new releases with features, updates, and/or fixes as needed.  To carry out these processes, software development relies on DevOps to streamline development while continuously delivering new releases and maintaining quality.  The […]

The post Best MLOps Tools for Your Computer Vision Project Pipeline appeared first on neptune.ai.



from Planet SciPy
read more

Friday, May 28, 2021

Python Pool: Learn About Caesar Cipher in Python

Cryptography is the study of the science behind securely transmitting a message from a sender to a receiver. The goal is to prevent a third party from accessing a message. It is achieved by converting the original message into a form that can only be interpreted if one has access to the key. Thus, the key is known only to the sender and the receiver. There are several algorithms in cryptography, but today, we will be looking into caesar cipher in python.

Introduction to Caesar cipher Algorithm

Caesar cipher is one of the oldest and the most commonly known cryptography technique. It is a weak encryption technique for practical implementation but for learning the basics of cryptography. Therefore, it is the best one to get started with. It is based on substitution cipher. Each character is shifted by a specific number of characters, which is the key. Before we dive further into this algorithm, we will understand some basic cryptography terms.

Terms in cryptography

Plaintext: It is the original message which is sent by the sender to the receiver.

Ciphertext: It is obtained when an encryption algorithm has been applied on the plaintext. Basically, it is the scrambled form of the plaintext which cannot be interpreted without the key.

Encryption: It is the technique behind conversion of a plaintext to its ciphertext.

Decryption: It is the technique behind the conversion of the ciphertext to its original plaintext.

Key: It is the value that, when fed to the encryption and decryption algorithm, gives ciphertext and plaintext, respectively.

How does Caesar Cipher work in Python?

The working of the caesar cipher is dependent on the key selected. Each alphabet in the plaintext will be shifted by an amount equal to the value of the key.

For example, if our plaintext is: ‘ABCD’ and the key is 1, then each letter will be replaced by the letter shifted by 1. So, A will be replaced by B, B will be replaced by C, C will be replaced by D, and D will be replaced by E. Thus, the ciphertext obtained would be ‘BCDE.’

caesar cipher python

Had the key size been 3, the ciphertext of the plaintext ‘ABCD’ would be ‘DEFG’.

Caesar Cipher Formula

The formula to convert a given plaintext ‘P’ to ciphertext ‘C’ using key ‘K’ is:

C = ( P + K ) % 26

Similarly, the formula to convert a given ciphertext ‘C’ to plaintext ‘P’ using key ‘K’ is:

P = ( C - K ) % 26

Here, we assign each alphabet a number – A = 0, B = 1, C = 2, D = 3,…,Z = 25. We perform a summation between the number concerning the alphabet and the key value. Then, we perform a modulus operation on that value. For the obtained value, we assign it the alphabet, which is the ciphertext alphabet.

caesar cipher python

Suppose our plaintext was ‘ATTACK’ and the key was 10, then for each letter, the encryption would be:

A : C1 = ( 0 + 10 ) % 26 = 10 % 26 = 10 = K
T : C2 = ( 19 + 10 ) % 26 = 29 % 26 = 3 = D
T : C3 = ( 19 + 10 ) % 26 = 29 % 26 = 3 = D
A : C4 = ( 0 + 10 ) % 26 = 10 % 26 = 10 = K
C : C5 = ( 2 + 10 ) % 26 = 12 % 26 = M
K : C6 = ( 10 + 10 ) % 26 = 20 % 26 = U

Therefore, the obtained ciphertext is : ‘KDDKMU’

Caesar Cipher Using Python

Now, we will be writing the code for implementing the caesar cipher algorithm. We shall be defining two functions – one for encryption and another for decryption. Lets us look at both separately.

Encryption algorithm explaination

To perform encryption, we will be creating a user defined function –

caesar_encryption(): The function will accept two arguments – plaintext and the key-and print the encrypted ciphertext. We shall take the plaintext and the key as the input from the user and pass them into the function.

Inside the function, we have a string named encryption_str of zero length. We have taken a for loop for iterating the plaintext. Inside the for loop, we have taken three if-else conditions. The first one is for handling uppercase letters, the second one for lowercase letters, and the last else case is for handling non-alphabet characters. For checking uppercase and lowercase, we have used isupper(), and islower() functions.

Then we have used the ord() function to obtain the Unicode code point representation of the letter. The uppercase alphabets start from the Unicode value 65 with A = 65, B = 66, etc. Similarly, the lowercase alphabets start from 97 with a = 97, b = 98, etc. We have subtracted 65 and 97 for uppercase and lowercase characters respectively to reduce each alphabet to the A = 0, B = 1, C = 2,…,Z = 25 representation. And then, we have applied the ‘C = ( P + K ) % 26’ formula and added 65 for lowercase and 97 for uppercase for that value to get the Unicode integer value for the obtained ciphertext letter.

Then, we have to use the chr() function, which is used to obtain the alphabet from its Unicode integer value. We have simply concatenated that character with the encryption_str string. If the character is not an alphabet, we would simply concatenate it as it is with the encryption_str string.

def caesar_encryption(plaintext,key):
  encryption_str = ''
  for i in plaintext:
    if i.isupper():
      temp = 65 + ((ord(i) - 65 + key) % 26) 
      encryption_str = encryption_str + chr(temp)                              
    elif i.islower():
      temp = 97 + ((ord(i) - 97 + key) % 26)
      encryption_str = encryption_str + chr(temp)
    else:
      encryption_str = encryption_str + i  

  print("The ciphertext is:",encryption_str)

plaintext = input("Enter the plaintext:")
key = int(input("Enter the key:"))
caesar_encryption(plaintext,key)

The output for the above encryption algorithm is:

Enter the plaintext:attack on the palace!
Enter the key:10
The ciphertext is: kddkmu yx dro zkvkmo!

Decryption algorithm explaination

We are using the same method for performing decryption. We have a user-defined function name caesar_decryption() which takes the ciphertext and the key as the arguments and prints the plaintext. It takes the ciphertext and key as input from the users.

We have a zero-length string named decryption_str, with which we will be concatenating our plaintext. Apart from the formula, the only slight difference here is that for both uppercase and lowercase if statements, we will be checking if the ( C – K ) value is negative or not from the ‘P = ( C – K ) % 26’ formula. If it is negative, then we will add 26 to it before performing modulus. If not, then we will refrain from doing that. Just like the encryption algorithm, the no alphabet characters will be unchanged.

def caesar_decryption(ciphertext,key):
  decryption_str = ''
  for i in ciphertext:
    if i.isupper():
      if ((ord(i) - 65 - key) < 0):
        temp = 65 + ((ord(i) - 65 - key + 26) % 26) 
      else:
        temp = 65 + ((ord(i) - 65 - key) % 26) 
      decryption_str = decryption_str + chr(temp)                              
    elif i.islower():
      if ((ord(i) - 97 - key) < 0):
        temp = 97 + ((ord(i) - 97 - key + 26) % 26) 
      else:
        temp = 97 + ((ord(i) - 97 - key) % 26) 
      decryption_str = decryption_str + chr(temp)
    else:
      decryption_str = decryption_str + i  

  print("The plaintext is:",decryption_str)

ciphertext = input("Enter the ciphertext:")
key = int(input("Enter the key:"))
caesar_decryption(ciphertext,key)

We will be taking the same ciphertext from the encryption algorithm example to check the plaintext. The output will be:

Enter the ciphertext:kddkmu yx dro zkvkmo!
Enter the key:10
The plaintext is: attack on the palace!

FAQ’s

What is the limitation of caesar cipher algorithm?

The limitation of the caesar cipher is that it is prone to brute force attack, meaning that by trying every key combination, the plaintext can be obtained. This is because there are only 26 unique keys possible.


That wraps up caesar cipher with python. Do let us know your views in the comments below.

Till then, Keep Learning!

The post Learn About Caesar Cipher in Python appeared first on Python Pool.



from Planet Python
via read more

Test and Code: 155: Four Questions to Ask Frequently During Software Projects - Tim Ottinger

Tim Ottinger has four questions that work great in many situations, from doing homework, to cooking, to writing code, to entire software projects.

They are actually awesome questions to ask during a software project.

We discuss the questions, where they came from, and look at some uses in software.

The questions:

  1. What is it that needs to be done?
  2. What do we need in order to do it?
  3. Where can we get what we need?
  4. How can we tell if we’re doing it right?

Bonus question that can be swapped out for #1:

  1. What's the most important thing that it doesn't do yet?

Special Guest: Tim Ottinger.

Sponsored By:

Support Test & Code : Python Testing

Links:

<p>Tim Ottinger has four questions that work great in many situations, from doing homework, to cooking, to writing code, to entire software projects.</p> <p>They are actually awesome questions to ask during a software project.</p> <p>We discuss the questions, where they came from, and look at some uses in software.</p> <p>The questions:</p> <ol> <li>What is it that needs to be done?</li> <li>What do we need in order to do it?</li> <li>Where can we get what we need?</li> <li>How can we tell if we’re doing it right?</li> </ol> <p>Bonus question that can be swapped out for #1:</p> <ol> <li>What&#39;s the most important thing that it doesn&#39;t do yet?</li> </ol><p>Special Guest: Tim Ottinger.</p><p>Sponsored By:</p><ul><li><a href="https://ift.tt/2JDHRTz" rel="nofollow">PyCharm Professional</a>: <a href="https://ift.tt/2JDHRTz" rel="nofollow">Try PyCharm Pro for 4 months and learn how PyCharm will save you time.</a> Promo Code: TESTANDCODE21</li><li><a href="https://configcat.com/" rel="nofollow">ConfigCat.com</a>: <a href="https://configcat.com/" rel="nofollow">Release features faster with less risk with ConfigCat. You can try it out with the forever free plan or get 25% off with code testandcode2021</a> Promo Code: testandcode2021</li></ul><p><a href="https://ift.tt/2tzXV5e" rel="payment">Support Test & Code : Python Testing</a></p><p>Links:</p><ul><li><a href="https://ift.tt/3dV48it" title="The Four Questions" rel="nofollow">The Four Questions</a></li></ul>

from Planet Python
via read more

Python Morsels: What is a callable?

Transcript

A callable is an object that you can call.

Functions are callable objects

When you define a function in Python:

>>> def greet(name):
...     print("Hi", name)
...

You'll get a function object:

>>> greet
<function greet at 0x7f61693c5940>

You can call a function object by putting parentheses (()) after it:

>>> greet("Trey")
Hi Trey

So, functions are callables, meaning they're objects that you're able to call.

Is it a function or a class?

Functions are not the only callables in Python.

If we call the built-in enumerate function, we will get back an enumerate object:

>>> colors = ["green", "purple", "white", "pink"]
>>> enumerate(colors)
<enumerate object at 0x7f816c0ad400>

We can loop over that enumerate object in order to see what's in it (related: looping with indexes):

>>> list(enumerate(colors))
[(0, 'green'), (1, 'purple'), (2, 'white'), (3, 'pink')]

Looping is the one thing we can do with an enumerate object.

The reason we get back an enumerate object when we call the enumerate function, is that enumerate isn't actually a function: it's a class!

>>> enumerate
<class 'enumerate'>

We call enumerate a function because we often use the word "function" in a fuzzy way in Python.

In Python we think in terms of duck typing. So if something is a function-like object (meaning it acts like a function) we may simply call it "a function".

The built-in enumerate function acts like a function (you call it using parenthesis) which means it's basically a function. But more properly, enumerate is a callable, meaning it's an object that can be called.

In Python, functions can be called and classes can be called.

Callable class instances

Functions and classes are both callables, but you can actually invent your own callables too.

We have a class here called Person:

class Person:
    def __init__(self, name):
        self.name = name
    def __call__(self):
        print("My name is", self.name)

When we call the Person class:

>>> trey
<__main__.Person object at 0x7fbf9f3331c0>

We'll get back an instance of that class (a Person object):

>>> trey = Person("Trey")

We can also call that Person object by putting parentheses after it:

>>> trey()
My name is Trey

This works because we've implemented a __call__ method on the Person class. Adding a __call__ to a class makes its class instances callable.

Summary

A callable is a function-like object, meaning it's something that behaves like a function. You can put parentheses after a reference to a callable to call it.

Functions are callables and classes are callables. They're not the only callables, but they're the primary two types of callables that you'll see in Python.



from Planet Python
via read more

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...