• Skip to main content
  • Skip to primary sidebar

CodeBlogMoney

Make Money using Coding and Blogging

Python Interpreter : The Best Language Interpreter

November 29, 2016 by Jimmy

Python is one of the best-interpreted languages and developed by Guido van Rossum in late 1980. Python is used as the first programming choice of Google, Ubuntu, RedHat and other IT product based companies.

The Python interpreter

The Python interpreter is a program which reads Python statements and executes them immediately. To use interpreter it requires opening the command prompt or terminal windows in your development environment and write command python, and it will show this result and start interpreter. I am using Window 10’s Ubuntu shell.

[email protected]:~# python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

Python interpreter executes program statements immediately. To run python statements, Python command prompt will start in interactive mode and it will be very useful to try out things.

Here are some Examples of one-line commands:

[email protected]:~# python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print ("Hello World")
Hello World
>>> 50 * 20
1000
>>> bin(5)
'0b101'
>>>

In above examples, one will print Hello World, other will do multiplication and the third one calculates Decimal to Binary using bin().

The >>> prompt is used to enter one-line commands or code blocks that define classes or functions. Simple one-line commands are there in above example. In next example please find multi-line code blocks.

Here are some Examples of multi-line code block:

[email protected]:~# python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> str1 = "Hello"
>>> str2 = "Hello"
>>> str1 == str2
True

In above example, it will compare two strings.

help() function is another awesome way to get help on python keywords, functions, etc.

Here is the example of checking syntax and guide of bin command. Press q to return to python interactive interpreter.

[email protected]:~# python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> help(bin)

Help on built-in function bin in module __builtin__:

bin(...)
    bin(number) -> string

    Return the binary representation of an integer or long integer.
(END)

I love the way Python Interactive Interpreter works. How about you?

Related Python Articles:

Read JSON File using Python Code and Prompt

JSON Pretty Print using Python- with Examples

Filed Under: Python Tagged With: binary, interpreter, python, windows 10

10 Python Tips and Tricks for Beginner and 9th is interesting

November 28, 2016 by Jimmy

Today Python is one of the most popular languages for coding in Unix/Linux world. You can find it everywhere from Web development to Server Component development, XML parsing to configuration management. Here I will be mentioning 10 Python tips and tricks for developers.

Python is pre-installed in many Operating Systems which released in last two year. Ubuntu, Redhat, Mac OS, Free BSD , Solaris, etc.

To check which version of python is installed go to shell and type:

$ python

This command will give you the version information of Python and start Python’s interactive interpreter.

Here are the few famous applications which are built using Python such as :

  • Youtube
  • OpenStak
  • Dropbox
  • Instagram

Here are 10 Python tips and tricks for Beginners and Experts.

1. Use Python Development Environment

By using Development Environment or IDE it will increase your productivity and easy to resolve error and warning. It will also help to debug the code, easy to navigate , integrate source control such as SVN, Git.

These are the recommended IDEs for Python Development.

  • PyDev – It’s free and Open Source Eclipse-based IDE . http://www.pydev.org/
  • IDLE: The Python built-in IDE, with auto-completion, helps to Format, Run, and Debug python code.
  • Other commercial versions are PyCharm(has Community version), WingIDE.

2. Calculate days between Today and Date.

import datetime

today = datetime.date.today()

someday = datetime.date(2017, 1, 1)

diff = someday - today

print (str(diff.days) +" days")

datetime module is used to find the days between two dates. this example will find the days between today and 1 Jan 2017.

3. Command line arguments while running Python Scripts

#file name is commandlinetest.py
import sys

print 'No of arguments passed:', len(sys.argv)
print 'List of arguments :', str(sys.argv)

run this script:

$ python commandlinetest.py 10 20 30

Output
No of arguments passed: 3
List of argumenrs : ['commandlinetest.py', '10', '20', '30']

sys module will have the information about arguments passed by accessing sys.argv variable. sys.argv is a list of strings representing the arguments on the command-line.

4. String Searching made easy

The first Method will check if a string contains another string by using the in syntax. in takes two arguments, first on the left and second on the right, and returns True if the left argument is contained within the right argument.

s = "This is a String finding program"

# Method 1
if 'String' in s:
    print('String is found in this program')

# Method 2
if s.find('String') != -1:
    print('String is at ' , s.index('String'))

Second Method offers a Library method called find(). This method is used with String Variable and it returns the position of the index of desired string. If the string is not found then -1 is returned.

5. Generating Random Numbers

Python is having the random library for generating random numbers. By default random library uses system time to generate random numbers.

import random

print('Random number:->' , random.randrange(10));

print('Random Range Between 10 to 20:->' , random.randrange(10,20));

print('Random with Floating values:->' , random.uniform(0,10));

Output :
Random number:-> 9
Random Range Between 10 to 20:-> 13
Random with Floating values:-> 5.012076169955613

random.randrange(10) sets the limit from 0 to 10 and return numbers between 0 to 10.

random.randrange(10,20) gives random values between 10 to 20.

random.uniform gives the result with floating value.

6. Opening WebBrowser from Python Script

