0% found this document useful (0 votes)
6 views17 pages

Un2 - CH - Basics of Pyhton To Flow of Control - Shnotes

The document provides an overview of Python programming, including its history, characteristics, advantages, and disadvantages. It covers essential concepts such as data types, variables, operators, control flow statements, and error handling. Additionally, it discusses Python's syntax rules, comments, and the importance of indentation in code structure.

Uploaded by

mukhiljeeva
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)
6 views17 pages

Un2 - CH - Basics of Pyhton To Flow of Control - Shnotes

The document provides an overview of Python programming, including its history, characteristics, advantages, and disadvantages. It covers essential concepts such as data types, variables, operators, control flow statements, and error handling. Additionally, it discusses Python's syntax rules, comments, and the importance of indentation in code structure.

Uploaded by

mukhiljeeva
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/ 17

PYTHON

SHORT NOTES

COMPUTER SCIENCE-(083)

RACHEL .V PGT CS/IP


BE BRIGHT
BASICS OF PYTHON
Developer :-
Python Programming language was developed by Guido Van Roussum in
early 1990s, its name is taken from a famous circus “Monty Python Flying Circus”

Python IDE(Integrated Development Environment):-

It is a software that provides an environment where a programmer can develop python


program. There are various IDE available
for example:- IDLE(Integrated Development Learning Environment), Sublime,
Atom,Pycharm, Canopy, Tonney etc

Python is a case-sensitive language.

All the commands are written in small letters. It differentiates between Capital letter and
small letter of same character. For example Computer and computer are considered two
different words. Capital letters are always treated smaller then lower letters. For example ‘Z’
is smaller then ‘a’.

Characteristics of Python:
Object-Oriented, Open-Source, Portable, Platform-independent, interpreted Language
developed by Guido Van Rossum in 1991.

Advantages of Python:
➢ Easy to use: Compact, easy to use, programmer friendly, simple syntax rules.
➢ Expressive syntax :Fewer lines of code with simple syntax.
➢ Interpreted Language: Interprets the code line by line at a time. It makes Python an
easy to debug language and suitable for beginners to advanced users.
➢ Completeness: No need to download and install additional libraries; all types of
required functionality is available through various modules.
➢ Cross Platform Language: Python can run equally well on variety of platforms -
Windows, Linux /Unix, Macintosh
➢ Free and Open Source: Freely available without any cost. Its source code is also
freely available.
➢ Applications: Scripting, Gaming Applications, GUI Programs, Database Application,
Web Applications
DisAdvantages of Python:

➢ Not the fastest Language: Python is an interpreted not a compiled language.


➢ Lesser libraries: Python offers library support for almost all computing programs but
its library is still not competent with C, Java and Perl
➢ Not strong on Type Binding: Python interpreter is not very strong on catching type
mismatch issues

Character Set of Python:

Set of all characters recognised by python. It includes:


• Letters: A- Z and a -z
• Digits: 0-9
• Special Symbols: + , - , /, % , ** , * , [ ], { }, #, $ etc.
• White spaces: Blank space, tabs, carriage return, newline, form feed
• Other Characters: All ASCII and UNICODE characters.
Tokens:
Tokens are smallest identifiable units in a python program. Different tokens are:
● Keywords: Keywords are reserved words. Each keyword has a specific meaning to the
Python interpreter, and we can use a keyword in our program only for the purpose for
which it has been defined. As Python is case sensitive, keywords must be written
exactly. Examples: int, print, input, for, while
● Identifiers: name given by programmer to identify variables, functions, constants, etc.
Rules for identifier names:
▪ Keywords cannot be used
▪ Can contain A-Z,a-z,0-9 and underscore(_)
▪ Cannot start with a number.
▪ We cannot use special symbols like !, @, #, $, %, etc., in identifiers.
Example: engmark, _abc , mark1, mark2
● Literals: literals are constant values.Literals in Python refer to the fixed values
assigned to variables. These are the raw values or data that do not change.
There are several types of literals in Python:

1. String Literals: These are sequences of characters enclosed in quotes.


