Python Programming - Python Loops

Python Programming – Python Loops

Python Programming – Python Loops In the previous sections, we have discussed decision-making statements that control the flow either sequentially or skip some statements depending upon the test condition. In some situations such as computing the table of a number, it is required to repeat some set of statements to attain the required results. This repetition can be achieved by using a loop control structure. In this section, we will discuss various loops provided by the Python language. We will demonstrate how loops are supportive and effective in the Python language. Types of loops The repetition of a loop can also be termed as iteration, which means repetitive execution of the same set of instructions for a given number of times or until a particular result is obtained. The repetition of a loop is controlled by a test expression (condition) specified with the loop. The loop begins and continues its execution as long as the test expression evaluates to true. The loop terminates when the conditional expression evaluates to false. After that, the control transfers to the next statement that follows the loop. The Python language supports 2 types of iterative or looping statements while and for as displayed in…

Python Programming - Operators and Expressions

Python Programming – Operators and Expressions

Python Programming – Operators and Expressions Special Operators Python language offers some special type of operators like the identity operator Identity Operator Identity operators compare the memory locations of two objects. They are used to check if two objects, values, or variables are located on the same part of the memory. Two variables that are equal do not imply that they are identical. The identity operators are listed in Table 3.7. Let us assume the value of x=10 and y=20. Operator symbol Name Example Output Description Is is X is y False Evaluates to true if the variables on either side of the operator point to the same object and false otherwise. Is not Is not X is not y True Evaluates to false if the variables on either side of the operator point to the same object and true otherwise. Python Programming – Identity Operators Python Programming – Logical/Boolean Operators Quick Tip: Using Python’s Comparison Operators | Chaining Comparison Operators in Python The Code 3.6. illustrates the use of identity operators. Code: 3.6. Illustration of identity operators # program to illustrate the use of identity operators x1=10 y1=10 x2= ‘Program’ y2= ‘Program’ x3= [1, 2, 3] y3= [1, 2,…

Python Programming - Expressions

Python Programming – Expressions

Python Programming – Expressions Expressions form a basic sentence in any programming language. To construct an expression, we need two basic entities, which are operand and operators. As described above, Python language provides a rich set of operators. Operators in Python language are symbols, which are used to perform not only arithmetic computations such as addition, subtraction, multiplication, or division but also logical computations. The operators specify the type of operation that needs to be applied. The values that are operated on by the operators are called operands. The combination of variables and constants along with Python operators create expressions. In other words, operators take more than one expression or operand to perform arithmetic and logical computations on it. The expressions are evaluated by using the operator precedence rules, which determine the order in which the operators in an expression are evaluated. Python Programming – Expressions Python Programming – Operators Python Programming – Logical/Boolean Operators The precedence and associativity of operators are described in the following sections. Python Operator Precedence The precedence of an operator tells the compiler the order in which the operators should be evaluated. In case two operators with the same precedence are part of an expression,…

How to use the Pexpect Module

How to use the Pexpect Module

This article is based on documentation from The reason I started to use Pexepect was because I was looking for a module that can take care of some of the automation needs I have (mostly with ssh and ftp). You can use other modules such as subprocess, but I find this module easier to use. Note, this post is not for a Python beginner, but hey it’s always fun to learn new things SSH Connection with Python How to use FTP in Python Python Code Examples What is Pexpect? Pexpect is a pure Python module that makes Python a better tool for controlling and automating other programs. Pexpect is basically a pattern matching system. It runs program and watches output. When output matches a given pattern Pexpect can respond as if a human were typing responses. What can Pexpect be used for? Pexpect can be used for automation, testing, and screen scraping. Pexpect can be used for automating interactive console applications such as ssh, ftp, passwd, telnet, etc. It can also be used to control web applications via `lynx`, `w3m`, or some other text-based web browser. Installing Pexpect The latest version of Pexpect can be found here wget http://pexpect.sourceforge.net/pexpect-2.3.tar.gz tar xzf pexpect-2.3.tar.gz…

How to use Fabric in Python

How to use Fabric in Python

What is Fabric? Fabric is a Python library and command-line tool for streamlining the use of SSH for application deployment or systems administration tasks. Typical usage involves creating a Python module containing one or more functions, then executing them via the fab command-line tool. You can execute shell commands over SSH, so you only need to have SSH running on the remote machine. It interacts with the remote machines that you specify as if they were local. Installation Fabric requires Python version 2.5 or 2.6 (Fabric has not yet been tested on Python 3.x) The most common ways of installing Fabric is via, pip, easy_install or via the operating system’s package manager: pip install fabric sudo easy_install fabric sudo apt-get install fabric # (the package is typically called fabric or python-fabric.) Please read the official documentation for more information (dependancies etc..) How to use Pip and PyPI How to use Virtualenv in Python How to use Python virtualenv Fabric Usage On their website they write: “it provides a basic suite of operations for executing local or remote shell commands (normally or via sudo) and uploading/downloading files, as well as auxiliary functionality such as prompting the running user for input, or…

