fbpx

Quick walkthrough of Python for PHP Professionals

Quick walkthrough of Python for PHP Professionals

Python is clean programming language which utilizes the multiple processors of a computer in a best way by its thread based parallelism.It is one of the languages that doesn’t uses semicolon (;) and brackets ({ and }) the way many other languages use. The spacing the structuring for indentation is strictly considered i.e code blocks are defined by their indentation.

I was a PHP guy before and switched to Python recently. And I am absolutely loving it. At first, reading the code was totally awkward for me. Here are a few of the most important concepts we need to understand before starting work on Python or Django.

Concept of Array: Dictionaries & Lists

In PHP program or script, Array is one of the most used data structures and is inconceivable. It uses lists and dictionaries for dealing with array type of data structure. Dictionaries and lists can be contained into each other i.e an element of dictionary can be a list and an element of list can be a dictionary.

There are four collection data types in the Python programming language:

  • List is a collection which is ordered and changeable. Allows duplicate members.
  • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
  • Set is a collection which is unordered and unindexed. No duplicate members.
  • Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.

Lists

A list can be seen as a stack with push and pop. append() does the pushing of item. 

lst = ["easy", "simple", "cheap", "free"]

lst.append(“walk”)

Tuple

thistuple = ("apple", "banana", "cherry")

Almost same as list in terms of accessing and updating value in/out of it.

Dictionaries

Lists are ordered sets of objects, whereas dictionaries are unordered sets. But the main difference is that items in dictionaries are accessed via keys and not via their position. A dictionary is an associative array (also known as hashes). Any key of the dictionary is associated (or mapped) to a value. The values of a dictionary can be any Python data type. So dictionaries are unordered key-value-pairs. A dictionary can be converted to a list and vice versa.

  • Empty dictionary

empty = {}

  • Dictionary as key/value

food = {"abc" : "yes", "def" : "xyz", "uvw" : "no" }

Value can be updated

Food[“abc”] = “no”

  • Mutable or lists/dictionaries themselves can not be used as key

dic = { [1,2,3]:"abc"}

Will throw an error as:

TypeError: list objects are unhashable

  • Tuple as key are ok though

dic = { (1,2,3):"abc", 3.1415:"abc"}

  • A dictionary of dictionary can be made of that dictionary is used as value and give a key to it.

food1 = {"abc" : "yes", "def" : "xyz", "uvw" : "no" }

food2 = {"abc" : "yes", "def" : "xyz", "uvw" : "no" }

dict = {“food1”:food1, “food2”:food2}

  • Operators for dictionaries are
    • len(d)
    • del d[k] – deletes key along with its value
    • k in d – if k is a key in dictionary d
    • k not in d
  • Copying

w = words.copy()

  • Clearning, i.e making it empty

w.clear()

  • Merging: overriding value of same key

w.update(w1)

w and w1 and two different dicts.

  • Iterating over

for key in d:

Creating List from Dictionaries

>>> w={"house":"Haus","cat":"Katze","red":"rot"}
>>> w.items()
[('house', 'Haus'), ('red', 'rot'), ('cat', 'Katze')]
>>> w.keys()
['house', 'red', 'cat']
>>> w.values()
['Haus', 'rot', 'Katze']

Creating Dictionaries from Lists

Given 2 lists:

>>> dishes = ["pizza", "sauerkraut", "paella", "Hamburger"]

>>> countries = ["Italy", "Germany", "Spain", "USA"]

Using zip function:

>>> country_specialities = zip(countries, dishes)
>>> print country_specialities
[('Italy', 'pizza'), ('Germany', 'sauerkraut'), ('Spain', 'paella'), ('USA', 'Hamburger')]
>>> 

dict function now actually converts to pure dict

>>> country_specialities_dict = dict(country_specialities)
>>> print country_specialities_dict
{'Germany': 'sauerkraut', 'Spain': 'paella', 'Italy': 'pizza', 'USA': 'Hamburger'}
>>>

The zip function ignores if any element of one list has extra more element. It just uses the same index element and zips the two lists.

 

Strings

Typecasting

They can be typecast straightly with int(), float() and str() function.

Multiline String

Three single quote or three double quote allows to write string in multiline.

