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

1 fundamental of python notes for school

Uploaded by

sparshmishra3457
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

1 fundamental of python notes for school

Uploaded by

sparshmishra3457
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Chapter 1: Python Revision Tour

Fundamental of Python
Introduction of Python
Python is an interpreter, interactive, object-oriented, and high-level programming language. It was created
by Guido van Rossum in 1991 at National Research Institute for Mathematics and Computer Science
Netherlands.

Features of Python

 It is loosely typed Programming Language or Dynamically typed language with few keywords and
simple English-like structure and is easy to learn.
 It is free open-source and portable language having a large repository of libraries.
 It take less time to develop as python programs are typically 3-5 times shorter than equivalent java
programs.
 It is easily compatible with other languages like c, c++, java, etc.
 Python is a Case-sensitive language.

Python IDLE
The python IDLE tool offers an interactive and a more efficient platform to write your code in python.
(Integrated Development Learning Environment)

Python IDLE comprise Python Shell (Interactive mode) and Python Editor (Script mode).

Python Modes or Modes of Python IDLE

● Interactive Mode: The Python commands are directly typed at >>> command prompt and as soon
as we press the enter key, the interpreter displays the results immediately, which is known as
displaying. (We cannot save file or command)
>>>10+50
60
● Script Mode: We can write multiple line of code here and get output and errors are running code.
We can open script mode using CTRL+N
Syntax of print () in python:
print(value1,value1,…………,sep=’ ‘, end=’ ‘)
Displaying Vs Printing: Getting output without using print function in interactive mode is called displaying,
And getting output using print () in interactive or script mode.
Different types of files in python: .py, .pyw, .pyc, .pyd, .pyo, .pyz

