Python
History :
Inventor : GUIDD VAN ROSSUM
Year : 1991
Language : JAVA
Market trend 1985 till date ruled by java
Language : Python
Got popularity 2003/2004 used AI/ML
Rossum very much fascinated with a BBC comedy
Series “Monty Python’s flying circus”
Working with python
Pre-request
a) Install the python interpreter
[Link]
b) IDEL (Integrated Development Learning)
Python shell >>>
Start
> python 3.13
> IDEL (optional)
Open file New file
Quit() to kill the program
c) Prefer IDEs (Integrated Developer Environment)
PyCharm – [Link]
Developer tools
PyCharm
Downloads
Save
Create a project
Right click new file python file
Spider
Jupiter notebook ([Link])
Google co labs etc
LEXCIAL STRUCTURE
1) Linear structure:
python is a lined structured programming
language. All your python codes are divided into
physical and logical lines.
2) Line structure:
Identifiers are the names given to python
objects, which includes variables, functions,
classes, methods etc.
Ex: x=10
def factorial (n)
………..
Class single LinkedList:
Def create_list (self, node):
………….
The naming convention includes a combination of the alphabets (upper &
lower case), digits, underscores (__). It uses a naming convention called
SNAKE CASE convention-words separated by underscores.
3) Line terminals
The default line terminal in python is a new line
character
4) No expiate types
Python does not requires explicit type
declaration. Implicitly the type of object is
decided, based on the content assigned to it
Ex: a=10
Assign the type ‘class<int>’ to ‘a’ based on the
value ‘10’.
5) Literals
Constants are referred as literals
Literals can be classified into several types
Integers ex: 10, 20, -10, -20
Floating point ex: 25.35, 10.60, -2.50
String literals
EX:
I. Single quotes: ‘YUSUF’
II. Double quotes: “YUSUF”
III. Triple quotes: “’YUSUF”’
Format
Number j
Number i + number 2j
6) Comments
Specified with “#” to comment an entire passage,
select the passage and type “ctrl /”.
7) Output statement
Syntax
print (‘text’/variable)
Operators:
Arithmetic operators
o Addition – (+)
o Subtraction – (-)
o Multiplication – (*)
o Floating point – (/)
o Integer division – (//)
o Modular division – (%)
o Exponentiation – (**)
Ex:
a = 21
b = 10
c = a/b
print (“floating point division:”, c) # 2.1
c = a//b
print (“integer division:”, c) # 2
c=a%b
print (“modulus:”, c) # 1
c=2**3
print (“exponential value:”, c) # 8
Output statement
Syntax
print(‘text’/variable)
ex:
branches = ‘CSE – 3/ IT – 3’
language = ‘python’
trainer = ‘Patrick’
print(branches, ‘are exploring’, language, ‘with Mr.’, trainer)
output
CSE – 3 are exploring python with Mr. patrick.
Problem statement (01)
The rates for adults and children for a round trip flight Mumbai Dubai
Mumbai are as follows
Rate for adults – 37750.00
Rate for child – 1/3rd of the rate per adult
The service tax for 7% is calculated on the total ticket cost. As it was a
holiday season a discount of 10% was given on the total ticket cost (which
includes the service tax)
Program
adult = 5
children = 2
rate_per_adult = 37750
rate_per_children = 1/3 * rate_per_adult
total_cost = (5 * rate_per_adult) + (2 * rate_per_children)
service = 7/100 * total_cost
total_cost = total_cost + service
discount = 10/100 * total_cost
total_cost = total_cost - discount
print('total_cost',total_cost)
Providing input()
Use the following called “input ()”
Syntax: variable = input()
Example program for input()
Branches = input()
Language = input()
Trainer = input()
Print(‘branches’, are exploring ‘language’, ‘with ‘,trainer)
Note:
The problem with input() is that whatever value you read gets
stored even when you read numbers, they are stored as strings
hence, they are unfit for mathematical operations
To overcome the above problem use appropriate conversion
functions
1) int()
Coverts a number stored as string to an integer type
Syntax:
Int(integer_as_string)
Ex:
print('enter a number')
x=input()
y=input()
p=int(x)
q=int(y)
z=p+q
print('sum:',z)
2) float()
Converts a number stored as a string to a float type
Syntax:
Float(number_as_string)
Ex:
print('enter tow numbers')
p=float(input())
q=float(input())
z=p+q
print('sum:',z)
3) str()
Converts a number to a string
Syntax:
Str(number)
Ex:
print('enter two numbers')
p = float(input())
q = float(input())
z=p+q
print('sum :'+ str(z))
There are M cars and N bikes moving on a highway. Count the total
number of tires available on the highway road M,N
Program
M = int(input())
N = int(input())
total_tires = (M * 4) + (N * 2)
print('total tyres :',total_tires)
Lohith attempted a coding contest which contained ‘p’ easy questions, ‘q’
moderate questions & ‘r’ difficult questions easy questions carries 2
points each, moderate question carries 5 points each, difficult questions
carries 10 points each calculate the total score obtained by Lohith (read
p, q, r as space separated floating point values)
Program
p,q,r = map(float,input().split())
total_score = (p * 2) + (q * 5) + (r * 10)
print('total_score:',total_score)
4) Relational operators: <, >, >=, <=, ==, !, =, is, in
5) Logical operators: and, or, not
6) Assignment operators: =, +=, -=, *=, /=, //=, %=, **=
CONTROL FLOW
Control the flow of the scripts
1) If
2) Match case [3.10 onwords]
3) While
4) Break
5) Continue
1) If-statement
Evaluate conditions in a script
Syntax [1 simple-if ]
If expression :
Statements
Problem ATM [[Link]]
x,y = map(float,input().split())
if x%5==0 && x<y
y = y – x – 0.05
print(y)
Syntax [2 if-else]
If expression:
Statements
Else statements
Syntax [3 if-else-if]
If expression:
Statements
Elseif expression:
Statements
Elseif expression:
Statements
………
Else
Statements
1) Problem: GRADE THE STEEL
hardness, carbon_content, tensile_strength = map(float, input().split())
if hardness > 50 and carbon_content < 0.7 and tensile_strength > 5600:
grade = 10
elif hardness > 50 and carbon_content < 0.7:
grade = 9
elif carbon_content < 0.7 and tensile_strength > 5600:
grade = 8
elif hardness > 50 and tensile_strength > 5600:
grade = 7
elif hardness > 50 or carbon_content < 0.7 or tensile_strength > 5600:
grade = 6
else:
grade = 5
print(grade)
2) An electrical board charges its consumer a bill based on the
following criteria
Units consumed Rate per unit
First 100 units Rs: 3
Next 200 units Rs: 5
Above 300 units Rs: 8
Read the number of units consumed and compute the bill om the
customer
Sol:
units = int(input())
if units <= 100:
bill = units * 3
elif units <= 300:
bill = (100 * 3) + ((units - 100) * 5)
else:
bill = (100 * 3) + (200 * 5) + ((units - 300) * 8)
print(bill)
3) Problem: FOOD CORNER HOME
Sol:
food_type = input()
quantity = int(input())
distance = int(input())
if food_type == "veg" or food_type == "non-veg" and quantity
> 0 and distance > 0:
if food_type == "veg":
bill = quantity * 120
else:
bill = quantity * 150
if distance > 3:
bill += bill + (distance - 3) * 3
else:
bill += 9 + (distance - 6) * 6
print(bill)
else:
print(-1)
--------------------------------- (OR) -----------------------------------
food_type = input()
quantity = int(input())
distance = int(input())
bill = -1
if food_type in ['v', 'n-v'] and quantity >= 1 and distance > 0
if food_type == 'v':
food_cost = quantity * 120
else:
food_cost = quantity * 150
if distance <= 3:
dc = 0
elif distance <= 6:
dc = (distance - 3) * 3
else:
dc = (3 * 3) + ((distance - 6) * 6)
bill = food_cost + dc
print(bill)
3) While:
Syntax:
While expression:
Statements…
Ex: print first 10 natural numbers
i=1
while i <= 10:
print (i)
i=i+1
# when uh want to put in single line
i=1
while i <= 10:
print (i,end = ' ')
i += 1
Factorial of a number:
print("read a number:")
n = int(input())
fact = 1
while n > 1:
fact *= n
n -= 1
print("factorial value:", fact)
Find the sum of individual digits of multidigit number..??
Sol: print("read a number:")
n = int(input())
s=0
while n != 0:
r = n % 10
s=s+r
n = n // 10
print("sum of the digits:",s)
Count the number of digits in a multidigit number….??
Sol:
print("read the number:")
n = int(input())
c = len(str(n))
print("digits:",c)
ISBN Problem (Book of potion making) [Link]
print("read a number:")
isbn = int(input())
while isbn != 10:
isbn = int(input())
if(len(str(isbn))) == 10:
d=0
s=0
while isbn != 0:
r = isbn % 10
s = s + (r * d)
isbn = isbn // 10
d=d-1
if s % 11 == 0:
print("legal isbn")
else:
print("illegal isbn")
else:
print("not s 10 digit number")
Check for a prime number
A prime number is one which has only two factors i.e (1 & itself)
num = int(input())
x=1
factors = 0
while x <= num:
if num % x == 0:
factors += 1
x += 1
if factors == 2:
print("a prime number")
else:
print("not a prime number")
PRIME MINISTERS NUMBER ([Link])
a, b = map(int, input().split())
while a <= b:
n=a
f1 = 0
x=1
while x <= n:
if n % x == 0:
f1 += 1
x += 1
if f1 == 2:
temp = n
s=0
while temp != 0:
s += temp % 10
temp //= 10
f2 = 0
x=1
while x <= s:
if s % x == 0:
f2 += 1
x += 1
if f2 == 2:
print(a, end=" ")
a += 1
Ecommerce offer:
bill = int(input())
se = 0
so = 0
while bill != 0:
r = bill % 10
if r % 2 == 0:
se = se + r
else:
so = so + r
bill = bill // 10
if se == 0 or so == 0:
print(se + so)
else:
print(se * so)
4) For:
Syntax:
For<variable>in<iterable>:
Statements
Iterable:
Indicates a python object on which you can iterable.
It can be a list, set, tuple, dictionary, strong or the range()
Ex 1: numbers = [10,20,30,40,50]
For num in numbers:
int(num)
Ex 2:college_name = ‘ALIET’
C=0
For x in college_name:
If x in [‘’A’,’E’,’I’,’O’,’U’,’a’,’e’,’i’,’o’,’u’]:
C+=1
Print(‘vowels:’,c)