a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''

 

Strings are Arrays

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.

a = "Hello, World!"
print(a[1])

len(), lower(), strip(), replace(), split() are common string operators. 

a = "Hello, World!"
print(a.replace("H", "J"))

split() is equivalent to PHP explode() function and creates a list data type whose value can be accessed through index of it.

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

String concat is done through + operator just like in javascript. Formatting is done with {} placeholder.

age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

Or put index number to be sure with indexing of the position during formatting

quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

 

Classes

  • __init__() is the constructor
class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)
  • Functions of class are called with dot (.) like in javascript

p1.myfunc()

  • The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class. It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class:
class Person:
  def __init__(mysillyobject, name, age):
    mysillyobject.name = name
    mysillyobject.age = age

  def myfunc(abc):
    print("Hello my name is " + abc.name)


p1 = Person("John", 36)
p1.myfunc()

 

  • Use the pass keyword when you do not want to add any other properties or methods to the class. Create a class named Student, which will inherit the properties and methods from the Person class:
class Student(Person):
  pass
  • Each file with .py extension can be treated as module. They can be imported with import method and call.

Save this code in a file named mymodule.py

def greeting(name):
  print("Hello, " + name)

Now in another file

import mymodule
mymodule.greeting("Jonathan")

So it’s quite different than in PHP, where we can include the file with include() function and any variable or function there are directly callable and usable (if defined in global scope).

The variables of a module (obtained after importing) can also be used in the same as the function are used.

  • While importing a module it can be given as alias
import mymodule
mymodule.greeting("Jonathan")
  • Python inbuilt modules are also imported by same import method
  • Only a single function or variable can be imported using from keyword
from mymodule import person1
print (person1["age"])

Here, person1 is actually just a variable of mymodule or mymodule.py file.

  • datetime and json are example of inbuilt modules. Json module has loads and dumps methods which are quite useful while converting json to python object and vice versa. 

Any valid json can be converted into valid dictionary by using json.dumps() method

import json

x = {

  "name": "John",
  "age": 30,
  "married": True,
  "divorced": False,
  "children": ("Ann","Billy"),
  "pets": None,
  "cars": [
    {"model": "BMW 230", "mpg": 27.5},
    {"model": "Ford Edge", "mpg": 24.1}
  ]
}
print(json.dumps(x))

This json.dumps() function also has indent, separator_parameter and sorting feature built in as optional parameters.

  • Python has a built-in package (module) called re, which can be used to work with Regular Expressions.
import re

txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)

The regex expressions are similar to other languages.

  • pip is python package manager that we can use to install all third party modules which are hosted in pip repository.

 

Exceptional Handling

try:
  print(x)

except:
  print("An exception occurred")

The finally block, if specified, will be executed regardless if the try block raises an error or not.

 

try:
  print(x)

except:
  print("Something went wrong")

finally:
  print("The 'try except' is finished")

 

String Formatting with datatype

quantity = 3
itemno = 567
price = 49
myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars."

print(myorder.format(quantity, itemno, price))
  • File handling is similar to PHP with open() function.

DB Connection

  • mysql-connector is the built in python module for connecting with mysql
import mysql.connector

mydb = mysql.connector.connect(

  host="localhost",

  user="yourusername",

  passwd="yourpassword",

  database="mydatabase"

)

mycursor = mydb.cursor()

sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"

val = ("John", "Highway 21")

mycursor.execute(sql, val)

mydb.commit()

print(mycursor.rowcount, "record inserted.")
  • For mongodb, it has built in pymongo module
import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")

mydb = myclient["mydatabase"]

mycol = mydb["customers"]

mydict = { "name": "John", "address": "Highway 37" }

x = mycol.insert_one(mydict)

Note: Examples are taken from www.python-course.eu and https://www.w3schools.com

Summary
Quick walkthrough of Python for PHP Professionals
Article Name
Quick walkthrough of Python for PHP Professionals
Description
Few of the most important concepts we need to understand are: 1. Concept of Array 2. Lists 3. Tuples 4. Dictionaries 5. Strings 6.Classes
Author
Publisher Name
Greencodes
Publisher Logo

Leave a Comment

Related Posts

Enter your keyword