Python character set: Character set is a set of valid characters recognized by python. A character by letter,
digit or any other special symbol.
1. Letters: A-Z, a-z 2. Digits: 0-9 3. Special Symbols:+-/*&=!@_ etc.
4. Whitespaces: Blank space, tabs (‘\t’), carriage return (Enter key), newline, form feed (skips to the start
of the next page.)
5. Other Characters: All ASCII code and Unicode character.

Tokens: A token is the smallest element of a python script that is meaningful to the interpreter.

Types of Tokens are:


 Identifiers: Name of variables, constant and function or module is called an identifier.
 Keywords: The reserved words of python. No keyword can be used as an identifier.
 Literals: A fixed numeric or non-numeric value which stored in any variable is called Literals.
 Operators: It is a symbol that performs some kind of operation on given values like: +,-,*, **, /, etc.
 Delimiters/ Punctuators: Delimiters are symbols which can be used as separators of values or to
enclose some values. Like: {} [] , : ;

Structure of a python program:

● Expressions: Expression is a combination of symbols, operators and operands. Like: a+b


● Statements: Statements is defined as any programming instruction given in python as per the
syntax , Like print(‘hello’), a=10
● Comments: Comments are additional information provided for a statement. (#) is used for single
line comment and (‘’’ ‘’’) used for multiple line comments.
● Function: A function is a block of code which only runs when it is called.
● Blocks: A block is a piece of Python program text that is executed as a unit.
Expressions Statements
Expression is a combination of symbols, operators Statements is defined as any programming
and operands instruction given in python as per the syntax
An expression represents some value. Statement is given to execute a task.
The outcome of an expression is always a value. Statement may or may not return a value as the
result.
Ex: 3*7+10 Print(‘hello’), a=10, if 10>5 etc.

Variable:
A Variable is like a container that stores any value. x=3, age=30

Rules for valid Variable name:

● A variable name must start with a letter or the underscore character


● A variable name cannot start with a number
● A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
● Variable names are case-sensitive (age, Age and AGE are three different variables)
● A variable name cannot contain spaces.
Components of Variable/Object:
A). Identity of the Variable / Object: It refers to the Variable’s memory location address which is
unchanged once it has been created. We can check memory location using this method: id()

B). Type of the Variable / Object (data type):

int float Complex Str(seq.) Boolean None


5 5.5 2+5j “hello” True/False(0/1) None
*(None is a datatype with single value. It is used to signify the absence of value / Condition evaluating to
false in a situation.)

We can seen any data type by: type()


y=”Hello”
type(y)
C). Value of the Variable/Object:
The value stored in Variable like: age=20, so 20 is the value of the variable.
L-value is age, and R-Value is 20

Multiple Assignments:
1) Assigning multiple values to multiple variables: x,y,z=2,3,4
2) Assigning same value to multiple variable: a=b=c=10

What is Dynamic Typing:


It refers to declaring a variable multiple times with values of different data types. And variable
automatically changes its data types according to data.

a=10
a=”Hello”

Keywords
Keywords are words that are already reserved for some particular purpose. The names of these keywords
should not be used as identifiers/Variable. Keywords are also called reserved words.

False, None, True, and, as, assert, 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.

Mutable and Immutable Types:


Mutable: A mutable object can be changed after it is created. Example: List, dictionary etc.
Immutable: A immutable object cannot be changed after it is created. Example: int, float, complex, bool,
string, tuple etc.

Taking input by input() (Python built in functions)

1. input(): Its used to get user input in string format.


ex: input(“Enter any number”)
2. int(): This function converts the inputted string value into numeric value if possible.
3. eval(): Its used to evaluate string as a number if possible. eval(“10+50”)
Type Casting
The process of converting the value of one data type (integer, string, float, etc.) to another data type is
called type conversion. Python has two types of type conversion.

1. Implicit Type Conversion: Python automatically converts one data type to another data type. This
process doesn't need any user involvement. Ex: type(5/2)
2. Explicit (forced) Type Conversion: In Explicit Type Conversion, users convert the data type of an
object to required data type. Ex: float(5), str(5),int(‘5’)

Operators and Operands


An operator is a symbol that performs an operation. +,-,*,/
An operator acts on some variables called operands.
For example, if we write a + b, the operator + is acting on two operands a and b. Python provides some
useful operators for performing various operations.

Binary Operators: Operators that operate on two operands are known as binary operators.
Ex: 3+3
Unary Operators: Operators that operate on one operand are known as unary operators.
Ex: -3
Types of Operators:
1. Arithmetic operators: Plus + , Minus - , Multiply * , Division / , Floor Division / /, Modulus % , Power **
Example: 12 + ( 3 ** 4 – 6 ) / 2

2. Comparison operators: Equality == , Not Equal to !=, Less than < , Less than or Equal to <=, Greater than
>, Greater than Equal to >=

3. Logical operators: not, and, or

4. Shorthand /Augmented Assignment operators,

A+=B means A=A+B A-=B means A=A-B A*=B means A=A*B


A/=B means A=A/B A%=B means A=A%B A//=B means A=A//B
A**=B means A=A**B

5. Membership operators:

‘H’ in ‘Hello’ => True ‘y’ in ‘Hello’ => False ‘HEL’ in ‘Hello’ => False
‘y’ not in ‘Hello’ => True ‘H’ not in ‘Hello’ => False
6. Identity operators,

Precedence of Python Operators

Operators Meaning
() Parentheses
** Exponent (Power)
* , /, //, % Multiplication, Division, Floor division, Modulus
+- Addition, Subtraction
==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators
Not Logical NOT
And Logical AND
or Logical OR

*What will be the output of given Expressions:


(5<10) and (10<5) or (3<18) and not 8<18
Conditional Statement and Looping Statement

Flow of execution/Program Control and Flow


Control and flow of a program is classified into 4 categories:
1. Sequence Statement 2. Selection/Decision Statement
3. Iteration / Looping Statement 4. Jump Statement

1. Sequence: In this, program executes in sequential order, one after another, without any jump in the
program.

Ex: Program to calculate sum:

a=10
b=20
c=a+b
print(c)

2. Selection/ Decision: In this, program executes according to condition. If any condition in true code will
run if condition if false code will not run. Keyword If , else

Types of Decision making statement in python:

1. if statement
2. if else statement
3. if elif else statement
4. Nested if-else statement
if statement: if else statement:
The statements inside the body of “if” only The if/else statement executes a block of code if a
execute if the given condition returns true. If the specified condition is true. If the condition is false,
condition returns false then the statements inside another block of code can be executed.
“if” are skipped. Syntax:
Syntax: if test expression:
if test expression: Body of if
statement(s) else:
statement(s) Body of else
if elif else statement: Nested if-else statement:
The if-elif-else statement allows you to check When you want to check for another condition after
multiple expressions for TRUE and execute a block a condition resolves to true. In such a situation, you
of code as soon as one of the conditions evaluates can use the nested if else statement.
to TRUE. The syntax of the nested if...elif...else construct
Syntax may be −
if expression1:
statement(s) if expression1:
elif expression2: statement(s)
statement(s) if expression2:
elif expression3: statement(s)
statement(s) else:
else: statement(s)
statement(s) else:
statement(s)
3. Iteration / Looping: In this statement program executes multiple times according to condition. Keyword
while, for

Types of looping statement in python:

For loop statement: While loop statement:


The for loop statement is used to iterate / repeat A while loop statement in python executes a block
itself over a range of values or a sequence. (That is of code repeatedly as long as the test/control
either, a list, a tuple or a string). condition of the loop is true.
Syntax: Syntax:
for iterating_var in sequence: while test expression:
statements(s) Body of while
statements(s)
Use of range()
range(start, stop, step)

Nested for Loop Nested while loop


i=1
for i in range(1,6): while i<6:
for j in range(1,i+1): j=1
print("*", end=" ") while j<1+i:
print() print("*",end=" ")
j=j+1
print()
i=i+1

4. Jump Statement:

Break Statement: Continue Statement: Pass Statement: The pass


Break statement in Python is used The continue statement is used to statement is a null operation, it
to terminate the loop when some skip the rest of the code inside a does nothing, it is also called
external condition is triggered. loop for the current iteration empty statement.
only.
Break statement with for loop l=[10,20]
Continue statement with for loop
Syntax for i in l:
Syntax
pass
for iterating_var in sequence:
for iterating_var in sequence:
if condition:
if condition:
break
continue
statements(s)
statements(s)
What is String in Python?
A string is a sequence of characters. We can enclose characters in quotes (single, double or triple.) For
example: fruits=’Mango Apple Grapes’

Creating String /Types of string:

str1=’Hello world’
str2=”Python Programming”
str3=’’’Python
Programming’’’

Escape sequence character: \, \n, \t, \r, \f, \’, \’’.

*(An escape sequence character is represented as a string with one byte of memory.)

Empty String: An empty string is a string without any characters inside. str=” ”, str=’ ‘

Multiple line String: Multiline strings are represented using triple quotes (‘’’ ‘’’) or even single or double
quotes.

Indexing in a string (Accessing Characters)

Accessing individual characters of the string by using the index value is called indexing.
Traversing a String: Traversing a string means accessing all the elements of the string one after the other
by using the subscript / index value.

For loop:

First way: Second way:

While loop:

Special String Operators:


Concatenation: Adding two strings. + is the operator to join two string. Example: “Hello ”+”world”

Repetition or Replicate: Create multiple copies of any string. * for repetition. Some Example: “Hello” *3.

Membership: Check whether a particular character exists in the given string or not.
Operators are: “in” and “not in”
Some Example:
“H” in “Hello” Gives True
“H” not in “Hello” Gives False.

Comparison Operators: Comparison operators are used to compare two strings. Python compares strings
using ASCII or UNICODE.
Some Example:
“Tim”==”tim” Gives False
“Freedom” > “Free” Gives True

String Slicing: Slicing is used to retrieve a subset of values. Chunk of characters can be extracted from a
string using slice operator. Example: var1 [start: end: step]
Some Example:
Str=”Save money”
str[1:3] gives “av”
str[:3] gives “Sav”
Updating: We can "update" an existing string by (re)assigning a variable to another string.

Example: var1 [range] +”x”

String are Immutable:


Strings are immutable means that the element of the string cannot be changed after it is created.
a=”student”
a [1] =”O” is invalid.

String Methods and Built-in-functions:

len() index() count() lstrip() join()


capitalize() isalpha() lower() rstrip() swapcase()
split() isalnum() islower() strip() partition()
replace() isdigit() upper() isspace() ord()
find() title() isupper() istitle() chr()

What is List in Python?


A list is a collection of comma-separated values (items) within square brackets. Items in a list need not of
the same type. It stores data in ordered sequence.

Declaring/Creating List:

Syntax to creating List:


List_name=[“value1”, “value 2”, “value 3”, “value 4”]
Nested_List=[“value1”, [“value 2”, “value 3”], [“value 2”, “value 3”]]
Empty list=[ ]
Creating list from sequence, list(“Hello”)

Accessing List Elements:

Traversing a list: Traversing a list means accessing each element of a list. This can be done by using either
for or while looping statement.

Aliasing means: It mean nick name or alternate name of object. Means two object with same id.
Copying list: It means to create clone or copy the list as different object. Means with different id.
List Operators in Python

1) Concatenation:. ‘+’ is a symbol of concatenation operator.

2) Repetition/Replication/Multiply: ‘*’ is a symbol of repetition operator.

3) Membership Operator: ‘in’ And ‘not in’ are the operators for membership operator.

4) Indexing: Index is nothing but there is an index value for each item present in the sequence or list.
Example of nested list also.

5) Slicing Operator: Slice is used to retrieve a subset of values.


Syntax: list [start : stop : step]

6) Comparing List: Python allows us to compare two lists. Each element is individually compared in
lexicographical (alphabetical or dictionary) order.

Built-in-functions and Methods of List

Append() Len() del statement Extend() Sort() Remove()


Insert() Clear() Max() Reverse() Count() Min()
Index() Pop() Sum()

Tuple in Python:
What is Tuple:
Tuple is a sequence of immutable Python object. Tuples are sequences, just like lists.
Tuples use parentheses and lists use square brackets.
Tuple can hold elements of different data type (Heterogeneous).
Tuples are immutable it means we cannot perform insert, update and delete operation on them. So,
iterating through a tuple is faster as compared to a list.

Tuple creation:

Empty tuple: t=()


Tuple with one element: t=(10,)
Tuple with one element: t=10,
Tuple with multiple value: t=(10, “Hello”,20,”Kanpur”)
Tuple with multiple value: t= 10, “Hello”,20,”Kanpur”

Creating tuple using function tuple()

Nested Tuple:Example: fruits= (10 , 20 , (‘Ram’ , ’Mohan’) , 40 , 50 , [‘Red’ , ’blue’] , 60)

Accessing a Tuple and Nested Tuple:


Traversing a Tuple:

Traversing a tuple means accessing each element of a tuple. This can be done by using either for or while
looping statement.

Common Tuple operations:


 Tuple Slicing: Slicing is used to retrieve a subset of values.
Syntax: tuple_name[start:stop:step]
 Tuple Addition/Concatenation/joining:
 Tuple Multiplication/Repetition
 Membership Operator like ‘in’ and ‘not in’
 Comparing Tuples

Built-in-functions and Methods of Tuple

len() count() any() min() max()


sorted() index() del statement

Some features of a tuple:


 You can't add elements to a tuple because of their immutable property. There's no append() or
extend() method for tuples.
 You can't remove elements from a tuple, also because of their immutability. Tuples have no
remove() or pop() method.
 You can find elements in a tuple since this doesn't change the tuple.
 You can also use the in operator to check if an element exists in the tuple.
 To change a tuple you can unpack it first, then change the value and pack it again.
 You can use list() and tuple() methods to change the values of a tuple.
 Tuples use less memory whereas lists use more memory.
Dictionary in Python:

What is Dictionary:
A python dictionary is a mapping of unique keys to values. It is a collection of key-value pairs. Dictionaries
are mutable which means they can be changed.

Important features of dictionaries are:

 Each key map to values. It’s called key value pair.


 Each key is separated from its values by a colon(:), the items are separated by commas, and the
entire dictionary is enclosed in curly braces {}.
 Keys are unique within a dictionary while values may not be.
 The value of a dictionary can be of any type, but the keys must be of an immutable data types.
Adding an item in Dictionary:
Creating a Dictionary: D={}
Empty dictionary: D[‘input’]=’Keyboard’
d={} D[‘Output’]=’Printer’
d=dict() D[‘Language’]=’Python’

D={‘input’: ’Keyboard’, ‘Output’:’Printer’, ‘Language’=’Python’}


Accessing a Dictionary:
To access dictionary elements, you can use the square brackets along with the key to obtain its value.
print (D[‘Output’])
It will give out: ‘Printer’
Traversing a Dictionary:
Traversing a dictionary means accessing each element of a Dictionary. This can be done by
Using either for or while looping statement.
Common Dictionary operations:
 Appending values to Dictionary, means add new elements to exiting dictionary.
 Updating Elements in a Dictionary
 Membership Operators ‘in’ and ‘not in’
 Removing an item from Dictionary
Built-in-functions and Methods of Dictionary

len() clear() get()


items() keys() values()
fromkeys() copy() popitem()
Max() min() sorted()

You might also like