Sunday, August 12, 2018

Python Data Types



Python Programming language has five standard data types and they are as follows:

Numbers
String
List
Tuple
Dictionary

Number

Type
Format
Description
int
n = 10
Signed Integer
long
n = 345L
(L) Long integers, they can also be represented in octal and hexadecimal
float
n = 25.37
(.) Floating point real values
complex
n = 1.14J
(J) Contains integer in the range 0 to 255.

Normally Python converts variable automatically but we can also use Python conversion functions (int(), long(), float(), complex()) to convert data from one type to another. To know the type of a variable, the type () returns information.

String

String is sequence of characters and string variables are created by enclosing characters in quotes. Python uses single quotes (' ) double quotes ( " )and triple quotes (""") to denote literal strings. Triple quoted strings denotes multi line string.

firstName = 'Suddhashil'
lastName = "Chakraborty"
message = """Normally Python converts variable automatically but we can also use Python conversion functions (int(), long(), float(), complex()) to convert data from one type to another. To know the type of a variable, the type () returns information."""

Entire string value can be accessed or we can access a part of the string variable using brackets ‘[]’. Example:

var1 = 'Hello World!'
var2 = 'This is India'

print var1[0] # this will print the first character in the string an `H`
print var2[1:5] # this will print the substring 'his i`( 1 denotes the first index while 5 characters are to be extracted from the string).


List

Lists are a very useful variable type in Python programming language. A list can contain a series of values. List variables are declared by using brackets [ ] following the variable name.

A = [ ] # This is a blank list variable
B = [11, 2, 4, 6] # this list creates an initial list of 4 numbers.
C = [2, 4, 'Suddhashil'] # lists can contain different variable types.

Index of lists in Python starts from 0 and the last index is length of the list. 'len ()' function returns the length / number of elements minus 1 in the list.

mylist = ['A1', 'A2', 'A3', 'A4']
B = len(mylist) # This will return the length of the list which is 3. The index is 0, 1, 2, 3.
print mylist[1] # This will return the value at index 1, which is 'A1'
print mylist[0:2] # This will return the first 3 elements in the list.

Lists can be multiple dimensional. We can declare multiple dimensions by separating an with commas. In the following example, the MyList variable is a two-dimensional list:

MyList = [[], []]
In a two-dimensional list, the first number is always the number of rows; the second number is the number of columns.

Lists are mutable and dynamic.


Tuple

Tuples are almost same as lists but they are fixed in size once they are assigned values. Tuples are immutable and are defined by parenthesis ().

mylist = ('A1', 'A2', 'A3', 'A4')

Main features of Tuples

Tuples have no append or extend method.

Elements cannot be removed from a tuple.

We can find elements in a tuple, since this doesn’t change the tuple.

We can also use the in operator to check if an element exists in the tuple.

Tuples are faster than lists. 

It makes we code safer if we “write-protect” data that does not need to be changed.



Dictionary

Dictionaries in Python are lists of Key - Value pairs where 'key' is always unique value. The main operation of a dictionary is to extract a value based on the key. 

Dictionaries are created by using braces ({}) with pairs separated by a comma (,) and the key and values are associated with a colon(:). 

We can access and modify 'values' in a Dictionary using the 'key'.

dict = {'Suddhashil': 14, 'Satavisha': 21}

dict['Suddhashil'] = 15  # set the value associated with the 'Suddhashil' key to 15

print (dict['Suddhashil']) # print the value of the 'Suddhashil' key - 15.

dict['Dhananjoy'] = 56 # Add a new key 'Dhananjoy' with the associated value - 56

print (dict.keys()) # print out a list of keys in the dictionary

print ('Dhananjoy' in dict) # test to see if 'Dhananjoy' is in the dictionary.  This returns true.

Thursday, August 9, 2018

Print Function in Python Programming language


Among many other functions, 'print ()' function is used in Python Programming language to display values. To concatenate both variables and string, Python uses '+' operator like:
str1="I am "
str2="Indian"
str3=str1 + str2
print(str3) # Output would be 'I am Indian'

Again another example on integer values

x=5
y=10
print(x+y) """ Output would be 15 - numeric addition would be performed first and then print () would display"""

But the following statement will signal error

str1="Age of Suddhashil is:"
x=14
print(str1 + x)

Numeric values and string values can not be used.

'n' is known as new line character in Python and different type values can be separated within print () using comma (,).

x=14
print("Age of Suddhashil is \n", x)

The output will be:
Age of Suddhashil is
14

We can use double quotes or single quotes to denote string but one point to be remembered that they should be used together.

Sunday, August 5, 2018

Variable Declaration in Python Programming Language



Unlike other programming languages, Python do not need explicit variable declaration. Explicit declaration means where variables are to be declared with 'data type' before using. Suppose we need a variable named 'num' in C++ language to store fractional value, then the variable must be declared explicitly using the statement 'flaot num' before using it. 

This is not the case with Python. Python language supports implicit variable declaration where variables are directly assigned values without declaring like 'x=10'. Depending upon the value assigned, type of the variable is set by Python. 

Example: num = 123 # This will create a variable 'num' and assign the value 123 on it.

We can change the type of a already created variable by assigning value of different type like num = 'Suddha' # the `num` variable is now a string type.


Rules and conventions of variable declaration


Like all other programming languages, Python programming language also follows few rules and conventions in variable declaration.

Rules

All variable names must start with alphabet and underscore ( _ ) and numeric value may come afterwards.

Apart from the above three characters, no other characters can be used in variable names.

Variable names are case sensitive in Python

No keywords can be used in variable names in Python programming language

Conventions

Variable names should be meaningful

Python variables are normally written in lower case character

Thursday, August 2, 2018

Python Indentations and Comments


Indentations are not compulsory in other programming languages but in Python indentations are very important. In other programming languages like C, C++ and Java, we prefer indentations as it make the program codes clear to the programmer but it has nothing to do with the program.

Python programming language uses indentation to indicate a block of code.

Example
if a > b:
  statement1
  statement2
  statement3
statement4
Indentations make it clear to Python that statement 1,2 and 3 are within the if block and statement4 is not within the 'if body'.

Python will give an error if we skip the indentation:

Example
if a > b:
statement

In C,C++ and java the 'if body' would be defined as

if (a > b)
{
  statement1
  statement2
  statement3
}
statement4

OR (Without indentation)

if (a > b)
{
statement1
statement2
statement3
}
statement4




Comments in Python

Comments is necessary in all programming languages and Python also uses it's own comment style.

For single line comment, the symbol '#' before the start of the line.

Example


#This is not executable code
print("Hello, World!")

Docstrings in Python

Python uses docstrings (""".........""") to make multiple line comments.

Example


"""This is a
multiline docstring."""
print("Hello, World!")

Sunday, July 29, 2018

Few Words About Python Programming Language



Python is a popular programming language that can be used for:

web development (server-side)
Software development,


Main Features of Python


Python can be used on a server to create web applications.

Python can work with database.

Python uses new lines to denote end of statement.

Indentation is compulsory in Python language to define scope; such as the scope of loops, functions and classes. No curly-brackets are used in Python to mark block. (In C, C++ and Java language, we need to set semicolon at the end of statements and block is necessary in loop, function, decision making statements etc.)


Advantages of Python


Python works on different platforms.

Python uses simple syntax similar to the English language.

Using Python programming language, one can write programs with fewer lines than some other programming languages.

Python is an interpreted programming language.

Program to find the case of a character


In this program, user will enter any character and the program will show whether the entered character is in upper case or in lower case.

The first program is done comparing the ASCII value of the entered character. ASCII values of 'A' to 'Z' are within 65 to 90 and ASCII values of 'a' to 'z' are within 97 to 122.

import java.io.*;
class CaseChecking

{
 BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
char ch;

public void take() throws Exception
{
 System.out.print("\nEnter the character:");
ch=(char)br.read();
if (ch>=65 && ch<=90)
System.out.println("Entered Character is in Upper Case.");
else
System.out.println("Entered Character is in Lower Case.");
}

public static void main(String args[]) throws Exception
{
 CaseChecking ob=new CaseChecking();
ob.take();
}
}

The same program can be done using Character class static methods 'boolean isUpperCase()' or 'boolean isLowerCase()'.


import java.io.*;
class CaseChecking

{
 BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
char ch;

public void take() throws Exception
{
 System.out.print("\nEnter the character:");
ch=(char)br.read();
if (Character.isUpperCase(ch))
System.out.println("Entered Character is in Upper Case.");
else
System.out.println("Entered Character is in Lower Case.");
}

public static void main(String args[]) throws Exception
{
 CaseChecking ob=new CaseChecking();
ob.take();
}
}

Restaurant Bill Producing BlueJ Program with Discount


  import java.io.*;
class Bill
{
 String item[]={"Pasta","Cheese Pizza","Mini Burgers with Cheeze","Corn Dogs","Grilled Chicken","Chrispy Popcorn","Tempura Green Beans","Double Decker Chicken","Pav Bhaji","Samosa"};
 double rate[]={100,102,103,104,105,106,107,108,50,10};
 String order[]=new String[10];
 double amt[]=new double[10];
 String ans;
 int plates[]=new int[10];
 int i,n=0,no,x=0;
 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 Bill()
 {
 
 }

 public void putOrder()throws IOException
 {
     System.out.println("**********************************************");
      System.out.println("St. Paul's Student's Canteen - MENU CARD");
      System.out.println("*********************************************");
      System.out.println("Item No.         Item            Rate/plate");
      for(i=0;i< 10;i++)
      {
                System.out.println((i+1)+ ":                "+item[i]+"------------------"+rate[i]);
      }
            System.out.println("You have to order at least 2 items. Enter item number to place order\n");
       
     while(true)
     {
          if(x==10)
          break;
         System.out.println("Enter item number:");
         no=Integer.parseInt(br.readLine());
         order[x]=item[no-1];
         amt[x]=rate[no-1];
         System.out.println("How many plates?:");
         no=Integer.parseInt(br.readLine());
         plates[x]=no;
         x++;
           System.out.println("Any More Item ?(Y/N):");
        ans=br.readLine().toUpperCase();
             if(ans.equals("N"))
             break;
 }
 showBill();

}
private void showBill() throws IOException
{
double bamt=0,b;
  System.out.println("You have ordered\n");
   System.out.println("Item       Rate         No. of Plates");
  for(i=0;i< x;i++)
  {
       System.out.println((i+1)+":"+order[i]+"---"+amt[i]+"---"+plates[i]);
    }
    while(true)
    {
         if(x<=1)
         break;
         System.out.println("Want to cancell any item (Y/N):");
         ans=br.readLine().toUpperCase();
         if(ans.equals("N"))
         break;
         System.out.println("Which item to cancell, enter item number:");
         no=Integer.parseInt(br.readLine());
         for(i=no-1;i< x;i++)
         {
              order[i]=order[i+1];
              amt[i]=amt[i+1];
              plates[i]=plates[i+1];
            }
            x--;
        }
        System.out.println("Cash Memo\n");
        System.out.println("*****************************************************************");
        System.out.println("Item          No. of plates      Rate           Amount\n");
         System.out.println("***************************************************************");
         for (i=0;i< x;i++)
         {
               System.out.print(order[i]+ "             "+plates[i]+ "              "+ amt[i]+ "                      ");
     
        b=plates[i]*amt[i];
         System.out.println(b);
         bamt=bamt+b;
        }
         System.out.println("Bill Amount Rs.                                     "+bamt);
          System.out.println("*******************");
          if (bamt>=500)
          bamt=bamt-bamt*.125;
          System.out.println("Total Amount after discount @ 12.5% Rs.(if applicable)                   "+bamt);
       
}
public static void main(String args[]) throws Exception
{
Bill ob=new Bill();
 ob.putOrder();
}
}


Variable description of the program




String item[] holds the items in the menu
double rate[] holds the rate of the items of menu card
String order[] it holds the items ordered by any customer
double amt[] it holds the price of items ordered
String ans It takes the choice of customer whether any more order is to be taken
int plates[] it holds the number of plates of each items ordered by customer
int x customer has to order atleast two items, ‘x’ keeps track of the number of items ordered.
int no items are ordered using the item number. ‘no’ holds the item number.
int i loop control variable.
double bamt holds the total bill amount
BufferedReader br It is used to take user input



Saturday, July 28, 2018

Python Language Syllabus for CBSE Class XI-XII


 Introduction to Python

Introduction to Python - an integrated high level language, interactive mode and script mode. Data types –Number (Integer - boolean, decimal, octal, hexadecimal; Floating point; Complex), none, Sequence (String,Tuples, List ) Sets, Mapping.

Mutable and Immutable Variables

Variables, Expressions and Statements: Values, Variables and keywords; Operators and Operands in Python: (Arithmetic, relational and logical operators), operator precedence, Expressions and Statements (Assignment statement); Taking input (using raw_input() and input()) and displaying output (print statement); Putting Comments.

Functions: Importing Modules (entire module or selected objects), invoking built in functions, functions from math module (for example, ceil, floor, fabs, exp, log, log10, pow, sqrt, cos, sin, tan, degrees, radians), using random() and randint() functions of random module to generate random numbers, composition.

Defining functions, invoking functions, passing parameters (default parameter values, keyword arguments), scope of variables, void functions and functions returning values, flow of execution

Conditional constructs and looping: if else statement while, for (range function), break, continue, else, pass, nested if, nested loops, use of compound expression in conditional and looping construct.

 Programming with Python

Strings: Creating, initialising and accessing the elements; string operators: +, *, in, not in, range slice [n:m]; comparing strings using relational operators; String functions & methods: len, capitalize, find, isalnum, isalpha, isdigit, lower, islower, isupper, upper, lstrip, rstrip, isspace, istitile, partition, replace, join, split, count, decode, encode, swapcase, String constants, Regular Expressions and Pattern Matching

Lists: Concept of mutable lists, creating, initializing and accessing the elements, traversing, appending, updating and deleting elements, composition, lists as arguments



List operations: joining, slicing, + , * , in , not in

List functions and methods: len( ), insert( ), append( ), extend( ), sort( ), remove( ), reverse( ), pop( ), list( ), count( ), extend( ), index( ), cmp( ), max( ), min( )

Dictionaries: Concept of key-value pair, creating, initialising and accessing the elements in a dictionary, traversing, appending updating and deleting elements

Dictionary Functions and methods: cmp( ), len( ), clear( ), get( ), has_key( ), items( ), key( ), update( ), values( ), pop( ), fromkeys( ), dict( )

Tuples: Immutable concept, creating, initialising and accessing elements in a tuple, Tuple assignment, Tuple slices, Tuple indexing,

Tuple Functions: cmp(), len(), max(), min(), tuple(), index(), count(), sum(), any(), all(), sorted(), reversed()

Google+ Followers

Subscribe via email

Enter your email address:

Delivered by FeedBurner