Python Strings


Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes.

Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end.

The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator.

For example −

#!/usr/bin/python

str = 'Hello World!'

print str          # Prints complete string
print str[0]       # Prints first character of the string
print str[2:5]     # Prints characters starting from 3rd to 5th
print str[2:]      # Prints string starting from 3rd character
print str * 2      # Prints string two times
print str + "TEST" # Prints concatenated string

This will produce the following result −

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

Python Numbers


Number data types store numeric values. Number objects are created when you assign a value to them.

For example −

var1 = 1
var2 = 10

You can also delete the reference to a number object by using the del statement.

The syntax of the del statement is −

del var1[,var2[,var3[....,varN]]]]

You can delete a single object or multiple objects by using the del statement.

For example −

del var
del var_a, var_b

Python supports four different numerical types −

  • int (signed integers)
  • long (long integers, they can also be represented in octal and hexadecimal)
  • float (floating point real values)
  • complex (complex numbers)

Examples

Here are some examples of numbers −

int long float complex
10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j
-786 0122L -21.9 9.322e-36j
080 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j
-0490 535633629843L -90. -.6545+0J
-0x260 -052318172735L -32.54e100 3e+26J
0x69 -4721885298529L 70.2-E12 4.53e-7j
  • Python allows you to use a lowercase l with long, but it is recommended that you use only an uppercase L to avoid confusion with the number 1. Python displays long integers with an uppercase L.
  • A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x and y are the real numbers and j is the imaginary unit.

Python – Standard Data Types


Python has various standard data types that are used to define the operations possible on them and the storage method for each of them. The data stored in memory can be of many types. For example, a person’s age is stored as a numeric value and his or her address is stored as alphanumeric characters.

Python has five standard data types −

  • Numbers
  • String
  • List
  • Tuple
  • Dictionary

Python Variable Types


Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.

The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable.

For example −

#!/usr/bin/python

distance = 100          # An integer assignment
area     = 1000.0       # A floating point
name     = "Clinton"    # A string

print distance
print area
print name

Here, 100, 1000.0 and “John” are the values assigned to distancearea, and name variables, respectively. This produces the following result −

100
1000.0
Clinton

Multiple Assignment

Python allows you to assign a single value to several variables simultaneously.

For example −

a = b = c = 1

Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables.

For example −

a,b,c = 1,2,"john"

Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object with the value “john” is assigned to the variable c.

Python – Lines and Indentation


Python programing language provides no braces ( like in C++ or Javascript ) to indicate blocks of code. Blocks of code are denoted by line indentation, which is rigidly enforced.

The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount.

For example the below code snippet is correct

if True:
    print "The Value is True"
else:
  print "False"

However, the following block generates an error −

if True:
    print "Answer"
    print "True"
else:
    print "Answer"
  print "False"

Thus, in Python all the continuous lines indented with same number of spaces would form a block. The following example has various statement blocks −

#!/usr/bin/python

import sys

try:
  # open file stream
  file = open(file_name, "w")
except IOError:
  print "There was an error writing to", file_name
  sys.exit()
print "Enter '", file_finish,
print "' When finished"
while file_text != file_finish:
  file_text = raw_input("Enter text: ")
  if file_text == file_finish:
    # close the file
    file.close
    break
  file.write(file_text)
  file.write("\n")
file.close()
file_name = raw_input("Enter filename: ")
if len(file_name) == 0:
  print "Next time please enter something"
  sys.exit()
try:
  file = open(file_name, "r")
except IOError:
  print "There was an error reading file"
  sys.exit()
file_text = file.read()
file.close()
print file_text

Multi-Line Statements

Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. For example −

total = item_one + \
        item_two + \
        item_three

Statements contained within the [] -Lists, {} – Dictionary , or () – Tuples brackets do not need to use the line continuation character. For example −

days = ['Monday', 'Tuesday', 'Wednesday',
        'Thursday', 'Friday']

Quotation in Python

Python accepts single (‘), double (“) and triple (”’ or “””) quotes to denote string literals, as long as the same type of quote starts and ends the string.The triple quotes are used to span the string across multiple lines. For example, all the following are legal −

word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""

Comments in Python

A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them.

#!/usr/bin/python

# First comment
print "Hello, Python!" # second comment

This produces the following result −

Hello, Python!

You can type a comment on the same line after a statement or expression −

name = "Madisetti" # This is again comment

You can comment multiple lines as follows −

# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.

Using Blank Lines

A line containing only whitespace, possibly with a comment, is known as a blank line and Python totally ignores it.

 

Reserved Words (Python)


Python keywords are reserved words that cannot used as constant or variable or any other identifier names.

All the Python keywords contain lowercase letters only. The following are the list of reserved keywords.

and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield

Python Identifiers


An identifier in Python is a name used to identify a variable, function, class, module or other object. It ( identifier ) starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9).

Python does not allow special characters such as @, $, and % within identifiers. Python is a case sensitive programming language. Thus, Hello and hello are two different identifiers in Python.

The following are naming conventions for Python identifiers −

  • Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
  • Starting an identifier with a single leading underscore indicates that the identifier is private.
  • Starting an identifier with two leading underscores indicates a strongly private identifier.
  • If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.

Using Facebook for Business Promotion


This post is designed to make the audience understand how Facebook can be used as a digital marketing tool. In addition, how the large database of information available in Facebook that can be tapped into by your business or organization to generate high quality leads, sales enquiries and traffic to your website or facebook page.

The following are the options for  promoting business through Facebook

Facebook Pages

Facebook pages assist businesses, brands and organizations in sharing information and reaching out to people. Users like the pages that they are interested in. With this, they can stay in touch and get updates about different activities. There are a number of different pages you can create depending on what sort of organization you are starting.

Following is a list of the types of Facebook pages that you can create:

  • Local business or place  
  • Company, organization or institution  
  • Brand or product  
  • Artist, band or public figure  
  • Entertainment  
  • Cause or community

Posts

How can posts be effective to grow your business ?

Facebook is a fantastic way to reach out to your audience on different levels. By posting information, photos, videos and stories, the content you share can:

  • Personalize your brand  
  • Drive users to your blog  
  • Generate more traffic directly to your website
  • Educate and create awareness about your industry  
  • Promote the culture of your organization

Facebook – Ads

There is a lot of flexibility when it comes to choosing the types of ads you want to produce for your Facebook page. This will depend on what you are offering for the campaign and the type of audience you want to promote.

Over the last couple of years, Facebook has spent a great deal of time and effort to adjust the types of ads and offers tailored to suit the needs of business owners and users.

Different types of ads serve the following purpose:

  1. Generate traffic to your website.  
  2. Boost likes and engagement for your page.  
  3. Install and promote your mobile and desktop applications.  
  4. Direct people to your business, e commerce platform or event.

 

Facebook Branding

The actions that you do in a public domain, shapes the way in which people perceive your business. No matter how much we try to ignore the fact, people do judge others around on what they see. They may judge you based on your actions.

The posts that you share, the photos that you upload and the content that you share does affect your branding.

It is always important to create a strategy that is aligned with the way you want to be represented.

 

Facebook — Identifying Targets

Identifying your target audience is important as it helps you narrow down on the people who see your posts to the ones that care the most. When you are using the ad creator,Facebook assists you in breaking down the target audience based on location as well demographics like age, interests, and gender. You will also be able to target your ad based on what people do on the Internet outside of Facebook.

You get full control over the audience you want to reach. Depending on your business needs and the strategy you are currently implementing, you can choose from either one or a combination of the targeting options.

Facebook — Post Frequency

Finding the sweet spot for the amount of posts you should make per week will strongly depend on how your audience is engaging in the content you share. On one hand, if you are publishing one post per week, this will probably be enough to keep the users from recognizing your online presence. But on the other hand, if you publish five posts per day, users will probably find this annoying and this could detract them from staying as a follower.

Experimenting with post frequency can take time. We would recommend you start with approximately 1-3 posts per week and we shall find a sweet sport for your business. You will notice that the likes, comments and shares on your posts will start growing.

Facebook — Likes

Getting likes from the posts that you publish are great, to a certain extent. It is now undeniable that social media is a viable method of marketing and a great way to grow your brand and generate more traffic and income for your business. The great benefit of ‘likes’ on Facebook is that they are quantitative and verifiable means of measuring success of the content you are providing. Likes also lead to insights. These insights provide detailed data on the activity that the fans are making on your site. This can be important for market research. If you have a website, by posting links to different types of items, you can see what kind of products your fan base likes more and can utilize this in your marketing strategy.

Facebook — Create Fans

With over 1.55 billion active Facebook users each month, it is important for your business page to be able to tap into your target market and start growing a ‘Fan Base’. Although this may be a daunting task initially, as the page grows in good content it should also increase in popularity.

Growing a solid fan base is important because:

  • It gives people a reason to trust you.
  • It is an indication of popularity.
  • The more fans you have; the more site traffic you should get.
  • It helps with your SEO strategy.

 

Facebook — Call-to-Action

The main objective of call-to-action button is to bring businesses. You can utilize the call-to-action button to send your fans to any link that you desire. This is a great way for people that visit your page to straight away interact and gain access to your pages primary objective.

You can select from a group of call-to-action buttons depending on what you are looking to do

Following are the main call-to-action buttons:

  • Book Now

This option can be used by service-based businesses for your users to book appointments / Book Table ( Restaurants ) / Offers / Home Delivery

  • Contact Us

It is what it says; you share your business/brand contact details here.Make sure this button is linked to your website’s contact us page.

  • Use App

If you have a mobile app page or mobile app, you can drive users to download the app.

  • Play Game

This option gives the users the ability to play an online game or try a demo. Great when you have a new game and want to show it off.

  • Shop Now

The show now button can be used to direct your fans to an ecommerce store.

  • Sign Up

This is the best option if you are looking to build a database for email,newsletter, etc.

  • Watch Video

With this option you can drive your users to a video. This can be either on your website, Facebook, YouTube or any other online application.

Hello Python !


It’s time to create your first program.

Here we shall use the “print” command to print the line “Hello, Python!”.

Type the following text at the Python prompt and press the Enter:

hello-python

You shall see “Hello, Python !” printed out on to the screen, Congratulations !!! you have now created the worlds simplest python script.

Getting Started with Python IDE


Python comes in two major versions, Python 2 and Python 3. Both are quite different. Here in this website i shall teach you Python 2, at the time of this writing Python 2.7.10 in the latest version. I shall be using Mac to show the samples and vim as the editor for writing the scripts for later on the tutorials. Python comes by default in Mac and almost every flavors  of linux. ( If you are using windows then you need to install python 2.7 )

If  you are on Mac or Linux the just fire up your Terminal and type “python”

python_terminal

after pressing enter you shall be presented with the following screen ( your’s may be a little different )

python-ide