What is Python
Your answer may be, It is a Programming Language which is used to
make applications and softwares.
Actually, Python is a High-Level Programming Language.
Next question may arise: Sir What is High-Level
Programming Language.
High-Level means Programmer friendly Programming Language. This
means we are not required to worry about Low-level things [i.e., Memory
management, security, destroying the objects and so on.].
It is similar to skill of driving a car without bothring about what is tyre
pressure, engine specification etc. Let's see following example--------
In [3]: # following code is very simple and easy to understand without anyone knowing python cod
a = 10
b = 20
c = 30 if a>b else 40
print(c)
40
the above code works. this means Python is high level programming.
Python is a General Purpose High Level Programming
Language.
Here, General Purpose means Python is not specific to a particular area,
happily we can use Python for any type of application areas. For
example,
Desktop Applications
Web Applications
Data Science Applications
Machine learning applications and so on. ## Everywhere you can use Python.
Who Developed Python
Guido Van Rossum developed (in 1989) Python language while working in National Research Institute
(NRI) in Netherland.
Easiness of Python with other programming
language
Lets print 'Hello World' in C, JAVA and Python
in C
1) #include <stdio.h>
2) void main()
3) {
4) printf("Hello World");
5) }
in Java
1) public class HelloWorld
2) {
3) public static void main(String[] args)
4) {
5) System.out.println("Hello world");
6) }
7) }
In Python
In [3]: print("Hello World")
Hello World
Just to print 'Hello World',
C language takes 5 lines of code
Java takes 7 lines of code
But, Python takes only one line of code.
How to download Python
use following link to download Python
https://www.python.org/downloads/
Python as Scripting Language
Means a group of lines of code will be there and they will be executed
line by line.
for example
In [6]: print('Python is fun!!')
print(5+3)
print(f+3)
Python is fun!!
8
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[6], line 3
1 print('Python is fun!!')
2 print(5+3)
----> 3 print(f+3)
NameError: name 'f' is not defined
In above example first two prints executed properly while in 3rd print
command error occured. this means python read and execute code line
by line
Python Variables and Identifiers
A name in Python program is called identifier. It can be class name or
function name or module name or variable name.
Eg: a = 20
It is a valid Python statement. Here 'a' is an identifier.
Rules to define identifiers in Python:
The only allowed characters in Python are
1. alphabet symbols(either lower case or upper case)
2. digits(0 to 9)
3. underscore symbol(_)
In [2]: # example of an identifier
a=50
a_sum=20
a$hey=30 # $ is not allowed
Cell In[2], line 5
a$hey=30 # $ is not allowed
^
SyntaxError: invalid syntax
In [4]: python987='how are you'
987python='how are you' # identifier should not start with digit
Cell In[4], line 2
987python='how are you' # identifier should not start with digit
^
SyntaxError: invalid syntax
In [18]: # Identifiers are case sensitive.
total=10
TOTAL=999
print(total) #10
print(TOTAL) #999
10
999
Keywords in python
In Python some words are reserved to represent some meaning or
functionality. Such type of words are called
Reserved words.
There are nearly 35 reserved words available in Python.
following code ask python to list all its reserved words (Keywords)
In [6]: import keyword
print(keyword.kwlist)
['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 'async', 'await', 'br
eak', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'fr
om', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'r
aise', 'return', 'try', 'while', 'with', 'yield']
In [2]: # keywords should not be used for identifier they are reserved by python
for=5
print(for)
Cell In[2], line 2
for=5
^
SyntaxError: invalid syntax
Let's write some codes
In [7]: # Python program to display data of different types using variables and constants
num=15
amount=256.87
code='A'
pi=3.1415926536
population_of_India=1400000000
your_message='hey!'
print("num= "+str(num))
print("Amount= "+str(amount))
print("CODE= "+code)
print("\nPopulation of India is : "+str(population_of_India))
print("\nMessage: "+your_message)
# you can reassign variables as many times as you want
num= 15
Amount= 256.87
CODE= A
Population of India is : 1400000000
Message: hey!
In [15]: # Multiple assignment in Python
su=flag=a=b=0 # all these variables will have zero value
print(flag)
su,a,b,mesg,flag=0,52,37.5,'waw','awesome' # each variables will have their respective
print(mesg)
0
waw
Input Operation in Python
In [6]: name=input("Please enter your name: ")
print("hello "+ name+ " !" +" \nhow are you?")
print(type(name))
Please enter your name: rahul
hello rahul !
how are you?
<class 'str'>
In [5]: # In, Python every input value is treated as str type only.
x=input("Enter your lucky number:")
y=input("what is your percentange in SSC: ")
print(type(x))
print(type(y))
Enter your lucky number:15
what is your percentange in SSC: 78.5
<class 'str'>
<class 'str'>
Following code shows method of Reading multiple values
from the keyboard in a single line
In [13]: # Reading multiple values from the keyboard in a single line
a,b= [int(x) for x in input("Enter 2 numbers :").split()]
print("The Sum is :", a + b)
Enter 2 numbers :200 50
The Sum is : 250
Explanation of above code:
Here, we are using only one input function (i.e., input("Enter 2 numbers :")). So what ever you provide it
is treated as only one string.
Suppose, you are provinding input as 200 50, this is treated as single string.
If you want to split that string into multiple values, then we required to use split() function .
If we want to split the given string (i.e., 10 20) with respect to space, then the code will be as follows:
input('Enter 2 numbers :").split()
Here, we are not passing any argument to split() function, then it takes default parameter (i.e., space) as
seperator.
Now this single string(i.e.,200 50) is splitted into list of two string values.
Now the statement : input('Enter 2 numbers :").split() returns ['10','20']
Now, in the list every number is available in string form.
So, what we will do here is, each value present in this list is typecast to 'int' value. [int(x) for x in
input('Enter 2 numbers :").split()] ===> it retrns [10,20]
This concept is known as list comprehension.
a,b = [int(x) for x in input('Enter 2 numbers :").split()] ===> it assigns 10 to a and 20 to b. This concept
is called as list unpacking.
a,b = [int(x) for x in input('Enter 2 numbers :").split()]
print('Sum is : ',a + b) ====> Gives the sum of two values as the result.
In [14]: s = input("Enter 2 numbers :")
print(s,type(s)) # s holds single value '10 20'
l = s.split() # After split, single string will be divided into list of two valu
print(l)
l1 = [int(x) for x in l] # This new list contains two int values after typecastig of e
print(l1)
a,b = l1 # in this list wahtever the values are there, assigns first value to 'a' and
#This is called 'list unpacking'.
print(a)
print(b)
print('Sum is :', a+b)
Enter 2 numbers :40 30
40 30 <class 'str'>
['40', '30']
[40, 30]
40
30
Sum is : 70
Output operation in Python
Syntax: print(value, sep= ‘ ‘, end = ‘\n’)
In [10]: # Python program to demonstrate print() method
print("ABCD")
print('A', 'B', 'C', 'D')
print('A', 'B', 'C', 'D',sep=" $ ") # each value is seperated by $
print('G', 'F', 'G', sep="#",end = "+") # since end is not \n hence new print will sta
print("Python is fun")
ABCD
A B C D
A $ B $ C $ D
G#F#G+Python is fun
In [18]: print(10,20,30,sep = ':', end = '***')
print(40,50,60,sep = ':') # default value of 'end' attribute is '\n'
print(70,80,sep = '**',end = '$$')
print(90,100)
10:20:30***40:50:60
70**80$$90 100
In [13]: # Python String formatting using F/f string
name="upendra"
password=1234
sport="kabaddi"
print(f"hey {name}!, your favourite sports is {sport} and your passowrd is {password}")
hey upendra!, your favourite sports is kabaddi and your passowrd is 1234
In [14]: # Python string formatting using format() function
name="upendra"
password=1234
sport="kabaddi"
print("hey {}!, your favourite sports is {} and your passowrd is {}".format(name,passwor
hey upendra!, your favourite sports is 1234 and your passowrd is kabaddi
In [15]: # you can use both method in same program and everywhere
name="upendra"
password=1234
sport="kabaddi"
print(f"hey {name}!, your favourite sports is {sport} and your passowrd is {password}")
print("hey {}!, your favourite sports is {} and your passowrd is {}".format(name,sport,p
hey upendra!, your favourite sports is kabaddi and your passowrd is 1234
hey upendra!, your favourite sports is kabaddi and your passowrd is 1234
** TypeCasting **
Input() takes values in string data type.
Which is not always desirable and sometimes we may need to convert it.
Mainly type casting can be done with these data type functions:
1. Int(): Python Int() function take float or string as an argument and returns int type object.
2. float(): Python float() function take int or string as an argument and return float type object.
3. str(): Python str() function takes float or int as an argument and returns string type object.
Lets see following example
In [4]: # Why we need type casting.
# lets see with example
number_1=input("Please enter your any number: ")
number_2=input("Please enter second number to add: ")
total=number_1+number_2 # python consider these two numbers as text and
# just keep them side by side without actually addin
print(total)
# lets use typecasting before adding it
total=int(number_1)+int(number_2) # Python convert string into integer and then add
print(total)
Please enter your any number: 10
Please enter second number to add: 20
1020
30
In [7]: # we can typecast at the start of the input
x=int(input("Enter First Number:"))
y=int(input("Enter Second Number:"))
print("The Sum:",x+y)
Enter First Number:15
Enter Second Number:25
The Sum: 40
In [8]: # We can write the above code in single line also
print("The Sum:",int(input("Enter First Number:"))+int(input("Enter Second Number:")))
Enter First Number:15
Enter Second Number:25
The Sum: 40
Write a program to read 3 float numbers from the keyboard
with , seperator and print their sum.
In [17]: take_input_list=input("enter 3 float numbers with , seperator: ")
seperate_list_content=take_input_list.split(',')
a,b,c=[float(x) for x in seperate_list_content]
print("The Sum is :", a+b+c)
enter 3 float numbers with , seperator: 14,85,75.5
The Sum is : 174.5
Program to take input from user and give age
In [17]: # Program to take input from user and give age
current_year=2024
year_of_birth=input("Please enter your year of Birth: ") # Python will consider this s
age=current_year-int(year_of_birth)
print("You must be "+str(age)+" years old")
Please enter your year of Birth: 1990
You must be 34 years old
Write a python program to calculate area of a triangle using
Heron's Formula
In [20]: # Write a python program to calculate area of a triangle using Heron's Formula
# Heron's formula is given
# area=sqrt(S*(S-a)*(S-b)*(S-c))
a=float(input("Enter the first side of the triangle: "))
b=float(input("Enter the second side of the triangle: "))
c=float(input("Enter the third side of the triangle: "))
print(a,b,c)
S=(a+b+c)/2
area=((S*(S-a)*(S-b)*(S-c))**0.5)
print("Area is "+str(area))
Enter the first side of the triangle: 5
Enter the second side of the triangle: 5
Enter the third side of the triangle: 5
5.0 5.0 5.0
Area is 10.825317547305483
In [22]: # Write a python program to print the unit digit of any number
# hint: if you divide given number by 10, the reminder will be the unit digit
num=int(input("enter any number: "))
unit_digit=num%10
print("the unit digit is :"+str(unit_digit))
enter any number: 145
the unit digit is :5
Write a Program to calculate average of two numbers, also
print their deviation
In [26]: # Write a Program to calculate average of two numbers, also print their deviation
num_1=int(input("enter the first number to be divided: "))
num_2=int(input("enter the second number which divides: "))
avg=(num_1+num_2)/2
dev_1=num_1-avg
dev_2=num_2-avg
print("the average is: "+str(avg))
print("Deviation of first num: "+str(dev_1))
print("Deviation of second number: "+str(dev_2))
enter the first number to be divided: 25
enter the second number which divides: 45
the average is: 35.0
Deviation of first num: -10.0
Deviation of second number: 10.0
Python program to calculate Simple and Compound Interest
In [2]: # Python program to calculate Simple and Compound Interest
# Reading principal amount, rate and time
principal = float(input('Enter amount: '))
time = float(input('Enter time in Years: '))
rate = float(input('Enter interest rate: '))
# Calcualtion
simple_interest = (principal*time*rate)/100
compound_interest = principal * ( (1+rate/100)**time - 1)
# Displaying result
print('Simple interest is: %f' % (simple_interest))
print('Compound interest is: %f' %(compound_interest))
Enter amount: 10000
Enter time in Years: 5
Enter interest rate: 8
Simple interest is: 4000.000000
Compound interest is: 4693.280768
In [ ]:
Python Libraries
A Python library is a collection of related modules. It contains bundles of
code that can be used repeatedly in different programs. It makes Python
Programming simpler and convenient for the programmer. As we don’t
need to write the same code again and again for different programs.
Python libraries play a very vital role in fields of Machine Learning, Data
Science, Data Visualization, etc.
Lets see with an example
In [11]: # Suppose we want to take square root of any given number
print(sqrt(24))
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[11], line 3
1 # Suppose we want to take square root of any given number
----> 3 print(sqrt(24))
NameError: name 'sqrt' is not defined
In [14]: # Lets import numpy library for the same operation
import numpy as np # importing numpy library
print(np.sqrt(24))
# now python will use sqrt() of numpy library and work
4.898979485566356
In [1]: # Lets see one more library called Matplotlib
import matplotlib.pyplot as plt # importing the matplotlib library
# Data for the pie chart
labels = ['Geeks 1', 'Geeks 2', 'Geeks 3']
sizes = [35, 35, 30]
# Plotting the pie chart
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
plt.title('Pie Chart Example')
plt.show()
In [17]: # Write a Python program to generate 6 digit OTP
# to generate random numbers we will use random library
from random import randint
print(randint(0,9),randint(0,9),randint(0,9),randint(0,9),randint(0,9),randint(0,9))
6 1 1 5 5 7
Assignment Number 1 Questions
1. Write a python program to find distance between two points
2. Write a python program to perform addition, multiplication, division, modulo division of of numbers
entered by user.
3. Write a python program to calculate area and circumference of a circle
4. Write a Python program to convert degree fahrenheit into degree celsius
5. Calculate total bill amount for purchase of 25 items each costing 650 rupees. Vendor is willing to give
8% discount while there is 18% GST.
6. Ask a student to provide IE1, IE2, Mid-Sem and End-Sem Marks. IE1 and IE2 marks are out to 10, while
Mid-Sem Marks are out of 50 and End-Sem out of 80 Marks. Scale down Mid-Sem marks to out of 30
and End-Term marks out of 50. tell the student his/her total marks out of 100.
7. Please take any unique question (should not be same as your batchmates) of your choice (just like
above questions) and write python code for it.
In [ ]: