How to check if a specific path exists or not by using Python

Each file or folder in the filesystem has a path, a specific one. Python coders deal a lot with paths of files in their computer programming projects, especially when developing software that deals with the utilities of the operating system. Being rich in already builtin features, Python offers many utilities that can help the coder accomplish the tasks they want, without any pain.

One can easily use the os module offered by Python to check if a specific path exists on their operating system or not. The following syntax, shows the usage of the os.path.exists utility.

os.path.exists(path_in_here)

When the os.path.exists Python statement is executed, it returns True or False, depending on the existence of the path which is being checked. It’s usage is very easy, but before one can do that, they have to import the os module first, like shown below.

import os

Once the Python os module is imported, one can easily utilize its resources. Since the purpose of this tutorial is to teach one how to check for the existence of the path of a file in their operating system, I am giving the following practical example to illustrate it.

import os
os.path.exists(‘test’)

When the above statements are executed in the interactive Python shell, False is being returned.

False

Why? Because the path which we are looking for does not exist in the system. With the main purpose of illustrating the usage of the os.path.exists utility when a path exists, I am running the example shown below on my unix based machine.

os.path.exists(‘/usr/local/bin/python’)

When the above Python statement is executed on the Python interactive shell, on my computer, the True value is being returned.

True

This time the True value is being returned, because the path which I am checking for, exists in the operating system.

Final thoughts

Python comes with the builtin tools that can help the coder solve almost any kind of problem. By using the os.path.exists utility, one can check for the existence of a path in their operating system.

Functions in Python, explained in details for complete beginners

One who has mastered the basic Python utilities such as variables, numbers, lists, tuples and dictionaries; should start to learn about functions and their usage, unless they want to remain in the beginner stage and stop progressing with their journey as a Python coder.

Based on my personal experience with the Python programming language so far, a function is the tool which groups a set of code statements together with the main purpose of helping the coder to utilize the same resources more than one in their applications, without repeating themselves.

By using functions not only do Python coders reduce their future work, but they also group code instructions together with the main purpose of developing a specific utility which solves a specific problem. For example, the following function written in Python computer programming language, is specifically developed to find the sum of two numbers and return the result back to the user.

def find_sum(a, b): return a + b

The above Python function takes as input two parameters,a and b. Based on the value of the parameters, it finds their sum and returns it to the user. As you may know, Python supports arithmetic operations by default.

a + b # python arithmetic operation

Why use functions in Python

There are many reasons why Python coders make use of function in their computer programming projects, but the following is the main two.

  • To maximize code reuse
  • To minimize code redundancy

Another obvious reason why those who code computer software make use of functions, is to split their project into small components which make the process of application development really easy and simple to track the code statements under the hood.

Since Python is an object oriented computer programming language, it is always a good idea to bring practical examples with the main purpose of making the theory completely easy to understand for everyone, even to those who have no coding experience at all.

Imagine if someone gave you a project which deals with the wrapping of the ffmpeg multimedia framework. Wouldn’t it make sense to write specific functions for extracting audio, cutting the videos, extracting images?

Based on my personal experience with Python computer programming language, it would make totally sense to split the project into simple components, by using specific functions. The following is a simple architecture I am writing to demonstrate how Python functions help in splitting the project into small utilities.

ffmpeg.extract_audio
ffmpeg.cut_video
ffmpeg.extract_images

In the above block of Python code, the ffmpeg is the module, and the others is the functions; the small components which build the functionalities of the project.

How to declare a function in Python

Python coders declare functions by using the def statement, which means to define a new function. The example shown below, is a practical one.

def new_function():pass

The pass statement is being used to skip the further coding of the function, it can be used in class statements too like shown below.

class A:pass

One can easily write a new function in Python by using the def statement. For a Python function to properly work, it must return something, a value. The Python return statement is being used to exit the function and send back the value to its caller.

def find_sum(a, b, c):return a + b + c

Once a function is being declared with the help of the def statement, a new object is created and assigned to the name of the function. According to the official Python documentation, the function does not exist until the moment the interpreter reaches and runs the def statement where the function is defined.

