Saturday, 6 January 2018

Python Identity Operators

#!/usr/bin/python3
a = int(input("Enter value for a:"))
b = int(input("Enter value for b:"))
print ('Line 1','a=',a,':',id(a), 'b=',b,':',id(b))
if ( a is b ):
  print ("Line 2 - a and b have same identity")
else:
  print ("Line 2 - a and b do not have same identity")
if ( id(a) == id(b) ):
  print ("Line 3 - a and b have same identity")
else:
  print ("Line 3 - a and b do not have same identity")
b = 30
print ('Line 4','a=',a,':',id(a), 'b=',b,':',id(b))
if ( a is not b ):
  print ("Line 5 - a and b do not have same identity")
else:
  print ("Line 5 - a and b have same identity")

Python Membership Operators

#!/usr/bin/python3
a = int(input("Enter value of a"))
b = int(input("Enter value of b"))
list = [1, 2, 3, 4, 5 ]
if ( a in list ):
  print ("Line 1 - a is available in the given list")
else:
  print ("Line 1 - a is not available in the given list")
if ( b not in list ):
  print ("Line 2 - b is not available in the given list")
else:
  print ("Line 2 - b is available in the given list")
c=b/a
if ( c in list ):
  print ("Line 3 - a is available in the given list")
else:
  print ("Line 3 - a is not available in the given list")


Python Bitwise Operators

#!/usr/bin/python3
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
print ('a=',a,':',bin(a),'b=',b,':',bin(b))
c = 0
c = a & b;
# 12 = 0000 1100
print ("result of AND is ", c,':',bin(c))
c = a | b;
# 61 = 0011 1101
print ("result of OR is ", c,':',bin(c))
c = a ^ b;
# 49 = 0011 0001
print ("result of EXOR is ", c,':',bin(c))
c = ~a;
# -61 = 1100 0011
print ("result of COMPLEMENT is ", c,':',bin(c))
c = a << 2;
# 240 = 1111 0000
print ("result of LEFT SHIFT is ", c,':',bin(c))
c = a >> 2;
# 15 = 0000 1111
print ("result of RIGHT SHIFT is ", c,':',bin(c))

Python Comparison Operators

#!/usr/bin/python3
a = int(input("Enter the value for a:"))
b = int(input("Enter the value for b:"))
if ( a == b ):
  print ("Line 1 - a is equal to b")
else:
  print ("Line 1 - a is not equal to b")
if ( a != b ):
  print ("Line 2 - a is not equal to b")
else:
  print ("Line 2 - a is equal to b")
if ( a < b ):
  print ("Line 3 - a is less than b" )
else:
  print ("Line 3 - a is not less than b")
if ( a > b ):
  print ("Line 4 - a is greater than b")
else:
  print ("Line 4 - a is not greater than b")
a,b=b,a #values of a and b swapped.
if ( a <= b ):
  print ("Line 5 - a is either less than or equal to b")
else:
  print ("Line 5 - a is neither less than nor equal to b")
if ( b >= a ):
  print ("Line 6 - b is either greater than or equal to b")
else:
  print ("Line 6 - b is neither greater than nor equal to b")

Python Arithmetic Operators

#!/usr/bin/python3
a = int(input("Enter the value for a"))
b = int(input("Enter the value for b"))
c = 0
c = a + b
print ("Sum of a and b is ", c)
c = a - b
print ("Substraction of a and b is ", c )
c = a * b
print ("Multiplication of a and b is ", c)
c = a / b
print ("Division of a and b is ", c )
c = a % b
print ("Modulus of a and b is ", c)
c = a**b
print ("Exponent of a and b is ", c)
c = a//b
print ("Floor Division of a and b is ", c)


Standard Data Types in python

Python has five standard data types-
1. Numbers
2. String
3. List
4. Tuple
5. Dictionary

1.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 var1

Python supports three different numerical types −
1. int (signed integers)
2. float (floating point real values)
3. complex (complex numbers)

2.Python Strings
Strings in Python are identified as a contiguous set of characters represented in the quotation marks.

#!/usr/bin/python3
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

3.Python Lists
Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]).

#!/usr/bin/python3
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print (list)                        # Prints complete list
print (list[0])                   # Prints first element of the list
print (list[1:3])                # Prints elements starting from 2nd till 3rd
print (list[2:])                  # Prints elements starting from 3rd element
print (tinylist * 2)           # Prints list two times
print (list + tinylist)       # Prints concatenated lists

This produces the following result-
['abcd', 786, 2.23, 'john', 70.200000000000003]
abcd
[786, 2.23]
[2.23, 'john', 70.200000000000003]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']

4.Python Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parenthesis.

#!/usr/bin/python3
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print (tuple)                     # Prints complete tuple
print (tuple[0])                 # Prints first element of the tuple
print (tuple[1:3])               # Prints elements starting from 2nd till 3rd
print (tuple[2:])                 # Prints elements starting from 3rd element
print (tinytuple * 2)           # Prints tuple two times
print (tuple + tinytuple)    # Prints concatenated tuple

This produces the following result-
('abcd', 786, 2.23, 'john', 70.200000000000003)
abcd
(786, 2.23)
(2.23, 'john', 70.200000000000003)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john')

5.Python Dictionary
Python's dictionaries are kind of hash-table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.

#!/usr/bin/python3
dict = {}
dict['one'] = "This is one"
dict[2]= "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one'])                      # Prints value for 'one' key
print (dict[2])                           # Prints value for 2 key
print (tinydict)                         # Prints complete dictionary
print (tinydict.keys())              # Prints all the keys
print (tinydict.values())           # Prints all the values

This produces the following result-
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']


Multiple Assignment in python3

pno, pname, price = 101, "LUX", 500.50
print(pno)
print(pname)
print(price)
 

Friday, 5 January 2018

Assigning values to the variables in python

 The equal sign (=) is used to assign values to variables

#!/usr/bin/python3
counter = 116                         # An integer assignment
km = 1000.0                           # A floating point
name = "Sateesh Bagadhi"     # A string
print (counter)
print (km)
print (name)


OUTPUT:
116
1000.0
Sateesh Bagadhi




Command Line Arguments

#!/usr/bin/python3
import sys
print ('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument List:', str(sys.argv))

Now run the above script as follows −
$ python test.py arg1 arg2 arg3

This produces the following result-
Number of arguments: 4 arguments.
Argument List: ['test.py', 'arg1', 'arg2', 'arg3']


Multiple Statements on a Single Line

Multiple Statements on a Single Line
The semicolon ( ; ) allows multiple statements on a single line given that no statement starts a new code block. Here is a sample snip using the semicolon-

import sys; x = 'foo'; sys.stdout.write(x + '\n')

Multiple Statement Groups as Suites
Groups of individual statements, which make a single code block are called suites in Python. Compound or complex statements, such as if, while, def, and class require a header line and a suite.
Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by one or more lines which make up the suite. For example

if expression :
suite
elif expression :
suite
else :
suite

Quotation & Comments in Python

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 is the beginning of a comment. All characters after the #, up to the end of the physical line, are part of the comment and the Python interpreter ignores them.

#!/usr/bin/python3

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

First Program

The Python language has many similarities to Perl, C, and Java. However, there are some definite differences between the languages.

Press Alt+ctrl+t to open the terminal and type
gedit welcome.py
in notepad enter the following code:

print "Hello World, Welcome to python";

save and close the file

to run a file in the terminal type  python welcome.py


 for python3 following is the code

print("Hello World, Welcome to python")

to run a file type python3 welcome.py




Lists

Python  Lists Python Collections (Arrays) There are four collection data types in the Python programming language: List  is a ...