How to use Pillow, a fork of PIL

How to use Pillow, a fork of PIL

Overview In the last post, I was writing about PIL, also known as Python Imaging Library, this library can be used to manipulate images quite easily. PIL hasn’t seen any development since 2009. Therefore, the kind users of this site suggested taking a look at Pillow. This article will tell you how to use Pillow. What is Pillow? Pillow is a fork of PIL (Python Image Library), started and maintained by Alex Clark and Contributors. It was based on the PIL code and then evolved to a better, modern, and more friendly version of PIL. It adds support for opening, manipulating, and saving many different image file formats. A lot of things work the same way as the original PIL. Python – Quick Guide Resize an Image with Python 2.x (and in Batch) Make your life easier with Virtualenvwrapper Download and Installing Pillow Before we start to use the Pillow, we must first download and install it. Pillow is available for Windows, Mac OS X and Linux. The most recent version is “2.2.1” and is supported by python 2.6 and above. To install Pillow on Windows machines you can use easy_install: easy_install Pillow To install Pillow on Linux machines simply…

Using Feedparser in Python

Using Feedparser in Python

Overview In this post we will take a look on how we can download and parse syndicated feeds with Python. The Python module we will use for that is “Feedparser”. The complete documentation can be found here. What is RSS? RSS stands for Rich Site Summary and uses standard web feed formats to publish frequently updated information: blog entries, news headlines, audio, video. An RSS document (called “feed”, “web feed”, or “channel”) includes full or summarized text, and metadata, like publishing date and author’s name. [source] What is Feedparser? Feedparser is a Python library that parses feeds in all known formats, including Atom, RSS, and RDF. It runs on Python 2.4 all the way up to 3.3. [source] RSS Elements Before we install the feedparser module and start to code, let’s take a look at some of the available RSS elements. The most commonly used elements in RSS feeds are “title”, “link”, “description”, “publication date”, and “entry ID”. The less commonnly used elements are “image”, “categories”, “enclosures” and “cloud”. HTML Parser: How to scrape HTML content | Parsing HTML in Python with BeautifulSoup Python Beautiful Soup Example: Yahoo Finance Scraper Beautiful Soup 4 Python Install Feedparser To install feedparser on your…

Using the CSV module in Python

Using the CSV module in Python

If you want to import or export spreadsheets and databases for use in the Python interpreter, you must rely on the CSV module, or Comma Separated Values format. What is a CSV File? CSV files are used to store a large number of variables – or data. They are incredibly simplified spreadsheets – think Excel – only the content is stored in plaintext. And the CSV module is a built-in function that allows Python to parse these types of files. It’s worth noting that when you work with a CSV file, you are dabbling in JSON development. JSON – which stands for JavaScript Object Notation – is a format that is used to store information as JavaScript code in plaintext files. You don’t need to know JavaScript to work with these files, nor is the practice confined to that language. Obviously, since we’re working with Python here. The text inside a CSV file is laid out in rows, and each of those has columns, all separated by commas. Every line in the file is a row in the spreadsheet, while the commas are used to define and separate cells. How to Validate an Email Address Using Python | Check if…

When to Use trycatch Instead of ifelse

When to Use try/catch Instead of if/else

While programming, we have to deal with many constraints which are imposed on variables so that program can be executed in proper way. To enforce the constraints on the variables, we use if else block as well as try catch blocks. In this article we will see how both the constructs work and we will look into the conditions where if-else blocks can be used and where try-except blocks can be used. Python Programming – Decision Making Conditional statements in Python Comment out a block of code in Python Working of if-else If-else blocks are used in python or any other programming language to control the execution of statements in a program based on a conditional statement.If The condition mentioned in the if block is True then the statements written in if block are executed. If the condition evaluates to False, the statements written in else block of the program are executed. If-else block is mainly used for flow control of the program based on the conditions which are known in advance to us. For Example, suppose we are performing a division operation in our program. In this case the variable in the divisor cannot be zero. If the divisor…

How to use For and While Loops in Python

How to use For and While Loops in Python

Why Loops? All programming languages need ways of doing similar things many times, this is called iteration. For Loop The for statement is used to iterate over the elements of a sequence. It’s traditionally used when you have a piece of code which you want to repeat n number of time. The for loop is often distinguished by an explicit loop counter or loop variable. Loops in Python Python Programming – Python Loops Break and Continue Statements For Loop Examples Let’s see how the for loop is working with some examples. for counter in range(1, 6): print counter #can also be written like this: numbers = range(1,6) for count in numbers: print (count) Output >>output 1 2 3 4 5 Loop through words Here we use the for loop to loop through the word computer word = “computer” for letter in word: print letter Output c o m p u t e r While Loop The while loop tells the computer to do something as long as the condition is met. Its construct consists of a block of code and a condition. The condition is evaluated, and if the condition is true, the code within the block is executed. This…