import webbrowser

webbrowser.open('http://codebeautify.org')

webbrowser module provides the easy way to open system’s default browser with URL mention in open method.

7. Calculate Program Execution time

import time

start_time = time.time()

add = 0
for i in range(1, 10000):
    add =add + i
print(add)

print("\n--- %s seconds ---" % (time.time() - start_time))

Many applications require a very precise time measurement. For this purpose, Python provides methods in time module. These methods will help you to measure execution time taken by the block of code.

In Linux and Unix, this command can let us know the execution of the python program.

$ time python nameofprogram.py

8. Converting the List to a String for Print

#declaring List
mylist = ['one', 'two', 'three']

print (', '.join(mylist))
print ('\n'.join(mylist))

To combine any list of strings into a single string, use the join method of a string object. First print statement will join string with ” , ” and second will add new line.

Output:
one, two, three
one
two
three

9. Strings Concatenating using ” + ” and more.

Python uses + and * from manipulating String.

Using +

$ python
>>> print "Jhon" + "Doe"
JhonDoe

Using *

$python
>>> print "Jhon" * 3
JhonJhonJho

10. Sorting Array of String

mylist = ['one', 'two', 'three', 'four', 'five']

mylist.sort()

for x in mylist:
    print (x);

Output:
five
four
one
three
two

Let me know your views and best Python tips in a comment below.

Filed Under: Python Tagged With: python, String, Tips, Tricks

Validate JSON using Python – with Examples

November 25, 2016 by Jimmy

This article is to Validate JSON using Python. Python has built-in JSON module to work with JSON data. Python is getting popular and becoming the first choice of startup development. JSON is used widely because of it easy to understand, compact and built-in support in JavaScript.

Validate JSON Using Python.

json.loads() method is used to validate JSON data.

Here is the function which will validate JSON data.

#JSON Validator function
import json

def json_validator(data):
    try:
        json.loads(data)
        return True
    except ValueError as error:
        print("invalid json: %s" % error)
        return False

json.loads()

json.loads() loads the JSON data to parse, it will return true or it will fail and raised the exception. This function will work as EAFP (Easier to ask for forgiveness than permission). EAFP is python’s ideology to handle this kind of situation.

Here is the Example of Validating JSON data using Python.

#Validating JSON using Phython Code
import json

def json_validator(data):
    try:
        json.loads(data)
        return True
    except ValueError as error:
        print("invalid json: %s" % error)
        return False

""" 
#Valid JSON Data

{
  "actors": {
    "actor": [
      {
        "id": "1",
        "firstName": "Tom",
        "lastName": "Cruise"
      }
    ]
  }
}

#Invalid JSON Data

 {
    {
    "actor": [
      {
        "id": "1",
        "firstName": "Tom",
        "lastName": "Cruise"
      }
    ]
  }
}
 """


print(json_validator('{"actors":{"actor":[{"id":"1","firstName":"Tom","lastName":"Cruise"}]}}' ))#prints True

print (json_validator('{{"actor":[{"id":"1","firstName":"Tom","lastName":"Cruise"}]}}')) #prints Error message and False

#End

I am using these ready-made tools to validate JSON data online.

https://codebeautify.org/jsonvalidator
https://jsonformatter.org

Are you also working with JavaScript? try this Validate JSON String Using JavaScript.

Filed Under: Python Tagged With: json, json validator, python, validation

Validate JSON String Using PHP

November 23, 2016 by Jimmy

This article is about to validate JSON String using PHP. JSON is the popular data format to transfer data between client and server. There are many JSON validators are available online such as JSON Validator and JSON Validator on CodeBeautify to validate JSON.

As a programmer, I am curious to know how these tools are working. Here I am going to explain.

json_decode() is the function which is been introduce in PHP 5.3 to validate JSON String.

About json_decode

Here is the description is given in PHP specification.

mixed json_decode ( string [, bool = false [, int = 512 [, int = 0 ]]] )

This function takes a JSON encoded the string and converts it into a PHP variable.

Validate JSON String Using PHP

Here is the function which works as JSON Validator.

//JSON Validator function
function json_validator($data=NULL) {

  if (!empty($data)) {

                @json_decode($data);

                return (json_last_error() === JSON_ERROR_NONE);

        }

        return false;
}

Let’s see how does this work.

if (!empty($data))

This condition will check the $data variable is not empty. If $data is empty, then it will return false.

@json_decode($data)

json_decode parses the data and return the PHP variable if the string is valid. If the string is not valid it will generate the error. Character “@” will suppress the error.

return (json_last_error() === JSON_ERROR_NONE);

This will check if $data is valid JSON string by comparing with JSON_ERROR_NONE. json_last_error() return the last error when json_decode() has called if there are any.

Here is the Example of Validating JSON data.

<?php
//JSON Validator function
function json_validator($data=NULL) {

  if (!empty($data)) {

                @json_decode($data);

                return (json_last_error() === JSON_ERROR_NONE);

        }

        return false;
}


//valid JSON Data
/*
 {
  "actors": {
    "actor": [
      {
        "id": "1",
        "firstName": "Tom",
        "lastName": "Cruise"
      }
    ]
  }
}
 */