o Example: "Hello, World!", 'Python'
2. Numeric Literals: These are numerical values.
o Integer Literals: Whole numbers without a fractional part. Example: 10,
-5
o Float Literals: Numbers with a fractional part. Example: 3.14, -0.001
o Complex Literals: Numbers with a real and an imaginary part. Example:
3+4j, -2-3j
3. Boolean Literals: These repre sent True and False values.
o Example: True, False
4. None Literal: Represents the absence of value or a null value.
o Example: None
5. Collection Literals: These include lists, tuples, dictionaries, and sets.
o List Literals: Example: [1, 2, 3, 4]
o Tuple Literals: Example: (1, 2, 3, 4)
o Dictionary Lit erals: Example: {'key1': 'value1', 'key2':
'value2'}
oSet Literals: Example: {1, 2, 3, 4}
● Delimiters: Symbols used as separators. Examples: {} , [ ] ; :
● Operators: Operators trigger an operation. Parameters provided to the operators are
called operands. Examples: + - * % ** / //

Data types:
Data type represents the type of data a Variable or a Literal is referring to. Each data type has
specific characteristics and operations associated with it.
In Python, there are various data types, Data types of variables:
● Numeric Types: int, float, complex
● Boolean – True or False values.
● None – a special type with an unidentified value or absence of value.
● Sequence: an ordered collection of elements. String, List and Tuples are sequences.
● Mappings – Dictionaries are mappings. Elements of dictionaries are key-value pairs.
Mutable and Immutable types:
Mutable -Values can be changed in place. E.g. List, Dictionary
Immutable: Values cannot be changed in place in memory. E.g., int, float, str, tuple.

Variables and Assignments:


Variables are used to store data.
The assignment operator (=) is used to assign values to variables. E.g. a = 100

Multiple Assignments:
• Assigning same value to multiple variables - a = b = c = 1
• Different values to different variables- a, b, c = 5,10,20
Dynamic typing:
Python is a dynamically typed language, which means that you don’t need to declare
the type of a variable when you create one. The type is determined at runtime based on
the value assigned to the variable

