Un2 - CH - Basics of Pyhton To Flow of Control - Shnotes
Un2 - CH - Basics of Pyhton To Flow of Control - Shnotes
SHORT NOTES
COMPUTER SCIENCE-(083)
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:
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.
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.
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
Assignment operators:
Variables are assigned values using assignment operators.
Example :
sum = 5 + x
result += 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.
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.")
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.
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