Thursday, 25 July 2024

Python - Unit I

 Python Topics:

    1.      Difference between C, C++, JAVA & Python

    2.      Python Basics

    3.      Python Versions

    4.      Python features

    5.      Python Applications

    6.      Python character set

    7.      Executing Python

    8.      Python comments

    9.      Python variables

    10.  Python input and output functions

    11.  Python datatypes

    12.  Python basic Programs

    13.  Python Tokens (Identifiers, Keywords, Literals, Operators & Separators)


 

Category of Language

--------------------------

1. Procedure Oriented Language

-it follows some step by step

-it can’t alter steps & can’t add additional steps

Ex:

    COBOL, FORTRAN, BASIC

 

2. Structured Oriented Language

-it follows some step by step

-it can’t alter steps & can add additional steps based on user requirements (extend itself)

-Data access without reference

Ex:

   C

 

3. Object Oriented Language(OOP's)

-it follows some step by step

-it can’t alter steps & can add additional steps based on user requirements (extend itself)

-Data access with reference(object)

Ex:

   C++, JAVA, Python, PHP, Android

 

Types of language

----------------------

1. Low level language (only binary code (0,1))

2. Middle level language (English & binary code (0,1))(Ex : C)

3. High level language (only English) (Ex: java...)

 

C                              C++                              Java                                Python

--------------------------------------------------------------------------------------------------

-Dennis Ritchie      - Bjarne Stroustrup     - James Gosling        - Guido van Rossum

-1972                      - 1980                          - 1990(Oak),1995     -1991

-.c                            -.cpp                            -.java                         -.py

-AT&T Bell, USA   - same                          -sun micro systems -Python Software Foundation

                                                                      (Oracle corp-2010)      

-Structured Oriented - OOP's                  -OOP's                      -OOP's(Multi)

 Middle level language

-Compiler                   - Compiler               -Compiler & interpreter – Interpreter (line by line)

-Console app              - Console app          -window, web, mobile -   window, web

-ASCII                        -ASCII                    -Unicode(UTF)                - Unicode

 

1) Python Basics

     ---------------

* Designed by             : Guido van Rossum, Netherland     

* Developer                : Python Software Foundation

* First appeared          : 1991

* OS                            : Cross-platform

* License                     : Python Software Foundation License & GPL(General Public License)

* Type                         : OSS(Open Source Software) - Free download and use

* Filename extensions: .py, .pyc, .pyd, .pyo (prior to 3.5),.pyw, .pyz (since 3.5)

* Website                    : www.python.org

* Paradigm      : multi-paradigm: (object-oriented, functional (structured oriented), procedural)

* Derived From           : C, C++,ABC, Modula-3,Algol-68,Small Talk & Unix shell

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

2) Python Versions

    -------------------

Python 1.0 - 1994  (1x)

 ...  Python 2.7 - 2010  (2x)

 ...  Python 3.7.0 - Jun 2018  (3x)

... Python 3.12.4 - Jun 2024

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

3) Python Features

     -------------------

1. case sensitive language

 (there is differentiate b/w small and caps)

2. easy to learn & understand, write

3. Portable Language (OS to OS)

4. Interpreted coding (line by line)

5. Many Predefined function (library function or in build function or readymade)

    (already compiled and executable code)

6. user can create an own function

7. Python is Object Oriented Language

8. Python is a OSS

9. multi-paradigm

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

4) Python Applications

  --------------------------

1. Web and Internet Development & Desktop GUI

2. Mathematics & Scientific and Numeric Applications

3. Database Access & Network Programming

4. Games and 3D Graphics & Console-based Applications

5. Applications for Images & Enterprise Applications

6. 3D CAD Applications & Audio – or Video- based Applications

7. Computer Vision (Facilities like face-detection and color-detection)

8. Machine Learning & Robotics & Web Scraping (Harvesting data from websites)

9. Scripting & Artificial Intelligence

10. Data Analysis (The Hottest of Python Applications) *******

11. AI

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

5) Python character set

   ------------------------

1. Alphabets: All capital (A-Z) and small (a-z) alphabets.

2. Digits: All digits 0-9.

3. Special Symbols: Python supports all kind of special symbols like, ” ‘ l ; : ! ~ @ # $ % ^ ` & * ( ) _ + – = { } [ ] \ .

4. White Spaces: White spaces like tab space, blank space, newline, and carriage return.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

6) Execute Python

    -------------------

 -Python has two basic modes

 

1. Interactive Mode (Command Line mode) - execute line by line

2. Script Mode - (File mode)

 

1. Interactive Mode

  ----------------------

-Interactive mode is a command line shell which gives immediate feedback for each statement, while running previously fed

-statements in active memory.

ex:

 >>>a=10

 >>>b=20

 >>>c=a+b

 >>>print(a)