Comments:
Comments are ignored by the Python interpreter. Comments gives some message to the
Programmer. It can be used to document the code.
Comments can be:
• Single-line comments: It begins with a hash(#) symbol and the whole line is
considered as a comment until the end of line.
• Multi line comment is useful when we need to comment on many lines. In python,
triple double quote (" " ") and single quote (' ' ') are used for multi-line commenting.
Example:
# This is a single line comment
' ' 'I am a multi line comment ' '’
print statement: used to display output. If variables are specified i.e., without quotes then
value contained in variable is displayed.
E.g., x = "scts " Output:
print(x) Scts

To combine both text and a str variable, Python uses the “+” character:
Example
x = "awesome" Output:
print("Python is " + x) Python is awesome
input() function:An input() function is used to receive the input from the user through the
keyboard.
Example: x=input('Enter your name')
age = int( input ('Enter your age'))
ex: num = int(input("Enter a Number : "))
num_cube = num*num*num
print("The cube is : ",num_cube)
Expressions:
An expression is combination of values, variables and operators.
E.g. – x= 3*3//5
Operators:
Operators trigger an operation. Some operators need one operand, some need more than one
operand to perform the operation.

Operand: Value(s) required for operation of operator.


Operators: Operators can manipulate the value of operands (variables or values).
Various symbols are used as operators.
a=5
b=6
sum = a + b
In above example, + and = are the operators, a, b are operands and sum is a variable.

Expression
An expression is combination of operators, operands, literals and parenthesis. An
expression produces a value when evaluated.

Python Statement
In Python, a statement is an instruction that the interpreter can execute.
Types of Operators
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Identity Operators
6. Membership Operators
Arithmetic operators: Arithmetic operators perform mathematical operations such as
addition, subtraction, multiplication, division, and modulus.

Modulo Operator
The modulo operator (%) evaluates the remainder of the operation when the operand on
the left is divided by the operand on the right of the modulo operator.
Example
15 % 7 = 1
13 % 7 = 6

Relational Operators: Relational operators compare the operands. They evaluate to


either True or False.
Logical operators:
Logical operators combine logical values of true or false into a logical expression. They
evaluate to either True or False. There are three basic types of logical operators: 'NOT',
'AND', and 'OR'.

Assignment operators:
Variables are assigned values using assignment operators.

Example :
sum = 5 + x
result += 5

Here, the sum variable is assigned


the sum of 5 and x. And, the result
variable is assigned the sum of
result and 5.

Identity Operators

The identity operators in Python are "IS" and "IS NOT". They check whether the two
objects are of the same data type and share the same memory address.
Example :
x=5
y=5
if x is y:
print("x and y are the same object")
else:
print("x and y are different object")

Output will display x and y are the same object because both of them reference the same
memory location.
Membership Operators

The membership operators in Python are 'IN' and 'NOT IN'. They check whether the
operand on the left side of the operator is a member of a sequence (such as a list or a
string) on the right side of the operator.
Example :
x = ['Red', 2, 'Green']
if 'Red' in x:
print("Found")
else:
print("Not Found")

Output will display Found because the item 'Red' is a member of the List x.
Precedence of Operators:

The operator having high priority is evaluated first compared to an operator in lower
order of precedence when used in an expression.

Examples:

1. x = 7 + 3 * 2 2. >>> 3+4*2
13 11
* has higher precedence than +, so it first Multiplication gets evaluated before the
multiplies 3*2 and then adds into 7 addition operation
Associativity of operators: Associativity refers to the order in which operators of the
same precedence evaluated. The associativity of an operator may be left-to-right or right-to
left.

Type castingor type conversion:


It is the process of converting a variable from one type to another. In Python, you can perform
type casting using built-in functions.
GHere are some common examples:

1. Implicit Type Conversion: Python automatically converts one data type to another
without any user intervention.

x = 10 # int
y = 2.5 # float
z = x + y # z is automatically a float
print(z) # Output: 12.5
print(type(z)) # Output: <class 'float'>
2. Explicit Type Conversion: You manually convert a variable to a different type using
built-in functions like int(), float(), str(), etc
num_str = "42"
num_int = int(num_str)
print(num_int) # Output: 42
print(type(num_int)) # Output: <class 'int'>

Errors:
A programmer can make mistakes while writing a program, and hence, the program may
not execute or may generate wrong output. The process of identifying and removing such
mistakes, also known as bugs or errors, from a program is called debugging.
Errors occurring in programs can be categorized as:
i) Syntax errors.
ii) Logical errors
iii) Runtime errors
Syntax Error
Syntax are the rules for framing statements in a programming language. Any violations in
the rules while writing a program are known as Syntax Errors. They prevent the code from
executing and are detected by the Python interpreter before the execution of the program
begins. Some of the Common Syntax Errors are
● Parenthesis Mismatch
● Misspelled keyword
● Incorrect Indentation
Logical Error
Logical errors occur when the code runs without any errors, but the output is not as
expected. Logical errors are caused by a problem in the logic of the code.
Example :
Average = mark_1 + mark_2 / 2 # incorrect calculation of average marks Corrected Code :
Average = (mark_1 + mark_2 ) / 2
Runtime Error
A runtime error causes abnormal termination of the program during the execution. Runtime
error occurs when the statement is correct syntactically, but the interpreter cannot execute it.
Example: 'division by zero'
num1 = 5.0
num2 = int(input("num2 = ")) #if the user inputs zero, a runtime error will occur
print(num1/num2)
Statement flow control:

Statements are the building blocks of the code, and they can be classified into different types
• Compound statement: A compound statement in Python is made up of multiple
individual statements, often organized in a block and executed together.
Ex. Conditional, loop statement
• Simple statement: A single excecutable statement
• Empty statement : It is represented using the pass keyword. It is used as a placeholder
in loops, functions, classes, or conditional statements when no code needs to be
executed.
for i in range(5):
if i == 3:
pass # Do nothing
else:
print(i)
Terminology

Indentation
Indentation refers to the spaces at the beginning of a line. Example
if a<5:
print(a)
print('Inner Block')
print('Outside block')

Block of code
A block of code is a set of statements that are grouped together and executed as a single unit.
A block of code is identified by the indentation of the lines of code.