A Python function can be assigned to a variable, stored in a list and even nested in if statements or while conditional loops.

For example, the following example illustrates how a function can be nested inside a Python if statement.

if execute:find_sum(1, 2, 3)

Time to open the Python interpreter and put some theory about functions in practice. Once you have launched the Python shell, make sure to write the following function.

def display_name(name):pass

The above function does not do anything at the moment, since we just declared it and passed with the Python pass statement.

Try to extend the above function like shown below.

def display_name(name):print(name)

Our function is not ready to be put in work. Although a very simple one, it is good enough to materialize the theory and the concepts we have covered so far.

The Python function display_name takes an input and displays it on the screen, by making use of the builtin function called print.

Run the following and see what happens.

display_name(‘codetheory’)

One can easily assign a function to a variable, and do the call from the variable. A practical example to illustrate such theory is being shown below.

f = display_name
f(‘codetheory’)

The above function does not return anything, it just displays stuff on the console with the help of the builtin Python print statement.

A function can also have arbitrary user-defined attributes, with the main purpose of recording data which can be used later. Take the following example, a simple function which calculates the final price of a product based on the tax.

def calc_price_of_product(price):
tax = 30
final_price = tax + price
return final_price

How to call a function in Python

Once a function is declared, for it to work, it must be called. One can easily call a function in Python by using the following syntax.

my_function()

Notice the brackets in the above call. Based on the declaration of the function, one needs to pass the right number of arguments as an input, before calling it; otherwise they will run into errors thrown by the Python interpreter.

A call of the Python function display_name needs to be done with an argument as an input. Try to call the Python function display_name like shown below and see for yourself what happens in the interactive interpreter.

display_name()

The interpreter will throw the following error, telling the user that they need to run the function with exactly one argument.

Traceback (most recent call last):
File “”, line 1, in
TypeError: display_name() takes exactly 1 argument (0 given)

Final thoughts

Functions make it very easy for the Python developer to write their projects without repeating themselves. Another reason why Python functions make a great utility when it comes to software development, is the fact that they help to split a big project into small components, specific to carry out certain tasks.

Through this article, we went through basic concepts of Python functions, knowledge which everyone should master in order to progress on their journey as Python coders, especially the complete beginners.

Basic Python skills everyone needs to start their coder journey, first part

What is python

Python is a high level computer programming language easy to learn and can be simply put in use by anyone who is passionate about coding. The first time I started reading some python code it felt like i was reading myself, I mean my thoughts converted to code.

Heavily used by Google and Youtube python is becoming very popular among computer programmers all over the world especially in the startup world as it features rapid development making it the swiss army tool for prototyping.

Why learn python

Many of you may ask why learn python and not java or another programming language. This is the right question to ask for a starter in the coding world and I will list some arguments below why one should start learning python as their first computer programming language.

It will take you probably two weeks to learn all the python syntax needed to build real world applications. Or just a few days if you are a passionate reader about these kind of topics.

The fact python is easy to read makes it easy for you as a developer to maintain the code of your project. As the project grows in terms of code you don’t want to come back after your holidays and when looking at the code you have written, not understanding at all how it really works under the hood.

I have had the chance to talk to a python developer who did perl programming for a living back in the days and he told me it is real hard to maintain the code of his old projects. Not hard, but real struggle!

Python is fully Open Source which means that you can look at its implementation code and understand stuff from a lower level perspective.

You can code python on almost any platform. Telling from my experience I have been able to run my python scrips in both Windows and Linux operating systems except for Mac because it is such an expensive toy for me, but for sure you can code python on Mac too.

Python is not just a language. It has a big community behind who is very welcoming and it makes you feel like Home. I am very happy to have met so many python developers in Firenze Italy back in 2013. I felt real love in there.

Some technical knowledge on python

You can notice a python file by the .py extension. Every file that ends with this extension is classified as a python module. For example the following is a python module.

pythongeek.py

The module serves as a container for the python code of our app and we can use the code of a module in other modules by importing it with the import statement like shown below, but do not try to understand this thing right now as this tutorial is just an introduction. I am sure some things may not make sense to you right now and that’s alright.

import pythongeek # imports the pythongeek module

Since python is an intepreted language you will need the official python intepreter to run python code on your machine. In most linux distributions such as Ubuntu it comes installed by default, but in Windows you have to install it yourself.

Having struggled myself with the installation of Python 2.7 on my Windows 7 machine, I decided to write a concise and easy to follow tutorial for everyone on how to download, install and configure Python 2.7.11 on Windows operating system. The tutorial is published on this website, make sure to check it before going any further, especially if you’re using Windows 7 as your main operating system.

Learn and build the basic Python coding skills

Now that you have python available on your machine it is time to build some basic coding skills to build the foundations for further development.

Now that you have a python interpreter in your machine it is time to start some coding. To open the python shell on windows just go to Start and in the search box type python.

Then click on IDLE (Python GUI). The following python graphical shell will come up.

Those who make use of Linux based operating systems, can follow this tutorial too as the python syntax is the same, it does not change per os. So open your terminal, and start to follow.

The above screenshot shows the graphical Python shell supported by Windows machines; for the purpose of this tutorial we are going to use this shell.

Variables

The first thing you need to learn in python is how to declare a variable. You can declare a variable in python like shown below.

a = 5

Where a is the name of the variable and 5 is the value this variable is linked to.

To get the value of the variable you type the name of it and hit Return (Enter) on your keyboard.

python basics

You can also do some maths in Python. The following is a simple arithmetic operation which the Python programming language supports.

a +1

Tuples, Lists, and Dictionaries

Let’s get more pythonic. There are special builtin datatypes in python such as the following:

  • Lists
  • Tuples
  • Dictionaries

There are many others, but for the purpose of this tutorial we will take a look at the ones listed above.

Let’s take a look at lists. For example the following is a list assigned to variable l.

l = [‘python’, ‘geek’, ‘google’, ‘youtube’]

python basics

Lists elements can be accessed and used in a program. For example to access the first element of the list you use the following syntax.

l[0] # where l is the list and 0 is the index of the first element

python basics

So to access the second element you do the following.

l[1]

A list can be updated. For example you can change the first element in our list by doing the following.

l[0] = ‘ruby’

As you can see, when printing the new list the first element is updated.

l

python basics

We will cover lists in more depth in specific tutorials. Now it is time to learn about tuples.

You can define a tuple like shown below.

t = (‘python’, ‘geek’, ‘internet’, ‘skype’)

python basics

The same as in lists you can do indexing in tuples too. For example to get the first element of the above tuple you do the following.

t[0]

python basics

So tuples are like lists? Not really!

Try to update the first element of the tuple we have and see what happens.

t[0] = ‘ruby’

python basics

Let’s move to dictionaries. For example the following is a python dictionary.

d = {‘name’: ‘pythongeek’, ‘occupation’: ‘maths’, ‘age’:13}

python basics

Each item of the dictionary is composed of two elements: a key and a value. For example the first item of our dictionary is composed of the key ‘name’ and the value ‘pythongeek’.

Try the following.

d[‘name’]

python basics

As you can see you access the value of an item in a Python dictionary by its key.

Final thoughts

Before one can code any big application or project in Python, they need to learn and master the basics of this amazing computer programming technology. In the next part, codetheory.in will share more python knowledge one needs in order to progress in their coding journey.

How to install and configure Python 2.7 on Windows 7, so you can execute the scripts from cmd

Python comes already installed in most of the linux based operating systems, probably because they’re mostly being used by heavy computer geeks who is passionate about coding and computer technologies in general. Unfortunately for those who make use of Windows 7, they have to manually download, install and configure Python on their machines completely by themselves.

The beginner who has no idea on how to properly setup Python 2.7 on their Windows 7 computer, is completely left with no official solutions; they have to swim completely alone unless they find a good tutorial on the internet, which explains everything in details so even a complete newbie can understand.