30

-----------------------------------------------

2. Script Mode

  -----------------

-The Script mode is the mode where the scripted and finished .py files are run in the Python interpreter.

Step 1: Click on Start button-->All Programs-->Python 3.6-->IDLE (Python 3.6)

Step 2:

            a=10

            b=20

            c=a+b

            print(a)

Step 3: Save---->Run(F5)

 

Output:

---------

         30

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

7) Python Comments:

     ----------------------

Python supports two types of comments:

1. Single Line Comment

2. Multiple Line Comment

 

1. Single Line Comment - Program title,Author,one line decription

    ------------------------

- In case user wants to specify a single line comment, then comment must start with #

  E.g.:   # This is single line comment.

 

2. Multi Line Comment: - paragram format (decription)

    -------------------------

-Multi lined comment can be given inside triple double quotes (“”” “””) or triple single quotes (‘’’ ‘’’).

 E.g.:    '''   '''   - using Triple Single Quotes

           """   """- using Triple Double Quotes

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 8) Python Variables

    -------------------

- Variable is used to store a value

- Variable also known as identifier.

- In Python, we don't need to specify the type of variable because

  Python is a type infer language and smart enough to get variable type.

- Variables are case sensitive (A and a both are two different variables).

Ex:

  a=10

  b=13.5

  c="jahab"

 

Rules for naming a variable

---------------------------------

1) starts with alphabets

2) don’t start with numbers (but mixed with)

3) don’t start with special char except (_)

4) keywords can’t be used as a variable

5) variables are case sensitive (differentiate between small and caps)

 

#Program: using variable

a=10

b=20.5

c="welcome"

d=2+3j

 

print(a)

print(b)

print(c)

print(d)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

9) Python Input and Output Statements

   ---------------------------------------------

1. Input Function:

    -------------------

 - Getting Data from User

Syntax:

            input ([Prompt])

Ex:

1) num1 = input (‘Enter the input :’)

2) num2 = int (input (‘Enter the input :’))

3) num3 = float (input(‘Enter the input :’))

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

2. Output Function:

    -------------------

- The print() function prints the given object to the standard output device (screen) or

  to the text stream file.

Syntax:

            print()

Ex:

  print("Python is fun.")

  a=15

  b=10

  print(a)

  print(b)

  print("a =", a)

  print("b =",b)

  print('a = ', a ,' b= ', b)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 10) Python Data Types

    ------------------------

Every value in Python has a datatype. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes.

 

1) Text Type:  str

2) Numeric Types:      int, float, complex

3) Sequence Types:     list, tuple, range

4) Mapping Type:       dict

5) Set Types:   set, frozenset

6) Boolean Type:        bool

7) Binary Types:         bytes, bytearray, memoryview

8) None Type: NoneType

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

                             (Example Programs)

                             -------------------------

#Program 1: Display Message

print("Welcome to Python")

 

#Program 2: Display Message

print ("hello welcome to python")

print ('hello welcome to python')

#print 'hello'                   error(in python 3...)

#print "hello welcome"  error(in python 3...)

 

#Program 3: Display Message

a="hai"

b=("welcome")

print (a)

print (b)

 #Program 4: using type keyword

a=10

b=20.5

c="welcome"

d=2+3j

print(type(a))

print(type(b))

print(type(c))

print(type(d))

 #Program 5: using isinstance keyword

a=10

b=20.5

print(isinstance(a,int))

print(isinstance(a,float))

print(isinstance(b,int))

print(isinstance(b,float))

--------------------------------------------

Note:

------

* type() - type() function to know which class a variable or a value

* isinstance()- isinstance() function to check if an object belongs to a particular class.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 6: Add Two Numbers

a=10

b=20

c=a+b

print ("Addition result is : ",c)

print ('Addition result is : ',c)

print ('Addition result is : '+str(c))

 

#Program 7: using different output format in Python

a=10

b=20

c=a+b

print("a :",a," b :",b," c :",c)

print("a : {}, b : {}, c : {}".format(a,b,c))

 

#Program 8: Add Two Numbers

a=10

b="welcome"

#c=a+b    ---error

c=str(a)+b

print(c)

 

#Program 9: Addition of two numbers using input() --Result is concatenation

a=input("Enter First Value :")

b=input("Enter Second Value :")

c=a+b

print("Addition is :",c)

 

#Program 10: Addition of two numbers using input()

a=int(input("Enter First Value :"))

b=int(input("Enter Second Value :"))

c=a+b

print("Addition is :",c)

 

#Program 11: Addition of two numbers using input()

a=input("Enter First Value :")

b=input("Enter Second Value :")

c=int(a)+int(b)

print("Addition is :",c)

 

#Program 12: Arithmetic calculations

a=int(input("Enter First Value :"))

b=int(input("Enter Second Value :"))

