HomeGetting started with python

Getting started with python

Python is one of the programming language developed by “Guido van Rossum” in 1991. It is based on ABC language and was inspired by the famous BBC comedy show Monty Python ‘s Flying Circus.

 

Features/Advantages/Characteristics of Python

  1. It is an open source programming language.
  2. It is platform -Independent language i.e can run across different platforms like windows, Unix, Linux etc.
  3. It is easy to understand and has small codes.
  4. It has extensive libraries to solve a task.

Limitation of Python language:-

  1. Type-binding
  2. Slower in execution
  3. Not easily convertible
  4. Weak in mobile computing and Enterprise application like banking and telecom application:-

Different areas where python can be used:-

  1. System software
  2. Web Application
  3. Game development
  4. App Development
  5. Websites Creation
  6. Computer Graphics
  7. Server side programs
  8. AI
  9. Machine learning 10.Big-data

 

In Python there are two modes to write a program:-

Command prompt/Interactive mode/Python shell

Script mode

  1. Command prompt/Interactive mode/Python shell:-
    In this we type the Python code and get the output in the same window.
  2. Script mode:-
    In this mode program can be saved by pressing CTRL+S and output can be seen in other window by running the program by pressing F5 or by clicking on run module.

print( )function in Python:-

It is used to display the message as it is written within the quotes to the output device like screen. For example

print(‘JLDAV SCHOOL’)

print(“My name is Riya”)

print(”’class is xi”’)

Note:- Message can be written using single , double or triple quotes in Python. If it is without quotes then it displays its actual content of

a variable

Newline Character \n:-It is used to add a newline. For example

print(“JLDAV SCHOOL\nMyname is riya”)and output will be

JLDAV SCHOOL

Myname is riya

Tab \t:- It is used to leave blank spaces. For example

print(‘\tJLDAV SCHOOL’)

print(“\tMy name is Riya”)

and in output it will print after leaving blank spaces from left side

JLDAV SCHOOL

My name is Riya

 

To write a program in python language we need to categories into three parts

  1. Input 2. Process 3. Output

For example write a program to add two numbers in python

  1. Input:
    To add two numbers we need two numbers let’s say
    X=5
    Y=7
  1. Process:
    Need to implement the formula and store result in a variable
    Like add=X+Y
  1. Output:
    Display the out using print function. For example
    print(“The sum of two numbers =”,add)Or we can write
    print(add)

Different ways to provide input:-

  1. Within the program
  2. At the time of execution of a program
    For example write a program to find average of three numbers
  1. One way is to provide input within the function
    X=4
    Y=6
    Z=9
    avg=(X+Y+Z)/3
    print(avg)
  2. Another way is to provide input at run time of program
    x=int(input(“Enter the value of x”))
    y= int(input(“Enter the value of y”))
    z= int(input(“Enter the value of x”))
    avg=(X+Y+Z)/3
    print(avg)

Note:- input() function return string type value and we can’t perform calculation on string so we need to convert it into integer using int() function.

If we write
x=input(“Enter the value of x”) // if x=4
y= input(“Enter the value of y”) // if y=5
z=x+y
print(z) //output will be 45 instead of 9 because here + will concat means join the value of x and y

Separator in Python:-
In Python sep separator is used between the values to separate them. By default space
character is used. For example

end separator:-
In Python end separator value is printed after all values are printed. By default end separator is new line character.

For example

Python Fundamental

Basic elements of Python are object, character set ,tokens , expressions, statements, operators and input-output etc.

Object are the core thing that python programs manipulate

Python character set is a set of valid characters recognized by python A character represents any letter, digit or any other symbol.

Letters:- A-Z or a-z Digits:- 0-9

Special symbols:- + – / * // ** = <> ! == “”, ; %#? $ ^ <= >= @ _

Whitespaces:- Tabs(->), enter(🡨), blank space, newline, formfeed Other characters:- All other 256 ASCII and Unicode characters.

Tokens:- can be defined as the smallest individual unit in a program. It is also known as lexical unit. Types of tokens:-

1. Identifiers:-is the name assigned to any variable, function, object, list etc. It can include letters, numbers and underscore character(_).

Rules to define an identifier in python programming:-

  1. It must start with an alphabet or underscore not by any digit.
  2. A keyword of python programming can not be treated as an identifiers. For example we can’t consider for as an identifier because it is a keyword.
  3. An identifier must not contain any special character except for (_) underscore.
  4. Python is case sensitive language so identifier like num and NUM are treated differently.

Some invalid identifiers with reason:-

File-pointers # contains special character(Hyphen-) 1File # contains digit in the beginning

break # contains keyword

Rollno. #contains special character(dot .)

Keywords:-
are words that are already reserved for some particular purpose and are also known as reserved words. For example False, if, for, def, else, elif etc.

Notes:- Keywords should not be used as an identifiers

To view all keywords type the following in script mode or in interactive mode.

>>> import keyword

>>> print(keyword.kwlist)

[‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘async’, ‘await’, ‘break’,

‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’,

‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]

Literals:-
are also known as constant that have fixed value that may be number, text, or other data that is stored in a variable. Different types of constants are:-

  1. Numeric literals:- when digit is used as a constant. For example a=5
  2. String literals:- when alphabetic or alphanumeric information is

enclosed in single, double or triple quotes used as a constant. For example

Name=”neena” or address=”b3A-123”

Sting types in Python:- There are two string types in Python.

    1. Single line string:- is a string that must terminate in one line.
      For example

      1. Multiline string:- is a string that contains multiple lines as one single string by putting a backslash in the end before pressing enter key. For example>>> print(“hello\

        hello how are you

        >>> print(“hello\ how are you\

        i am good”)

        hello how are you i am good

        Note:- When multiline string is enclosed within triple quotation marks then no backslash is required at the end of line. For example

        >>> str=”””hello how

        are you”””

        >>> str =’hello\nhow\nare you’

        >>> print(str) hello

        how are you

      2. Escape sequence:- are special characters that you can use along with backslashFew examples are print(“hello \n how are you”); hellohow are you>>> print(“hello \t how are you”); hello how are you>>> print(“hello \’ how are you”); hello ‘ how are you>>> print(‘hello \” how are you’); hello ” how are you>>> print(“hello \b how are you”); hello how are youOperators:-
        are used to performs some specific operation on operands.The various Python operators are:-

        1. Arithmetic Operators:-are used to perform some mathematical computation.
          If x=4 and y=2

        2. Relational /comparison Operators:- are those that performs comparison among operands. It returns either true or false based on the condition.
          Relational operators are:- If a=4 and b=2

          1. Identify operators:- They are usually used to determine the type of data a certain variable contains.The two identity operators used in Python are (is, is not).

            1. Operator is – Evaluates to true if the variables on either side of the operator point to the same object and false otherwise.
          2. For example

Output will be true

  1. Operator ‘is not’ – Evaluates to false if the variables on either side of the operator point to the same object and true otherwise.

For example

4.Membership operators are operators used to validate the membership of a value. It test for membership in a sequence, such as strings, lists, or tuples.

      1. in operator : The ‘in’ operator is used to check if a value exists in a sequence or not. Evaluates to true if it finds a variable in the specified sequence and false otherwise.

# Python program to illustrate # Finding common member in list # using ‘in’ operator list1=[1,2,3,4,5]

list2=[6,7,8,9]

for item in list1:

if item in list2: print(“overlapping”)

else:

print(“not overlapping”)

Output:

not overlapping

‘not in’ operator- Evaluates to true if it does not finds a variable in the specified sequence and false otherwise.

# Python program to illustrate # not ‘in’ operator

x = 24

list = [10, 20, 30, 40, 50 ];

if ( x not in list ):

print(“x is NOT present in given list”) else:

print(“x is present in given list”)

Punctuators:-is a token. Most commonly used punctuators in Python are:

‘ “ # \ () {} [] @ , : . =

Expressions:- A sequence of operands and operators, like x+y -7 , is called

an expression. Python supports many operators for combining data objects into expressions.

Statements:- Programming Instructions that a Python interpreter can execute are called statements. For example, x= 5 is an assignment statement. if statement, for statement, while statement, etc.

Comments:- is also known as remarks. It is non executable. It is used to increase the clarity of a program.

There are two types of comments:-

        1. Single line comments:- It begin with symbol #(hash). For example

#This program calculate sum of two numbers # a is number1

# b is number2

        1. Multi-line comments:- are used when we want to make multiple lines as comment. This can be done
          1. By typing # symbol in the beginning of every line. For example

# p stands for principle #r stands for rate

# t stands for time Or

          1. By typing ‘’’ triple quotes in the beginning and at the last. This type of multi-line comments are also known as docstring. For example

‘’’ p stands for principle

r stands for rate

t stands for time’’’

Functions:- A function is a block of code that has a name which only runs when it is called.

def sum():

:

:

sum()

Variables:- is a named location that is used to store some value. For example to store marks of a student

Marks=45

Where Marks is a variable having value 45

If we take a variable x=8 and check its memory address by using id fn is 1912449056 then again if we change the value of x=6 and check its memory address which is 1912449056 that means In python we change value in a variable it stored in different memory location i.e variables in python do not have fixed locations unlike in other programming languages like in c, c++etc.

Lvalue:-variable name is known as lvalue that can come left hand side as well as right hand side of an assignment. For example

X=4

Y=2 Z=X+Y

Here X,Y,Z are Lvalue

Rvalue: The value which is stored in a variable is known as Rvalue. It can come right hand side only. For example

X=4

Here 4 is a Rvalue. If we write 4=x it will be wrong.

Multiple assignments:-Python provides different ways to assign values to variables. These are:-

  1. Same value to multiple variables:-In Python same value can be assigned to multiple variables in a single statement. For example to assign 10 to three variables x,y and z we write x=y=z=10
  2. Different values to multiple variables:- In Python different values can be assigned to multiple variables in a single statement. For example to assign 5,6,7 to variables x,y and z order wise. we write

x=y=z=5,6,7

Note:- Until some value is not assigned to a variable it is not created. Printing a variable without assigning a value will results into an error.

Dynamic typing:- A variable having value of certain type

Can be made to assign different type of value. This is called Dynamic typing. For example if we write

X=56

Then we write X=45.6

That means earlier we assigned integer value in X then we assigned float value in X ,so in python language it is not going to generate any error like in c and c++ because in python programming X contains different memory location for both values unlike c ,c++ etc which support static typing i.e data type of a variable can not be changed.

Components of the variable:-

  1. Type of the variable:- To find what type of value stored in a variable type() method is used in python programming. For example

>>> x=30 # value of x is of integer type

>>> type(x)

<class ‘int’> # type(x) will return int value

>>> x=34.5 # value of x is of float type

>>> type(x)

<class ‘float’> # type(x) will float type value

  1. Identity of the variable:-To find the memory address of a variable id() method is used in python programming. For example

>>> x=30

>>> id(x)

1954785664 # memory address of x

>>> x=45.5

>>> id(x) # memory address of x 56405248

  1. Value of the variable:- To display value stored in a variable print() method is used. For example

>>> x=30

>>> print(x) 30

>>> x # In command prompt if we write only the name of a

30 # variable we get its value

Data types in python:- Data types available in Python are:-

  1. Number which is of types:-

    1. Integer(int):-It represents whole numbers that may be positive and negative. For example 34,-3 etc
    2. Floating numbers(float):- It represents number with decimals. For example 45.5, -35.5 etc
    3. Complex numbers:-which consists of real and imaginary numbers. For example

>>> x=3+5j

>>> x.real 3.0

>>> x.imag 5.0

  1. string(str):- A string is a sequence that may consists of alphabets or alphanumeric characters and enclosed within

single,double or triple quotes(‘, “ , ‘’’). For example

>>> str=”Hello how are you”

>>> str1=”address id:- b2b-345, Janakpuri”

>>> print(str) Hello how are you

>>> print(str1)

address id:- b2b-345, Janakpuri

  1. Boolean(bool):-It represents two possible values i.e true or false. For example

>>> x,y=4,5

>>> print(x>y) False

>>> print(x<y) True

  1. None:-It is used to represent the absence of value. For example

>>> p=10

>>> q=None

>>> p 10

>>> q

>>>

Type Conversion

To convert one datatype into another datatype.

There are two ways to perform conversion:-

Implicit conversion:- When type conversion done automatically by python . Implicit conversion, also known as coercion For example

A=45.5

B=35

C=A+B // Will automatically convert addition of int and float into float

print(C)

OUTPUT

80.5

Explicit Conversion:- When conversion done by the user as per their requirement.Explicit conversion also called type casting. for example

A=55.5

B=int(A) // will store integer part in variable B

Debugging

The process of identifying and removing errors is called debugging, Different types of errors:-

i) Syntax errors:- occurs when do not follow the rules of python programming .for example print(“hello] //absence of right parenthesis

ii) Logical errors:- occurs when the logic of program is not correct. It is difficult to trap. For example

For example, if we wish to find the average of two numbers 10 and 12 and we write the code as 10 + 12/2, it would run successfully and produce the result 16 but the correct code to find the average should be (10 + 12)/2

iii) Runtime errors:- A runtime error causes abnormal termination of program while it is executing. For example when we divide any number by zero.

 

 


Team NB Learner