Having struggled myself in the beginning of my journey as a Python coder, I finally decided to write a very concise and easy to follow tutorial for anyone out there who is interested in installing and configuring Python 2.7 on their Windows 7 operating system.

There are many ways one can configure Python programming technology on their Windows machine. The main purpose of this tutorial is to give one the proper instructions on how to install Python 2.7 on Windows 7 so they would be able to execute scripts directly from the Windows command line interface, which is widely known as cmd.

Before going on with the technical instructions, it is truly important for one to learn about environment variables and their purpose on Windows machines.

Windows environment variables

The information about Windows environment variables being shared in here is for complete beginners, for those who have no idea about them. It does not intend at all to cover them in details, but only for the purpose of understanding their important role in configuring Python 2.7 on Windows 7 so one can easily test and run their Python scripts from the command line.

An environment variable in Windows is mainly being used to point to specific paths of executables so the system can directly execute the programs from the command line, without the need of the absolute path. Each program installed on Windows 7, and I do believe in all operating systems available out there, gets placed in specific path, in a specific directory. For the system to keep track of these paths, the environment variables is being used.

One can easily access the environment variables of their Windows 7 machine, by following the instructions being shown below.

System Properties, Advanced, Environment Variables.

Download and install Python 2.7 on your Windows 7 computer

Before proceeding with the download and installation of Python 2.7 on your Windows 7 operating system, it is important to find out the system type. Do you have a 32 bit machine or a 64 bit one? Based on the architecture of your machine, you will download the specific Python 2.7 interpreter.

To find out your system type go to Start, right click on Computer and go to Properties; the following will come up.

As you can see from the above screenshot I have a 64 bit machine. I need to download the python installer for 64 bit system type.

Now go to the python official website and go to Downloads. Under Downloads click on the Windows category.

Depending on the system type you have, you have to download the right version. In the following screenshot everything is self explanatory so take a look at it and click on the python installer for your type.

python installation

Note: The version of python we need is 2.7.11

Download the right version of python for you and move it on Desktop like shown below.

python installation

Then do a right click on the python installer you just moved to Desktop and click on Install. The installation of python will start. The following box will show up.

python installation

If you don’t want to make python available to other users then just select the second option and click Next. I prefer to leave this as default.

The next box will ask you about the path where you want python to be installed. Please leave this as default as you are new to this stuff.

python installation

The C:\Python27\ is the path where our python installation is going to be placed. We will need this path for some configuration so make sure to save it in a notepad file.

C:\Python27\

Then the following will show up. Make sure to click Next.

python installation

Once the above step is completed, the installation of the official Python 2.7.11 interpreter will start on your Windows 7 machine.

python installation

When the setup is close to the finish, just click the Finish button like shown below.

python installation

We are not done yet!

If you go to your Windows 7 cmd and type python in there, like shown below, you will probably get some error, like path not found.

python

The error occurs because the system does not know where to look for the windows executeable named python. It does not exist.

python installation

You have to create it.

Setup python path in Windows 7

So what you need to do in order to execute python program from the command line is to edit the Path environment variable.

First go to My Computer, Properties, Advanced System Settings, Environment Variables. Then find the Path environment variable and click on it; then click Edit.

In the end add the following path.

C:\Python27\

After you have copied the above path and added it in the Path environment variable, click Ok. You will now be able to execute Python 2.7.11 directly from the cmd.

I also have a video in which this article is based. Please make sure to watch it after reading this tutorial, so you can get a better idea on the stuff being explained in here.

My Experience With Newor Media

Where there is code, there is usually some sort of monetization along with it.  For many of us on the web that means digital advertising, which has gotten a bad reputation from pretty much it’s inception.  As you can see, I use ads on this site to help me make a side paycheck now and then.

In the beginning I used AdSense, and there’s nothing wrong with that.  I did it for years, and the return was decent.  I, like many, get a lot of companies trying to places ads on my site, but why not just stick with AdSense?  It’s easy, and you can access to the largest ad marketplace.