add=a+b

sub=a-b

mul=a*b

div=(float)(a)/b

rem=a%b

print ('Addition result is : ',add)

print ('Subtraction is : ',sub)

print ('Multiplication is : ',mul)

print ('Division is : ',div)

print ('Divide is :%0.1f ' %div)

print ('Remainder is : ',rem)

 

#Program 13: Simple Interest Calculation

p=float(input("Enter P:"))

n=float(input("Enter N:"))

r=float(input("Enter R:"))

si=p*n*r/100

print ("Simple ins :",si)

 

#Program 14:  Volume of Cone

r=float(input("Enter r :"))

h=float(input("Enter h :"))

v=(1.0/3.0)*3.14*r*r*h

print ("Cone :",v)

print ("Cone :%0.2f" %v)

 

 

#Program 15:  Using math function

import math

n=int(input("Enter input :"))

x=math.sqrt(n)

y=math.pow(n,2)

pi=math.pi

print (x)

print (y)

print (pi)

 

#Program 16:  Volume of Sphere

import math

r=float(input("Enter r :"))

v=(4.0/3.0)*math.pi*math.pow(r,2)

print ("Sphere :",v)

 

#Program 17: swapping two numbers using third variable

a=10

b=20

print("Before swapping")

print("a :",a,"\t b :",b)

t=a

a=b

b=t

print("After swapping")

print("a :",a,"\t b :",b)

 

#Program 18: swapping two numbers without third variable

a=10

b=20

print("Before swapping")

print("a :",a,"\t b :",b)

a=a+b

b=a-b

a=a-b

print("After swapping")

print("a :",a,"\t b :",b)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

11) Python Tokens

     ------------------

- Tokens can be defined as a punctuator mark, reserved words and each individual word in a statement. Token is the smallest

unit inside the given program.

 

There are following tokens in Python:

 

1. Identifiers.

2. Keywords.

3. Literals or constant.

4. Operators.

5. separators

 

1. Python Identifiers

    ---------------------

- Identifiers are the names given to the fundamental building blocks in a program.

- These can be variables, class, object, functions, lists, dictionaries etc.

 

There are certain rules defined for naming i.e., Identifiers.

---------------------------------------------------------------------

I.  An identifier is a long sequence of characters and numbers.

II. No special character except underscore ( _ ) can be used as an identifier.

III.Keyword should not be used as an identifier name.

IV. Python is case sensitive. So using case is significant.

V.  First character of an identifier can be character, underscore ( _ ) but not digit.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

2. Python Keywords

    ----------------------

- Keywords are special reserved words which convey a special meaning to the compiler/interpreter.

- Each keyword have a special meaning and a specific operation.

 

List of Keywords used in Python are:

------------------------------------------------

True     False    None   and      as

asset    def       class     continue          break

else      finally  elif       del       except

global  for       if          from    import

raise     try        or         return   pass

nonlocal           in         not       is          lambda

--------------------------------------------------

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

3. Python Literals

    ------------------

- Literals can be defined as a data that is given in a variable or constant.

 

Types of Literals

-------------------

i). String Literals

ii). Numeric Literals (Integer, Long, Float, Complex)

iii). Boolean Literals (True or False)

iv). Special Literals (None)

 

i). String Literals

  ------------------

- String literals can be formed by enclosing a text in the quotes.

- We can use both single as well as double quotes for a String.

Eg:

   a="Welcome"

   b='a'

  

2. ii) . Numeric Literals

     ----------------------

- Numeric Literals are immutable.

 

Types of numeri Literals

---------------------

a. Integer

   ex:

         a=100

b. floating point

    ex:

         pi=3.14

c. complex

    ex:

         x=3+2j

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

iii). Boolean literals:

    ---------------------

-A Boolean literal can have any of the two values: True or False.

Ex:

    x=True

    y=False

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

iv). Special literals:

     ------------------

-Python contains one special literal i.e., None.

-None is used to specify to that field that is not created.

-It is also used for end of lists in Python.

Ex:

      x=None

      print(x)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

4. Python Operators

   ----------------------

- Operators are particular symbols that are used to perform operations on operands.

- It returns result that can be used in application.

 

Types of Operators

 ---------------------

-Python supports the following operators

1. Arithmetic Operators : +,-,/,*,%, **(raise to power),//(Floor division)

2. Relational Operators : >,>=,<,<=,==,!=

3. Assignment Operators : =,+=,-=,*=,/=,%=, **=, //=

4. Logical Operators    : and, or, not

5. Membership Operators : in, not in

6. Identity Operators   : is,is not

7. Bitwise Operators    : &,|,^,~,>>,<<

 

5. Separators

----------------

.  --dot

() -- parenthesis

[] - set brackets

{} - braces

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

No comments:

Post a Comment