Python Programming

Variables & Operators

Every programming language is focused around data input, data processing and data output. They differ based on their implementation syntax. Python programming syntax encourages human readable code. A new python programmer must go through these syntaxes before including with python programming.

1. Types of data in python

Primitively, python uses five types of data, which are:

1. Numbers
    1.1 int        Eg. -9,0,3 etc.
    1.2 float      Eg. 5.5, 3.56 etc.
    1.3 complex    Eg. 2+i3, 5+i7 etc
2. String         Eg. 'abcd', "123@abc"
3. List           Eg. [2,1,4,1,'A','Python',34.5]
4. Tuple          Eg. (2,1,4,1,'A','Python',34.5)
5. Dictionary     Eg. {'A':'Apple', 1:100}

2. No variable declaration just assignment

x = 1

here the type declaration of variable i.e, int x is not required because python only declares values not variables. Variables are merely reference tags for values.

3. type() function

Since python does not require variable declaration, the reference type of a variable can be determined using type() function

x = 1
<class 'int'>

4. Dynamically typed

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


the variables introduced in python program need not bind to a type immediately, upon interpretation they take the form of the data they refer.

5. Strongly typed

An explicit type conversion is need to change the data from one type to another.

x = "23"
y = int(x)+2

6. Case sensitive

All identifiers and values in python are case sensitive. Change of case results to new reference or object.

x = "hello"
y = "Hello"
x == y

7. Semicolon ';'

It works as line termination. But it is mostly replaced by '\n'

x = 1;
x = 1

Other scenario includes multiple assignment

x = 1; y = 2
x,y = 1,2

8. Interchangible quotations

Python does not have a character type that's why single and double quotes can be used interchangibly but consistently.

x = "Python is cool"
y = 'Python is cool'
x == y

9. Comment

Single comments can be marked by #

x = 10 # This is a comment

Multi-line comment can be marked by three pairs of quotes

We are

10. Multiline definition

'\n' acts as line termination. If an assignment has to continue over multiple lines, we can use '\'

x = 100000000000 + 200000000 +  \
3000000 + 400000

'\' can also be used to turn special characters into raw string.

x = 'I couldn\'t find a better notes'

Multiline string can be defined using three pairs of single or double quotes.

x = ''' we are
all parts of
the same string '''

Collection types like list, tuple and dictionary can simply spread declaration over multiple lines using comma ','.

x = [

11. Indentation

Curly braces '{}' are not used in python for block definition, rather colon ':' and indentation are used.

def function():
    if 10>5:
        print("Body of function")

One tab space is common form of indentation but two or more spaces can consistently be used as well.

12. Control flow

Program control flows left to right over one statement and gradually goes top to bottom in general. But around assignment '=' operator it flows right to left and around nested functions it goes inside out.

x = 10

13. keyword vs function representation

keywords like if, return , del etc does not require '()' in call. While a function call compulsorily requires a '()' suffixed to the name.

if x == 10: pass
print("hello world")

In python 2.7 print was a keyword so the correct syntax is print "hello world"

Whereas in python 3.6 print is a function so the correct syntax is: print("hello world")

14. Nomenclature

Naming things in python below rules and conventions:

  • Rule 1: Variable name should contain only alpha-numeric characters and underscore, i.e, [A-Za-z0-9]
  • Rule 2: Variable name sould begin with only alphabets or underscore, i.e, [^A-Za-z]
  • Rule 3: Variable name should not one of the below keywords

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

To view keywords use

import keyword

  • Varibales should preferably be named in lower cases variable
  • function names must suffix '()' but not keywords myFunction()
  • class names are preferably in title case MyFirstClass

15. import dir(), help()

  • To include a built-in or installed library use import keyword.
  • To find all attributes/function in a library use dir(obj).
  • To find help on any object use help(obj).

Eg. 'math' library has sqrt() function to find square root.

import math


Variables are identifiers for data. It acts as a reference and can refer to only one object at a type. Although, multiple variables can refer to the same object. Without the variable reference the data is garbage collected.

del keyword

It deletes a variable name from the namespace. Syntax: del variable_name


Arithmatic operators

 + - * / // % ** 

// (floor divide) gives quotient in division
% (modulus) gives remainder in division
** exponent

Membership operators

in : It returns True if the operand is present in the sequence, False otherwise.
not in : It returns True if the operand is not present in the sequence, False otherwise.

Logical operators

< > == != >= <=

increment, decrement

+= -=

Operator precendance

* / // %
+ -
In [3]:
x = 2+2*3

y = (2+2)*3
x 8
y 12
In [6]:
# floor division '//'


A tabspace seperating a defintion within a block of code from the cod outside.

In [14]:
class A:
    def function(self):
        for i in "heLLo":
            if i in "aeiou":
                print(i.upper(),end=" ")
                print(i.lower(),end=" ")
            # inside loop
        # outside loop - inside function
    # inside class - outside function
obj = A()
h E l l O 

Scope of variable

Extent of variable definition

In [ ]:
x = 1
def fun():
    x = 2

Basic I/O


In [27]:
x = input("Enter something: ")
print("You entered: ",x)
Enter something: 1234
<class 'str'>
You entered:  1234
In [31]:
x = eval(input("Enter something: "))
print("You entered: ",x)
Enter something: "hello"
<class 'str'>
You entered:  hello
In [34]:
x = int(input("Enter something: "))
print("You entered: ",x)
Enter something: 1234
<class 'int'>
You entered:  1234

Type casting:

Data type conversion
1. Number - int(), float(), complex()
2. String - str()
3. List   - list()
4. Tuple  - tuple()
5. Dictionary - dict()
In [38]:
l = list(input("Enter a list: "))
Enter a list: abc123
['a', 'b', 'c', '1', '2', '3']
In [65]:
# I/O using function definition and call

# l = 10
# l = input()
def addtwo(a,b,c):
    return a+b
x = addtwo(325,32,234)
In [ ]:
# d =  s * t
100 km/h
20 min
In [72]:
def fun(s,t):
    d = s*(t/60)
    return "%.2f" %d

res = fun(100,20)
In [74]:
from math import sqrt
def pytho ( a, b) :
    return sqrt(a**2 + b**2)
x = pytho (3,4)
print (x)
In [ ]:
# 1. Write a program to find the area of square with given side.
In [ ]:
# 2. Write a program to find the square root of a given number.
In [ ]:
# 3. Write a program to print the ascii number for a given character.
In [1]:
# 4. Write a program to convert decimal values into hexadecimal values.
In [ ]:
# 5. Write a program to convert temperature from degree celcius to degree fahrenheite.
In [ ]:
# 6. Write a program to calculate Body Mass Index(BMI).
In [ ]:
# 7. Write a program to find the hypoteneous of a given right angled trianle using Pythagorous Theorem.
In [ ]:
# 8. Write a program to find the velocity of train. using 
In [ ]:
# 9. Write a program to calculate curent using ohm's law.
In [ ]:
# 10. Write a program to find the energy produced by a given object of mass m, using Eienstien Formula E=mc^2
In [ ]:
# 11. Brain Teaser: The redius of a type is 8 inch. How many rotations will the type make to cover 100 kilometers.
In [ ]:
# 12. Print the ascii order of all characters.