0% found this document useful (0 votes)
9 views

Python Notes Jnvb Sept7

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Python Notes Jnvb Sept7

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

JAWAHAR NAVODAYA VIDYALAYA :: BNAVASI KURNOOL

2.Introduction to Python
Q1:What is Program?
Ans: An ordered set of instructions or commands to be executed by a computer is
called a program

Q2:What is Programming Language?


Ans :The language used to specify set of instructions to the computer is called a
programming language .Example : Python, C, C++, Java, etc.

Q3.What is Python?
Ans:Python is a programming,highlevel,interpreted,portable,free&open source language, as
Python programsare executed by an interpreter.Created by Guido van Rossum in
February,1991.Python got its name from a BBC comedy series from seventies called “Monty
”. It is based on two programming languages called ABC and
Modula–3.
Q4: What are the Advantages ofPython?
1.Easy to Use: Python is compact and very easy to use with very simple syntax
rules. It is programmer–friendly
2.Expressive Language: Because of simple syntax and fewer lines of code, it is
more capable to express code's purpose than many other languages
3.Interpreted Language: Python interprets and executes the code line by line at a
time. It makes Python an easy–to–debug language and thus suitable for beginners
and advanced users.programs written in Python are easily readable and
understandable
4.Completeness: Python Standard Library provides various modules for different
functionalities.
5.Cross–Platform Language: Python can run on different platforms like Windows,
Linux / Unix, Macintosh, Super Computers, Smart Phones etc. Hence it portable
language
6.Free and Open Source: Python is freely available at free of cost and its source
code is available to every body for further improvement
7.Variety of Usage: Python can be used for a variety of applications like Scripting,
Web Applications, Software development.,Game development, System
Administration, Rapid Prototyping, GUI Programs, Database Applications etc.,
scientific computing, big data and Artificial Intelligence.
8.Case Sensitive:It is case sensitive. i.e. Uppercase and Lowercase alphabets are
different
3.1.1 Working with Python
To write and run Python program, install Python interpreter in computer. IDLE (GUI integrated) is the
standard, most popular Python development environment.

Python shell(interpreter) can be used in 2 ways(i)Interactive Mode(ii) Script Mode


Other IDE’s are: PyCharm, Visual Studio Code, Sublime Text, Jupyter, Spyder, PyDev.
(i)Interactive Mode:As the name suggests, this mode allows to interact with OS. This mode does not save
commands in form of a program. The symbol '>>>' is called Python prompt, indicates that interpreter is
ready to accept command.

(ii) Script Mode:In the script mode, we can write a Python program in a file, save it and then use the
interpreter to execute the program from the file. Such program files have a .pyextension and they are
also known as scripts.
Basic Structure Of Python Program:

1.Comments:These are the statements that will be ignored by Python interpreter .A single line
comment starts with the symbol#. For multiline comment content will be enclosed in triple quotes
(" " ") or triple apostrophe (' ' ').

2.Functions: A function is a code that has collection of statements to do some task. It has a name
and a function can be executed repeatedly as many times required

def wish(name): def rip(name):


print("HAPPY BIRTH DAY Mr.", name) print("REST IN PEACELate",name)
wish("Syed Rafiq") rip("Syed Rafiq")

3.Statement:A statement is a programming instruction that does something i.e. performs some
action.An expression evaluates and gives some results.
x = 15
y =x – 2 * 4
z = x + z – 10
if (x > y):
4.Expression:An expression in Python is a combination of literals,operators and operands that is
evaluated to produce some other values

Some examples of valid expressions are given below.

(i) num – 20.4 (iii) 23/3 -5 * 7(14 -2)

(ii) 3.0 + 3.14 (iv) "Global"+"Citizen"

5 Indentation and Blocks:Python uses indentation for block as well as for nested block structures.
Leading whitespace (spaces and tabs) at the beginning of a statement is called indentation. In
Python, characters that are used for spacing are called as whitespace characters.

A block is a piece of Python program text that is executed as a unit.

PYTHON CHARACTER SET:


Python character set represents the set of valid characters that Python supports. It has the
following character set
Letters A–Z, a–z
Digits 0–9
Special Space + – * / ** \ { } ( ) // = != == < , > . ' ' " " ; : % ! & # <= >=
Symbols @ _ (underscore)
Whitespace Blank Space, Escape characters( Newline \n ,Tab \t, Carriage
Return \r, , Form feed\f)
Other Python can process all ASCII(American Standard code for
Characters Information Interchange) and Unicode characters as part of data
or literals
TOKENS: The smallest individual unit in a program is known as Token. It is also
called as Lexical Unit. There are 5 Tokens present in Python are
(i) Keywords (ii) Identifiers (iii) Literals (iv) Operators (v) Punctuators

1.Keywords or Reserved Words:Each keyword in python has a specific meaning to


the Python interpreter.keywords cannot be used as identifiers, variables &
functions and Python has the 33keywords. Except “False”, “None”, and “True” all
the keywords are in lowercase.

async,await
A3(2)+B1+C2+D2+E3+F4+G1+I4+L1+N3+O1+P1+R2+T2+W2+Y1
To get the updated keywords list type below program
import keyword
list=keyword.kwlist
print(len(list))
for i in list:
print(i)
2.Identifiers: InPython programming language, identifiers are names usedto identify a
variable, function, or other entities in aprogram.
The 4 rules for naming an identifier in Python are as follows:
1Name should begin with uppercase (A-Z) orlowercase (a-z) orunderscore sign (_).
2.It can be of any length (it is preferred tokeep it short and meaningful)
3.An identifiercannot start with a digit &It should not be a keyword or reserved word
4.We cannot use special symbols like !, @, #, $, %, etc.in identifiers

Valid Identifiers Invalid Identifiers Remarks


_marks !marks No Special Character
Myfile My file No Space
syed_rafiq syed-rafiq Hyphen given
name 1name Can’t start with digit
true True Reserve words can’t use
3.Literals / Constants: A literal or constant is a program element that will never change
its values during program execution.
Python allows5 kinds of literals like (i) String literals (ii) Numeric literals (iii) Boolean
literals (iv) Special Literal None v. Literal Collection (list, tuple, set, dictionary)

(i)String or Character Literals: A string literal is a sequence of characters enclosed in


either single quotes or double quotes. Ex: “python”, ‘python’ ‘’’python’’’.
Escape sequence will be given as a string and performs specified task. Some escape
sequences are
\n New line characterEx:>>>print ("I like \t \t python langage")
\t Horizontal Tab Ex:>>>print ("I like \n \n python langage")
Python allows (i) Single–line Strings (ii) Multiline Strings
Single–line Strings: The strings that create by enclosing text in single quotes or double
quotes are called single–line strings. Ex: "Python", 'Apple'
Multiline Strings: To provide a string in multiline, it is to be provided in triple quotes
(triple single quotes or triple double quotes)
(ii)Numeric Literals: In Python,Numeric Literals consists of digits and are
immutable(unchangeable).There are three types namely (i) Integer literals (ii) float literals
(iii) complex literals

(i) Integer literals:An integer literal is whole numbers or must have at least one digit and
must not contain any decimal point.
Python Supports 4 types of integer literals
a. Decimal Integer literals b.Binary Integer Literals
c. Octal Integer literals d.Hexadecimal integer literals.
a. Decimal Integer Literals: It consists of a sequence of digits between 0 and 9 and does
not start with zero. Ex: 1234, –458 etc.
b. Binary integer literals: consists of digits “0” and “1” and starts with “0b”

c. Octal Integer Literals: It consists of sequence of digits between 0 to 7. It begins with


“0o”(Digit Zero followed by Letter o) Note: 8 and 9 are invalid in Octal Integer

4.Hexadecimal Literals: It consists of a sequence of values between 0–9 and A–F. It


begins with “0x”. The numbers 10 to 15 are represented by A-F

2. Floating (or) Real Point Literals: represent real numbers and are written with a decimal
point.These can be expressed in two forms viz. Fractional Form and Exponent Form
a. Fractional form: it consists of signed or unsigned digits including a decimal point
between digits Ex: 3.0,15.9,-10.0
b.Exponent form: A real constant in exponent form consists of two parts mantissa and
exponent. The mantissa must be either an integer or a proper real constant. The mantissa
is followed by a letter E or e and the exponent. The exponent must be an integer.
Ex: 152E05, 1.52e07, 0.152E08, 152e+8,–0.172E–3, .25e–4
3. Complex Literals: Complex number in python is made up of two floating point values,
one each for real and imaginary part. Syntax: a + bj,
a is the real part of the number.b is the imaginary part of the number.
j represents the imaginary unit, which is the square root of -1.i2=-1

(iii)Boolean Literals: A Boolean literal represent one of the two Boolean values i.e. True or
False. It is a unique data type, consisting of two constants, True and False. Boolean True value is
non-zero(1). Boolean False is the value zero(0).

(iv)Special Literal- None: None is a special literal in Python. It indicates the absence of
value. It means "There is not useful information" or "There is nothing here".
>>>a = None
>>>print (a)
None
4. Operators:An operator is a symbol that is used in a program in respect of some operation.
Each programming language will have its own set of operators.
The constants or variables that participate in the operation are called operands

Unary Operator: If an operator takes only one operand Ex:5


Binary Operator: If an operator takes two operands Ex: 1+3=4
Ternary or Conditional Operator: ternary operator is just a shorthand of the if and if...else
statements. You can use it in just a single line of code.If an operator takes three operands
Ex

5. Punctuators: These are the symbols used in programming to organize sentence structures and
indicate the emphasis of expressions, statements and program structure. Some punctuators
available in Python are, ' " # \ ( ) [ ] { } @,:. =
Variables: A variable is an identifier whose value can change during program execution.In
Python, we can use an assignment operator(=) to create new variables and assign specific values
to them.
Ex: gender = 'M' , message = "Keep Smiling" , age=30

LValues and RValues: The LValues are the variables that hold a value or expression. The RValues
are the literals or variables that are assigned to LValues and can present on only right–hand side
of assignment.
Ex: Valid Statements a = 20 Invalid Statements: 20 = a
Multiple Assignments: Different ways of assignments are
1. Assigning same value to multiple variables
Ex: a = b = c = 18
2. Assigning multiple values to multiple variables
Ex1: x, y, z = 10, 20, 30 # Means x=10, y=20, z=30
Ex2: x,y = y,x # This makes x=20, y = 10
Ex3: a, b, c = 5, 10, 7
a, b, c = a+1, b+2, c–1
print (a, b, c) # a=6, b=12, c=6
Displaying type of variable: The type( ) can be used to display the data type of a variable.
>>> a=10 >>> a=20.5 >>> a="Python"
>>> type(a) >>> type(a) >>> type(a)
<class 'int'> <class 'float'> <class 'str'>
id of an object: The id of an object is the memory location of it. The function id( ) is used
for this purpose Ex:

Constant: In the Python programming language, Constants are types of variables whose values cannot
be altered or changed after initialization Eg:3.14; gravity=9.8
Input() And Output() functions In Python:
Input:-In Python, we have the input() function for taking values entered by input device such as a
keyboard. The input() function prompts user to enter data.
Syntax for input() is: variable = input([Prompt]) Eg:>>> name = input("Enter your name: ")
Print():Python uses the print() function to output data to standard output device — the screen.
The function print() evaluates the expression before displaying it on the screen
Syntax for print() is: print(value) Eg:>>>print("Hello")
Data Types in Python:

Sequences:- Sequence: is an ordered collection of items, where each item is indexed by an


integer value. Python provides sequence data types like Strings, Lists, Tuples, and mapping data
type Dictionaries
(a)Strings: String is a group of characters, Every character in a string has an index ,and Every
character has two indexes Forward Indexing(0,1,2,3…) to and Backward Indexing(-1,-2,-3,…)
Ex:
Index 0 1 2 3 4 5
String P Y T H O N
Index –6 –5 –4 –3 –2 –1
Type conversion or casting: to change one type of value/variable to another type and can be
done in 2 ways. Explicit (programmer specifies the conversions) or implicit(Interpreter
automatically converts the data type).

(b)Lists: List is also a sequence of values of any type. Values in the list are called elements / items.
They are mutable and indexed/ordered. List is enclosed in square brackets [].Example: l = [1,2.3,’jnv’]

(c)Tuples: Tuples are a sequence of values of any type, and are indexed by integers.
They are immutable. Tuples are enclosed in parentheses (). Example: t=(1,2.3,’jnv’)

(d)Sets: A set is an unordered collection of unique elements with no duplicate entry.


They are mutable. Sets are enclosed in curly brackets { }. Example: s={1,2.3,'jnv'}, s=set([1,2.3,'jnv'])

Mapping:-Mapping is an unordered data type in Python. Currently, there is only one standard mapping data
type in Python called Dictionary.

Dictionary: Dictionary is an unordered data type in Python holds data items in key-value pairs,
They are mutable. Dictionaries are enclosed in curly brackets { }
Ex: d={"Name" : "Teja", "Age":16,"Group":"MPC","Fees":20000,"School":"JNV"}
MUTABLE AND IMMUTABLE DATA TYPES:
Mutable Types: The mutable types are those that can change their value in place. Lists, Sets and Dictionaries and
are mutable types

Immutable Types: The immutable types are those that cannot change their value in place. Integers, Float, Booleans,
Complex,Strings and Tuples are immutable types

Python Operators: Python supports 5 kinds of operators.

1. Arithmetic Operators 2.Relatonal or Comparison Operators 3.Assignment Operators


4.Logical Operators 5.Membership Operators

1. Arithmetic Operators: Python supports arithmetic operators to perform the four basic
arithmetic operations (+ - * /) , floor or integer division (//)Quotient,
modulus division(%)Remainder, and exponentiation (**)Power(^)
2.Relatonal or Comparison Operators: in Python are used to compare two values and return a
Boolean result (True or False).There are 6 RO’s in Python 1.Greater than(>) 2.Greater Than or Equal
To(>=),3. Less Than(<),4. Lesser Than or Equal To(<=),5. Equal To(==),6. Not Equal To(! =)

3. Assignment Operators: in Python assign values to variables.There are 8 ASo’s in Python


4.Logical Operators: There are three logical operators supported by Python. These operators (and,
or, not) are to be written in lower case only. The logical operator evaluates to either True or
False based on the logical operands on its either side.
1.and: and operator is used by applying(.-->dot) between two variables, it is just like
multiplication. If both operands are True, then condition becomes True

2.or : or operator is used by applying(+-->plus) between two variables, it is just like addition.
If any of the two operands are True, then condition becomes True

3.Not: Used to reverse the logical state of its operand.It returns True if the conditional expression
returns False, and vice-versa.
#WAPP by using LO operators
Membership Operators : is used to check if a value is a member of the given sequence
or not. There are two membership operators in python in and not in.
1.in Operator: Returns True if the variable or value is found in the specified sequence
and False otherwise.

2.Not in: Returns True if the variable/value is not found in the specified sequence and
False otherwise

Expressions: An expression is defined as a combination of constants, variables and operators


Some examples of valid expressions are given below.
(i) num – 20.4 (iii) 23/3 -5 * 7(14 -2) (ii) 3.0 + 3.14 (iv) "Global"+"Citizen"
Precedence of Operators: When an expression contains more than one operator, their
precedence (order or hierarchy) determines which operator should be applied first. Higher
precedence operator is evaluated before the lower precedence operator.

You might also like