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

Introduction of Python, Operators, Conditional Statements

The document provides an overview of Python, detailing its history, features, and basic programming concepts. It covers the evolution of Python from its inception in the late 1980s by Guido Van Rossum to its latest versions, along with methods to run Python scripts and fundamental programming constructs such as variables, data types, and operators. Additionally, it explains Python's syntax, including comments, identifiers, input/output functions, and the significance of indentation.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Introduction of Python, Operators, Conditional Statements

The document provides an overview of Python, detailing its history, features, and basic programming concepts. It covers the evolution of Python from its inception in the late 1980s by Guido Van Rossum to its latest versions, along with methods to run Python scripts and fundamental programming constructs such as variables, data types, and operators. Additionally, it explains Python's syntax, including comments, identifiers, input/output functions, and the significance of indentation.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 60

Introduction

• Python is a general purpose, interpreted and high-level


programming language
• It’s design philosophy emphasizes code readability.
• Its syntax are said to be clear and expressive.
• Python interpreters are available for many operating systems.
• Like Java, once written, programs can be run on any operating
system.

T Seshu Chakravarthy Department Of Computer Science and Engineering


History
• The history of Python starts with ABC.
• Python was conceptualized by Guido Van Rossum in the late
1980s.
• It was in late 1980’s, when Guido van Rossum came up with an
idea to develop a programming language while working in
CWI(Centrum Wiskunde and Informatica), Amsterdam, for a
project named Amoeba which is a distributed operating system.
• He along with his team was using ABC language for their project
which was not able to handle exceptions and interface with the
Amoeba Operating System.

T Seshu Chakravarthy Department Of Computer Science and Engineering


History
• In December, 1989, he actually started implementing his ideas to
develop a new programming language that is capable of exception
handling with several other programming paradigms.
• Rossum being a big fan of a British sketch comedy series, Monty
Python’s Flying Circus, named the language as Python.
• Python came into sight on 20 Feb, 1991 for the very first time with
a version 0.9.0.

T Seshu Chakravarthy Department Of Computer Science and Engineering


T Seshu Chakravarthy Department Of Computer Science and Engineering
T Seshu Chakravarthy Department Of Computer Science and Engineering
History
• Python 0.9.0 - February 20, 1991
• Python 1.0 - January 1994
• Python 2.0 - October 16, 2000
• Python 3.0 - December 3, 2008
• Python 3.7 - June 27, 2018
• Python 3.11 -November 2022,
• Python 3.12.0 2 October 2023

T Seshu Chakravarthy Department Of Computer Science and Engineering


T Seshu Chakravarthy Department Of Computer Science and Engineering
Running Python scripts

Method One: Interactive Mode


• The most basic way to run code is to enter and run lines of code in
the Terminal.
• start Python by typing in python at the $ command prompt, type
in print "Hello and hit enter.
Ex :
• >>> print(“hello”)
o/p :hello

T Seshu Chakravarthy Department Of Computer Science and Engineering


Running Python scripts

Method 2: Running a Python Script in the Terminal


• Python code is written in plain text files, typically given a “.py”
extension.
• Open up a Terminal window. Let’s say you saved your script with
the name hello_world.py in your Documents folder.
• Navigate to the Documents folder by typing in cd Documents and
hit enter.
• Then to run your code type in python hello_world.py and hit
enter. Your code will run and you’ll see the output.
$python hello_world.py
T Seshu Chakravarthy Department Of Computer Science and Engineering
Running Python scripts

Method 3: Running a Python Script in Jupyter notebook

Install the classic Jupyter Notebook with:


pip notebook

To run the notebook:


jupyter notebook

T Seshu Chakravarthy Department Of Computer Science and Engineering


Example Program

name="Devansh"
age=6
print("Name:",name)
print("Age:",age)

T Seshu Chakravarthy Department Of Computer Science and Engineering