Recently, through a mutual friend, I was introduced to a company called Newor Media that basically manages all your ads for you.  Not really a network, but people who are experts in networks and getting good rates.  They guaranteed me that they would beat AdSense, and would provide up to 6 banner ads along with other recommendations to help monetize the site. The only confusing part is that they seem to be private, but if you contact them on the site, they are usually open to new sites.  I was also a little bit hesitant as I was running AdSense for years, so I didn’t want to waste my time trying someone new.

But here is my honest unbiased feedback about working with them. I have been using them for 5-6 months now, so it’s possible something could change later on. But, I want to fully recommend them to anyone reading this. Seriously, it is one of the best decisions I’ve made when it comes to this site. Their online reporting is a bit simple, but shows daily revenue and impressions which is all I really need. I also get the impression that they are actively working on the ads, as they occasionally update me with new partners or suggestions, which is pretty unlike other networks.

I’m making significantly more than AdSense right now, and the quality of the ads is still high in my opinion.  They also have some of the best customer service I’ve ever seen, and if I have a question or need to make a change, they respond back in 10 minutes (usually).  And payments are automatic.

So far I’m very happy. I was never super comfortable with AdSense, only because I know I was probably under monetized a bit.  But the ease of set-up is about the same with Newor Media, and they actually seem to care about improving performance and helping me.  Give them a shot and let me know what your experience is.

10 Best Free Icon Sets for Your Design Projects

If you’re a web developer or designer, chances are there are few things you love more than a good set of freebies. Free graphics are hardly hard to come by, but quality free brackets aren’t quite as common as you might hope. Luckily for you, we’ve curated this versatile list of free icon sets that will add dimension, color, and flair to any of your websites and designs. Keep reading to see if any of these sets might be right for you or one of your projects.

1. Free Shopping Cart Icons

Screen Shot 2017-02-08 at 1.32.25 PM

This collection of shopping related icons is perfect if you’re working on a retail or ecommerce project. The set comes with Add to Cart buttons, shopping cart icons, shopping bag icons, and some small shopping basket graphics. Definitely a good set to have in your arsenal, even if you don’t currently have an ecommerce project going on.

2. Calendar Icons Set

Screen Shot 2017-02-08 at 1.36.55 PM

This icon set features 8 different calendar designs that come as PSDs with organized layers, making it easy to customize dates and colors to reflect the needs of your individual projects.

3. 100 Kitchen Icons

Screen Shot 2017-02-08 at 2.41.09 PM

Perfect for any projects having to do with restaurants or the culinary world. Some of the icons included in this set are ones that you certainly wouldn’t find in a generic or all-purpose collection, including corkscrews, rolling pins, juicers, whisks, and strainers.

4. New York Building Icons Set

Screen Shot 2017-02-08 at 2.50.41 PM

Inspired by the buildings of New York City, most of these simple icons could easily represent buildings or skyscrapers belonging to any urban city. A very professional looking set.

5. Fileicons

Screen Shot 2017-02-08 at 2.58.54 PM

This colorful set of icons that represent various files with different extensions is very useful for any web developer to have on hand. The files come in several different sizes for all of your possible icon needs.

6. One-line Startup Icons

Screen Shot 2017-02-08 at 3.00.12 PM

An icon set inspired by startup (and, dare we say, hipster?) culture. The cool thing about this set (besides the Darth Vader icon), is that they were all drawn using one loopy line, which adds a cool variation to the startup theme.

7. Zen Icons

Screen Shot 2017-02-08 at 3.02.00 PM

With only 12 icons included in this set, the collection isn’t quite as useful or versatile as others on this list. But what it lacks in practicality, it makes up for in beauty. The intricate details are what make these icons unique. Perfect to use in a portfolio site or something similar.

8. Flat Social Icons

Screen Shot 2017-02-08 at 3.06.10 PM

This basic set of flat social media icons is perfect for linking to any social media presence. Colors and shapes are totally customizable.

9. Flat Business Vector Icons

Screen Shot 2017-02-08 at 3.08.06 PM

This set of business-related icons can be used in many different types of projects for professional businesses. As a designer or developer, you can’t go wrong by having these in your personal icon collection.

10. Flat Line Icons