Selection Statements:
It helps us to execute some statements based
on whether the condition is evaluated to True
or False.
if statement: A decision is made based on the result of the comparison/condition. If condition
is True then statement(s) is executed otherwise not.
Syntax:
if <expression>:
statement(s)
Example:

a=3 Output:
if a > 2: 3 is greater
print(a, "is greater")
done
print("done")

if-else statement:
If condition is True then if-block is
executed otherwise else-block is
executed.
Syntax:
if condition:
# code to execute if the condition
is true
else:
# code to execute if the condition
is false

Example:
a=int(input('enter the number')) Output:
if a>5: enter the number 2
print("a is greater") a is smaller than the input given
else:
print("a is smaller than the input given")
if-elif-else statement:
The elif statement allows us to
check multiple expressions for
TRUE and execute a block of
code as soon as one of the
conditions evaluates to TRUE.

Syntax:
If <test expression>:
per = int(input("Enter Percentage : "))
Body of if stmts
if per >= 75:
elif < test expression>:
print("Distinction")
Body of elif stmts
elif per >= 60:
else: print("Grade-A")
Body of else stmts elif per >= 50:
print("Grade-B")
elif per >= 40:
print("Grade-C")
else:
Example: print("Grade-D") expression value

Nested if statement
A nested if statement is an if statement that is placed inside another if statement. This allows
you to test multiple conditions.
Syntax:
if condition1:
# code to execute if condition1 is true
if condition2:
# code to execute if both condition1 and condition2 are true
else:
# code to execute if condition1 is true but condition2 is false
else:
# code to execute if condition1 is false
Ex:
age = 20
income = 40000
if age >= 18:
if income >= 30000:
print("You are eligible for the loan.")
else:
print("You meet the age requirement, but your income is too low.")
else:
print("You are not eligible for the loan because you are underage.")

range( ) Function range( ) is a built-in function that returns a sequence of numbers.


Syntax range(start, stop, step)
start: The starting value of the sequence (inclusive). If not specified, it defaults to 0.
stop: The ending value of the sequence (exclusive).
step: The difference between two consecutive elements.
Its default value is 1. The range( ) function can be used in for loops to iterate over a
sequence of numbers.

Case-1 Case-2 Case-3


Case-4
x = list(range(5)) x = list(range(3,6)) x = list(range(3,20,2))
x = list(range(0, -9, -1))
print(x) print(x) Output print(x)
print(x)
Output [3, 4, 5] Output
Output
[0, 1, 2, 3, 4] [3, 5, 7, 9, 11, 13, 15,
[0, -1, -2, -3, -4, -5, -6, -7,
17,
8]
19]

Iteration/Repetition:
Repeated execution of a set of statements is called iteration.
Iteration means 'repetition'.
Iterative flow repeats statements in a block of code. Repetition or looping can be
performed a fixed number of times or until a certain condition is met.
This is accomplished through the use of iterative statements: for and while.

The for-statement (counting loop) and while- statements (conditional loop)can be used.
While loop: while loop keeps iterating a block of code defined inside it until the desired
condition is met.

Syntax: Example: Output:


while(expression): i=1 School
Statement(s) while i<=3: School
print("School")
School
i=i+1

For loop: for loop iterates over the items


of lists, tuples, strings, the dictionaries and
other iterable objects.
Syntax:
for <loopvariable> in <sequence>:
Statement(s)

Example 1: Example 2:
L = [ 1, 2, 3, 4, 5] for k in range(10):
for var in L:
print(k, end =’ , ‘)
print( var, end=’ ‘)
output:
Output is:
0,1,2,3,4,5,6,7,8,9
12345
Break and Continue Statement:

The break and continue statements are used to alter the flow of loops in Python.

Break Statement: The break statement is used to terminate a loop immediately. It is typically
used with conditional statements.

Continue Statement: The continue statement skips all the remaining statements in the current
iteration of the loop and moves the control to the beginning of the next iteration.
Break Continue
for i in range(1, 11): for i in range(1, 11):
if i == 5: if i == 5:
break # Exit the loop when i is 5 continue # Skip the iteration when i is 5
print(i) print(i)
output:
output:
1
2
3
4

You might also like