$sampleJSONData1 = '{"actors":{"actor":[{"id":"1","firstName":"Tom","lastName":"Cruise"}]}}' ;


//invalid JSON Data
/*
 {
    {
    "actor": [
      {
        "id": "1",
        "firstName": "Tom",
        "lastName": "Cruise"
      }
    ]
  }
}
 */

echo "Result for sampleJSONData1: ";
echo (json_validator($sampleJSONData1) ? "JSON is Valid" : "JSON is Not Valid");

echo "</br>";
echo "Result for sampleJSONData2: ";
echo (json_validator($sampleJSONData2) ? "JSON is Valid" : "JSON is Not Valid");

Related Articles:

Validate JSON String using JavaScript

Filed Under: PHP, Problem Solving Tagged With: json, php, Validate, Validate JSON String using php

All about AJAX – From Beginners to Experts – Part 1

January 28, 2015 by Jimmy

Brief History of Web Development

Let’s go 18 years back 1996, We have just started to create web pages, static with text, static with images and wowed the world. The browser was in demand to display web pages which render HTML. Later on, using Perl or C dynamic content has started to serve to a browser. As HTML and Browser evolved, Web becoming interesting, to stream video, playing games, online chatting, pay the bills, find a date and lots of other fun/work activity.

Flash Player was the key part in 2000 to the 2010 year. By using it, Advertiser has started creating animated ads and born of Rich Internet Application. With the use of Adobe Flex technology and instantly became famous. But Flash Player is not supported by Apple on Mobile devices and HTML 5 seems promising.

HTML 5 has gain popularity and started to use to make Richer Internet Application using JavaScript and it’s framework introduced by many giants. i.e JQuery, DOJO, Backbone, Sencha, Angular.

New Trend came and that’s Single Page Application without refreshing the page, render dynamic data like Gmail does. To get data, Browser needs to send the request to the server using JavaScript and that’s called AJAX.

Brief History of AJAX

Microsoft has introduced Internet Explorer to beat Netscape Navigator and got succeed. IE become the world famous browser and introduced many functionalities like ActiveX and Iframe to load asynchronous data. In 1998 IE introduce XMLHTTP for outlook web app. Another browser like Mozilla, Safari has introduced XMLHttpRequest and IE has supported in IE 7.

JavaScript was not widely supported and trusted language in those days. So the world was adopting Adobe Flex to develop Enterprise Rich Internet Application and it grew a lot in 2007-2008. In 2010 Apple wrote a letter regarding supporting flash player in iPhone, IPAD and IOS supported devices and that was not a good news for Adobe for more info click here. From that day the Big company would hesitate to build an application in Flex and search for new approach rises.

Google continued to develop an application in that approach and gave the world Gmail, GMap, Google+, Picasa etc using AJAX and others followed.

What is AJAX?

AJAX stands for Asynchronous JavaScript and XML. AJAX is a technique to send the request and get data asynchronously with the refreshing web page which happens in the traditional application like Wikipedia.

With Ajax, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. – Wikipedia

XMLHttpRequest is used to make a call to server and retrieve the data. It’s an API provided by the browser to support AJAX technology.

This JavaScript code is to make ajax call to server.

function myAjax() {
 var xmlHttp = new XMLHttpRequest();
 var url="serverStuff.php";
 var parameters = "first=barack&last=obama";
 xmlHttp.open("POST", url, true);

 //Black magic paragraph
 xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 xmlHttp.setRequestHeader("Content-length", parameters.length);
 xmlHttp.setRequestHeader("Connection", "close");

 xmlHttp.onreadystatechange = function() {
  if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
   document.getElementById('ajaxDump').innerHTML+=xmlHttp.responseText+"<br />";
  }
 }

 xmlHttp.send(parameters);
} //from stackoverflow

Here is the PHP code.

<?php
 //serverStuff.php
 //from stackoverflow
$lastName= $_POST['last']; $firstName = $_POST['first']; //everything echo'd becomes responseText in the JavaScript echo "Welcome, " . ucwords($firstName).' '.ucwords($lastName); ?>
And here is HTML code.
<!--Just doing some ajax over here... from stackoverflow-->
<a href="#" onclick="myAjax();return false">
Just trying out some Ajax here....</a>
<br />
<br />
<span id="ajaxDump"></span>

This is an example without any framework or library. Just plain JavaScript.

In next blog, it will be in more detail to make a different kind of ajax call with JQuery.

 

Filed Under: JavaScript, jQuery Tagged With: ajax, history, Javascript

  • « Go to Previous Page
  • Go to page 1
  • Interim pages omitted …
  • Go to page 3
  • Go to page 4
  • Go to page 5
  • Go to page 6
  • Go to Next Page »

Primary Sidebar

Categories

  • Blogging
  • HTML
  • Java
  • JavaScript
  • jQuery
  • JSON
  • MySql
  • Performance
  • PHP
  • Problem Solving
  • Python
  • Testing
  • XML

Copyright © 2021 · Metro Pro on Genesis Framework · WordPress · Log in