Screen Shot 2017-02-08 at 3.09.59 PM

If you’re looking for a generic, versatile icon set, this is a great option. It includes all the basic icons a developer might need — arrows, play buttons, envelopes, music notes, pencils, etc, all in a simple, modern aesthetic.

10 Essentials For Using Chrome’s Developer Tools

Google Chrome’s Developer tools makes coding so much easier I’m not sure how developers ever lived without it. For those unfamiliar with it, the tool allows developers to edit their code in real time from their live web browser so they can see exactly how any changes they might make to their code would change or impact their sites. Essentially, it saves developers a lot of frustration when it comes to building, editing and maintaining their products. Developer Tools is generally easy to use and pretty intuitive for any developers, but just in case you missed something, here are our top ten tips for using Developer Tools to its full advantage.

1. The search function

Did you know Developer Tools has a search function that will search through a site’s entire source for you? It’s not immediately obvious that this function exists because there isn’t an easily accessible search bar. To use the functionality, you have to hit CMD + OPT + F (or CTRL + SHIFT + F, for you Windows users), and then you’ll be able to search for anything in the source code. This is great for trying to find those pesky HTML tags that get buried in nested code.

2. You can use the console to select elements

If you don’t want to search, you can also find items by selecting them in the console. Simply insert the element (or class or ID name) you’re looking for within the query selector $$() and all instances of that element will appear for you on the console (just like when using jQuery, be sure to place your element, class, or ID names in quotations or the selection won’t work).

3. Pretty Print

This is a cool feature that can be used when viewing the source code that will format any ugly or disorganized code to make it legible for you. You can find the Pretty Print icon (it looks like two brackets: {}) in the bottom left-hand corner of the editor in the source tab.

4. Color Picker

This is my personal favorite Dev Tool feature. When you select an element with any color attribute, you can actually click on the little color square in the CSS panel to access a color picker, where you can change the color of the element using the built in color picker. Not only does it simplify things, but it’s also pretty fun to play around with (you can also change the color from HEX to RGBA (or vice versa) within this color picker panel too — a super useful trick).

Screen Shot 2016-09-25 at 4.21.07 PM

5. Toggle Element State

At the top of CSS panel there’s a button that says :hov, and if you click on it you’ll be able to toggle the element’s pseudo-selectors :hover, :active, :focus, and :visited, so you can see what the elements look like when all those states are activated. This trick seems to be particularly useful because it can be very difficult to edit how an element looks in it’s active state while not actually being able to activate the element (or access that element’s CSS state rules) because you’re using your cursor within Dev Tools.

6. Preserve Log

You’ll find this one particularly useful if you happen to use the console a lot. By checking “Preserve Log” at the top, your console log will be saved so that you can refresh the page without losing any of your data.

7. Device Toolbar

This one is probably pretty well-known, but just on the off chance that someone is new to Dev Tools, it should be known that dev tools offers an awesome way to view sites as they would appear on a mobile device or tablet (there are even several mobile device and tablet templates you can view). Gone are the days of constantly resizing your browser window and crossing your fingers that it looks the same on an iPhone. To activate the device view, click the icon that looks like a phone next to a tablet in the top left hand corner of the Dev Tools editor.

Screen Shot 2016-09-25 at 4.33.51 PM

8. Edit HTML Elements

You can change the name, get rid of, or otherwise edit any HTML element in the elements console simply my double clicking on the element you wish to change. From there, go ahead and make your changes or delete the element as you wish.

9. Adjust the docking position

It seems like most developers prefer to work with the Dev Tools editor anchored to the bottom of their page, but if you like, you can change the position so that it appears anchored to the right hand side (this is actually the default positioning) or so that Dev Tools pops out as its own window. To toggle the docking position, click the vertical three dots next to the ‘x’ on the right hand side of the screen and select the position that works best for you.

Screen Shot 2016-10-16 at 3.27.51 PM

10. Jump to line

You can jump to a particular line within a file in the source tab by pressing CMD + O (CTRL + O for Windows users) to easily access any part of the file without all that scrolling and searching.