program to convert height in feet and inches to cm. [1 feet = 12
inch and 1 inch= 2.54 cm

print("Input your height: ")


h_ft = int(input("Feet: "))
h_inch = int(input("Inches: "))
h_inch += h_ft * 12
h_cm = round(h_inch * 2.54, 1)
print("Your height is : %d cm." % h_cm)

T Seshu Chakravarthy Department Of Computer Science and Engineering


Comments in python
Single line comments:
• # This would be a comment in Python
Multi line comments:
• “””” This would be a multiline comment in Python that spans
several lines and describes your code, your day, or anything you
want it to … “””

T Seshu Chakravarthy Department Of Computer Science and Engineering


Variables
• A Python variable is a reserved memory location to store values.
• A variable is a symbolic name for this physical location.
• This memory location contains values, like numbers, text or more
complicated types.
i = 42
S=“hi”
Z=10.5

T Seshu Chakravarthy Department Of Computer Science and Engineering


Cont ..
Ex:
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print (counter)
print (miles)
print (name)

T Seshu Chakravarthy Department Of Computer Science and Engineering


Python Identifiers

• Identifier is the name given to entities like class, functions,


variables etc. in Python.
• It helps differentiating one entity from another.
Rules for writing identifiers or variables
• Identifiers can be a combination of letters in lowercase (a to z) or
uppercase (A to Z) or digits (0 to 9) or an underscore (_).
• An identifier cannot start with a digit.
• Keywords cannot be used as identifiers.
• We cannot use special symbols like !, @, #, $, % etc. in identifier

T Seshu Chakravarthy Department Of Computer Science and Engineering


Input and output
• input() and print() are widely used for standard input and output
operations respectively.
• print() function is used to output data to the standard output
device (screen).
Syntax:
Print(variable)
Ex:
a=5
Print(a) or print(“value of c is”,c)

T Seshu Chakravarthy Department Of Computer Science and Engineering


Input and output
• Input() function is used to read the input form the user.
variable=input(“Enter Value ”)
• By default type of entered value is string.
• int() or float() functions are used convert this string number in to
integer or float.
a=input(“enter a value”)
a=int(a) or a=float(a)

T Seshu Chakravarthy Department Of Computer Science and Engineering


Keywords in python
• There are 33 keywords in Python 3.3.
• Keywords are the reserved words in Python. We cannot use a
keyword as variable name, function name or any other identifier.
Keywords in Python programming language
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise

T Seshu Chakravarthy Department Of Computer Science and Engineering


Indentation in python

• A block is a group of statements in a program or script.


• Python does not use braces({}) to indicate blocks of code for class
and function definitions or flow control.
• In python Blocks of code are denoted by line indentation.
• Python programs get structured through indentation, i.e. code
blocks are defined by their indentation.

T Seshu Chakravarthy Department Of Computer Science and Engineering


Cont …

• All statements with the same distance to the right belong to the
same block of code.
• If a block has to be more deeply nested, it is simply indented
further to the right.
• Leading whitespace (spaces and tabs) at the beginning of a logical
line is used to compute the indentation level of the line, which in
turn is used to determine the grouping of statements.

T Seshu Chakravarthy Department Of Computer Science and Engineering


Cont …

• Ex:
a=input("enter a")
b=input("enter b")
if a>b:
print('a is big')
print("hi")
else:
print("b is big")

T Seshu Chakravarthy Department Of Computer Science and Engineering


Basic Data types in Python
• Every value in Python has a data type.

T Seshu Chakravarthy Department Of Computer Science and Engineering


Basic Data types in Python
1.Integers (int): Whole numbers, such as -5, 0, 42.
2.Floating-Point Numbers (float): Numbers with a decimal point, such as -3.14, 2.718.
3.Strings (str): Sequences of characters, enclosed in single (' ') or double (" ") quotes.
For example, "Hello, World!".
4.Booleans (bool): Represents either True or False, often used for logical operations.
5.Lists (list): Ordered collections of items that can be of different data types. Lists are
mutable (can be changed after creation). Example: [1, 2, 3, "apple"].
6.Tuples (tuple): Similar to lists, but immutable (cannot be changed after creation).
Example: (1, 2, 3, "apple").
7.Dictionaries (dict): Key-value pairs, where each key maps to a value.
Example: {"name": "John", "age": 30}.
8.Sets (set): Unordered collections of unique elements. Example: {1, 2, 3}.
9.Complex Numbers (complex): Numbers with a real and an imaginary part. Example: 1 + 2j.

T Seshu Chakravarthy Department Of Computer Science and Engineering


Data types
• We can use the type() function to know type a variable.
Ex:
a= 5
b = 2.0
c = 1+2j
d = "Hi"
e=[1,2,"bye"]
f=(5,6,1.2)
g={8,9,20}
Output:
h={"name":"Ram","id":70459}
5 is of type: <class 'int'>
print(a, "is of type:", type(a)) 2.0 is of type: <class 'float'>
print(b, "is of type:", type(b)) (1+2j) is of type : <class 'complex'>
print(c, "is of type :", type(c)) Hi is of type: <class 'str'>
print(d, "is of type:", type(d)) [1, 2, 'bye'] is of type: <class 'list'>
print(e, "is of type:", type(e)) (5, 6, 1.2) is of type : <class 'tuple'>
print(f, "is of type :", type(f))
{8, 9, 20} is of type : <class 'set'>
{'name': 'Ram', 'id': 70459} is of type : <class 'dict'>
print(g, "is of type :", type(g))
T Seshu Chakravarthy
print(h, "is of type :", type(h)) Department Of Computer Science and Engineering
Python Operators

• Operators are used to perform operations on variables(operands).


Python provides the following operators:
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Identity operators
6. Membership operators
7. Bitwise operators

T Seshu Chakravarthy Department Of Computer Science and Engineering


Arithmetic Operators

• Arithmetic operators are used with numeric values to perform


common mathematical operations

T Seshu Chakravarthy Department Of Computer Science and Engineering


Arithmetic Operators

x=5
y=2
print('Addition=',x+y)
print('subtraction =',x-y)
print('multiplication =',x*y)
print('division =',x/y) Output:
Addition= 7
print('Floor dvision =',x//y) subtraction = 3
multiplication = 10
print('Remainder =',x%y) division = 2.5
print('Exponentiation =',x**y) Floor dvision = 2
Remainder = 1
Exponentiation = 25

T Seshu Chakravarthy Department Of Computer Science and Engineering


Assignment Operators

• Assignment operators are used to assign values to variables:

T Seshu Chakravarthy Department Of Computer Science and Engineering


Comparison/Relational Operators

• Comparison operators are used to compare two values:


• It either returns True or False according to the condition.

T Seshu Chakravarthy Department Of Computer Science and Engineering


Comparison Operators

x = 10
y = 12
print('x > y is',x>y)
print('x < y is',x<y)
print('x == y is',x==y)
print('x != y is',x!=y)
print('x >= y is',x>=y)
print('x <= y is',x<=y)

T Seshu Chakravarthy Department Of Computer Science and Engineering


Logical Operators

• Logical operators are used to combine conditional statements

Ex:
x=5

print(x > 3 and x < 4)


print(x > 3 or x < 4)
print(not(x==5))

Output:
False
True
False
T Seshu Chakravarthy Department Of Computer Science and Engineering
Membership operators

• They are used to test whether a value or variable is found in a


sequence (string, list, tuple, set and dictionary).
• In a dictionary we can only test for presence of key, not the
value.

T Seshu Chakravarthy Department Of Computer Science and Engineering


Membership operators

x = 'Hello world'
print('H' in x)
print('S' in x)
print('Hello' not in x)

Output:
True
False
False

T Seshu Chakravarthy Department Of Computer Science and Engineering


Bitwise operators
• These operators act upon the individual bits (0 & 1) of their
operands.
• It operates bit by bit, hence the name.
• For example, 2 is 10 in binary and 7 is 111.

1. Bitwise AND (&)


2. Bitwise OR (|)
3. Bitwise XOR (^)
4. Bitwise Complements (~)
5. Bitwise Left shift (<<)
6. Bitwise Right shift (>>)
T Seshu Chakravarthy Department Of Computer Science and Engineering
Bitwise operators
int x=10; int y=11;
X: 0000 1010
Y: 0000 1011
X&Y : 0000 1010
result is 10
X: 0000 1010
Y: 0000 1011
X|Y : 0000 1011
result is 11
X: 0000 1010
Y: 0000 1011
X^Y : 0000 0001
result is 1
a = 0011
~a = 1100

T Seshu Chakravarthy Department Of Computer Science and Engineering


Bitwise operators
Bitwise Left Shift Operator «
• This operator shifts the bits of the number towards left a
specified number of positions.

X<<n=x*2n

X=10;
X<<2=10x22
=10x4= 40

Bitwise Right Shift Operator (»)


• This operator shifts the bits of the number towards right a
specified number of positions.
X=10;
X>>n=x/ 2n
X>>2=10/22
=10/4=2

T Seshu Chakravarthy Department Of Computer Science and Engineering


Identity operators
• is and is not are the identity operators in Python.

Ex:
a1 = 3
b1 = 3

print(a1 is b1)
print(a1 is not b1)

T Seshu Chakravarthy Department Of Computer Science and Engineering


Precedence and Associativity of Operators
in Python

• Operators have different levels of precedence, which determine the order in which
they are evaluated.
• When multiple operators are present in an expression, the ones with higher
precedence are evaluated first.
• In the case of operators with the same precedence, their associativity comes into play,
determining the order of evaluation.

What is the value of below expression?


10 + 20 * 30

T Seshu Chakravarthy Department Of Computer Science and Engineering


Precedence and Associativity of Operators
in Python
Precedence Operators Description Associativity
1 () Parentheses Left to right
2 ** Exponentiation Right to left
3 ~x bitwise NOT Right to left
Multiplication, matrix, division, floor division,
4 *, @, /, //, % Left to right
remainder
5 +, – Addition and subtraction Left to right
6 <<, >> Shifts Left to right
7 & Bitwise AND Left to right
8 ^ Bitwise XOR Left to right
9 | Bitwise OR Left to right
in, not in, is, is not, <, <=, >, >=, !
10 Comparisons, membership tests, identity tests Left to Right
=, ==
11 and logical AND Left to right
12 or Logical OR Left to right
18 := Assignment expression (walrus operator) Right to left

T Seshu Chakravarthy Department Of Computer Science and Engineering


Precedence and Associativity of Operators
in Python
2. 100 / 10 * 10

In this expression ‘*’ and ‘/’ have the same


precedence and their associativity is Left to Right,
so the expression “100 / 10 * 10” is evaluated as

=(100 / 10) * 10
=10*10
value=100

3. What is the value of 100 + 200 / 10 - 3


* 10
4. What is the value of 4+3*2&4|6

T Seshu Chakravarthy Department Of Computer Science and Engineering


What is the value of 100 + 200 / 10 - 3 * 10

1.First, perform the multiplication and division:


1. 200 / 10 = 20
2. 3 * 10 = 30
2.Then, perform the addition and subtraction from left to right:
1. 100 + 20 = 120
2. 120 - 30 = 90
So, the value of the expression "100 + 200 / 10 - 3 * 10" is 90.

What is the value of 4+3*2&4|6

1.Multiplication: 3 * 2 = 6
2.Addition: 4 + 6 = 10
3.Bitwise AND: 10 & 4 = 0 (In binary, 10 is 1010 and 4 is 0100. The result of a
bitwise AND is 0 where there are differing bits.)
4.Bitwise OR: 0 | 6 = 6 (In binary, 0 is 0000 and 6 is 0110. The result of a bitwise OR
is 1 where there is at least one 1.)
So, the final result of the expression is 6.

T Seshu Chakravarthy Department Of Computer Science and Engineering


Evaluate the expression step by step according to operator precedence
and associativity and print the final output for x = 10 and y = 50 x ** 2
> 100 and y < 100

Let's evaluate it step by step:


1.Evaluate x ** 2:
•x = 10
•x ** 2 = 10 ** 2 = 100
2.Evaluate y < 100:
•y = 50
•y < 100 is true because 50 is indeed less than 100.
3.Now, we have 100 > 100 and True. To evaluate the and operator, we need both sides to be
True for the whole expression to be True. Since the first part, 100 > 100, is False (because
100 is not greater than 100), the whole expression is False.
So, the final output for x = 10 and y = 50 is False.

T Seshu Chakravarthy Department Of Computer Science and Engineering


Write a python program which prompts a user to enter the Basic salary to calculate the Total salary of an
Employee considering the bonus and conveyance offered to him. Display the Total salary with two digits after
the decimal point.
HRA = 20% of Basic
DA = 105 % of Basic
Conveyance = Rs1300
Bonus = Rs1000 Code:
# Get the basic salary from the user

basic_salary = float(input("Enter the Basic salary: "))

hra = 0.20 * basic_salary


da = 1.05 * basic_salary
conveyance = 1300
bonus = 1000
total_salary = basic_salary + hra + da + conveyance + bonus

print(f"Total Salary: {total_salary:.2f}")

T Seshu Chakravarthy Department Of Computer Science and Engineering


Decision making (or) conditional Statements
• Decision making is required when we want to execute a code
only if a certain condition is satisfied.
1. The if statement
2. The if else statement
3. if...elif...else Statement
4. Nested if statements

T Seshu Chakravarthy Department Of Computer Science and Engineering


if statement
Syntax:
if test expression:
statement(s)

• Here, the program evaluates the test expression and will execute
statement(s) only if the text expression is True.
• If the text expression is False, the statement(s) is not executed.
• In Python, the body of the if statement is indicated by the indentation.
• Body starts with an indentation and the first unindented line marks
the end.
T Seshu Chakravarthy Department Of Computer Science and Engineering
if statement
num = 3
if num>0:
print(num, "is a positive number.")
print("This is always printed.")

T Seshu Chakravarthy Department Of Computer Science and Engineering


if...else Statement
Syntax:
if test expression:
Body of if
else:
Body of else
• The if..else statement evaluates test expression and will execute
body of if only when test condition is True.
• If the condition is False, body of else is executed.
• Indentation is used to separate the blocks.

T Seshu Chakravarthy Department Of Computer Science and Engineering


if...else Statement
no=input("enter number")
no=int(no)
if(no%5==0 and no%11==0):
print("number is divisible by 5 and 11")
else:
print("number is not divisible by 5 and 11")

T Seshu Chakravarthy Department Of Computer Science and Engineering


if...elif...else Statement
if condition1:
# Code to be executed if condition1 is True
elif condition2:
# Code to be executed if condition2 is True
else:
# Code to be executed if none of the conditions are True

• if...elif...else Statement allows you to execute different blocks of code based on specified
conditions.

T Seshu Chakravarthy Department Of Computer Science and Engineering


if...elif...else Statement
• If the condition for if is False, it checks the condition of the
next elif block and so on.
• If all the conditions are False, body of else is executed.
• Only one block among the several if...elif...else blocks is
executed according to the condition.
• The if block can have only one else block. But it can have
multiple elif blocks.

T Seshu Chakravarthy Department Of Computer Science and Engineering


if...elif...else Statement
a=int(input("enter numbers"))
b=int(input("enter numbers"))
c=int(input("enter numbers"))
if(a>b and a>c):
print(a,"is big")
elif b>c:
print(b,"is big")
else:
print(c,"is big")

T Seshu Chakravarthy Department Of Computer Science and Engineering


Nested if statement
• We can have a if...elif...else statement inside another
if...elif...else statement. This is called nesting in computer programming.
Example:
num = int(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
T Seshu Chakravarthy Department Of Computer Science and Engineering
Program:
signal=input ("enter signal")
if(signal=="red"):
print("STOP")
elif(signal=="orange"):
print ("Be slow")
elif(signal=="green"):
print ("to go")
else:
print("error")

T Seshu Chakravarthy Department Of Computer Science and Engineering


score=float(input("enter score"))
if(score>=0.9 and score<=1.0):
print("A")
elif(score>=0.8 and score<0.9):
print("B")
elif(score>=0.7 and score<0.8):
print("C")
elif(score>=0.6 and score<0.7):
print("D")
elif(score<0.6):
print("F")
else:
print("error")

T Seshu Chakravarthy Department Of Computer Science and Engineering


MRP=int(input("enter MRP"))
if(MRP>=1 and MRP<2000):
discount=0.05*MRP
elif(MRP>=2000 and MRP<5000):
discount=0.1*MRP
elif(MRP>=5000 and MRP<10000):
discount=0.15*MRP
elif(MRP>10000):
discount=0.2*MRP
else:
print("error")
amount=MRP-discount
GST=0.09*amount
paidamount=amount+GST
print("MRP Discount GST Paidamount")
print(MRP," ",discount," ",GST,"
",paidamount)

T Seshu Chakravarthy Department Of Computer Science and Engineering


# Get the month from the user
month = int(input("Enter a month (1-12): "))

# Check the month and determine the season


if month in [12, 1, 2]:
season = "Winter"
elif month in [3, 4, 5]:
season = "Spring"
elif month in [6, 7, 8]:
season = "Summer"
elif month in [9, 10, 11]:
season = "Autumn"
else:
season = "Invalid month"

print(season)

T Seshu Chakravarthy Department Of Computer Science and Engineering


T Seshu Chakravarthy Department Of Computer Science and Engineering
End

T Seshu Chakravarthy Department Of Computer Science and Engineering

You might also like