[Go to site: main page, start]

0% found this document useful (0 votes)
25 views42 pages

Introduction to Python Programming

its a python note
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)
25 views42 pages

Introduction to Python Programming

its a python note
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

What is Python

Python is an object-oriented, interpreted and dynamic programming language.


It is dynamic typed that means we don't use data types to declare variable. Example: write a=10
to declare an integer variable.
Python History
o Python laid its foundation in the late 1980s.
o The implementation of Python was started in the December 1989 by Guido Van Rossum.
o ABC programming language is said to be the predecessor of Python language.
Python Features
There are a lot of features provided by python programming language.
2) Easy to Use: Python is very easy and programmer-friendly language.
3) Expressive Language: The code is easily understandable.
4) Object-Oriented language: Python supports the object oriented features.
5) Interpreted Language: Interpreter executes the code line by line at a time.
6) Cross-platform language: Python can run equally on different platforms such as Windows,
Linux, Unix, Macintosh etc. Thus, Python is a portable language.
7) Free and Open Source: Python language is freely available ([Link]).The source-code
is also available. Therefore it is open source.
8) Large Standard Library: Python has a large and broad library.
9) Integrated: It can be integrated with languages like C, C++, and JAVA etc.
How to Install Python
To install Python, firstly download the Python distribution from [Link]/download.
Setting PATH in PYTHON
Path will be set for executing Python programs.
1. Right click on My Computer and click on properties.
2. Click on Advanced System settings
3. Click on Environment Variable tab.
4. Click on new tab of user variables.
5. Write path in variable name (c:\\Python i.e. path where Python is installed).
6. Copy the path of Python folder
7. Paste path of Python in variable value.
8. Click on Ok button
9. Click on Ok button

How to execute python


There are three different ways of working in Python:
1) Interactive Mode:
You can enter python in the command prompt.

Press Enter key and the Command Prompt >>> will appear. Then
you can execute your Python commands.
2) Script Mode:
you can write your Python code in a separate file using any editor of your Operating System.

Save it by .py extension.

Now open Command prompt and execute it by:

NOTE: Path in the command prompt should be where you have saved your file.
In the above case file should be saved at desktop.

3) Using IDE: (Integrated Development Environment)


You can execute your Python code using a Graphical User Interface (GUI).
All you need to do is:
Click on Start button -> All Programs -> Python -> IDLE (Python GUI)
Variables
Variable is a name of the memory location where data is stored. Once a variable is stored that
means a space is allocated in memory.
Assigning values to Variable:
We need not to declare explicitly variable in Python. When we assign any value to the variable that
variable is declared automatically.
The assignment is done using the equal (=) operator.

Multiple Assignments:
1. Assigning single value to multiple variables:
x=y=z=50
print (x)
print (y)
print (z)
2. Assigning multiple values to multiple variables:
a,b,c = 5,10,15
print (a)
print (b)
print (c)
The values will be assigned in the order in which variables appears.

Tokens:
Token is the smallest unit inside the given program.
There are following tokens in Python:
o Keywords.
o Identifiers.
o Literals.
o Operators.
Keywords
Keywords are reserved words which convey a special meaning. List of Keywords used in Python
are:
True False None and as
asset def class continue break
else finally elif del except
global for if from import
raise try or return pass
nonlocal in not is lambda

Identifiers
Identifiers are the names given to variables ,class ,object ,functions , lists , dictionaries etc.
There are certain rules defined for naming i.e. Identifiers:
 An identifier is a sequence of characters and numbers.
 No special character except underscore ( _ ) can be used as an identifier.
 Keyword should not be used as an identifier name.
 Python is case sensitive.
 First character of an identifier can be character, underscore ( _ ) but not digit.
Python Operators
Operators are symbols which operate on some values (Operands)
Example: 4 + 5 (Here 4 and 5 are Operands and + is the operator).
Python supports the following operators
1. Arithmetic Operators
2. Relational Operators
3. Assignment Operators
4. Logical Operators
5. Membership Operators
6. Identity Operators
7. Bitwise Operators

Arithmetic Operators:
Operators Description
+ addition
- subtraction
* multiplication
/ division (with fraction)
// Floor division(gives integer value after division only integer)
% remainder after division(Modulus)
** exponent(raise to power)

Relational Operators:
Operators Description

< Less than


> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to

Assignment Operators:
Operators Description Example
= Assignment x = 5 means Assigns 5 to x
+= Add and Assign x += 3 means x = x + 3
-= Subtract and Assign x -= 3 means x = x - 3
*= Multiply and Assign x *= 3 means x = x * 3
/= Divide and Assign x /= 3 means x = x / 3
//= Floor divide and Assign x //= 3 means x = x // 3
%= Modulus and Assign x %= 3 means x = x % 3
**= Exponent and Assign x **= 3 means x = x ** 3

Logical Operators:
Operators Description
and Logical AND (When both conditions are true then output will be true)
or Logical OR (If any one condition is true then output will be true)
not Logical NOT(if condition is true then output is false and vice versa)
Membership Operators:
Operators Description
in Returns true if a variable is in sequence of another variable
not in Returns true if a variable is not in sequence of another variable

Example:
a=10
b=20
list=[10,20,30,40,50];
if (a in list):
print ("a is in given list" )
else:
print ("a is not in given list" )
if(b not in list):
print ("b is not given in list" )
else:
print ("b is given in list" )
Output:
a is in given list
b is given in list

Identity Operators:
Operators Description
is Returns true if identity of two variables are same
is not Returns true if identity of two variables are not same

Example:
a = 20
b = 20
if( a is b):
print (a,b have same identity)
else:
print (a, b are different)
b=10
if( a is not b):
print (a,b have different identity)
else:
print (a,b have same identity)
Output:
a, b have same identity
a, b have different identity

Bitwise Operators
These operators are used to compare (binary) numbers:

Operator Name Example


& AND x&y
| OR x|y
^ XOR x^y
~ NOT ~x
<< Left shift x << 2
>> Right shift x >> 2
Operator Precedence
Operator precedence describes the order in which operations are performed. For example,
multiplication has higher precedence than addition.
The precedence order is described in the table below:

Operator Description Precedence


( ) Parentheses Highest
** Exponentiation
~ Bitwise NOT
* / // % Multiplication, division, floor division, and modulus
+ - Addition and subtraction
<< >> Bitwise left and right shifts
& Bitwise AND
^ Bitwise XOR Lowest
List
 List contains items of different data types.
 Values stored in a List are separated by commas(,) and enclosed within square brackets [ ]
Example:
list1 = ['aman', 678, 20.4, 'saurav']
list2 = [456, 'rahul']
 List is mutable (modifiable)
Example:
L1 = [10, 20, 30, 40]
L1[2] = 90
print (L1)
Output: [10, 20, 90, 40]
 List allows +ve and -ve index
 Value stored in a List can be retrieved using the slice operator :
Example:
list1[1 : 4]
Output: 678, 20.4, 'saurav'
 + is the concatenation operator and * is the repetition operator
Example: list1 + list2
Output: 'aman', 678, 20.4, 'saurav', 456, 'rahul'
Example: L1 * 3
Output: [10, 20, 90, 40 , 10, 20, 90, 40, 10, 20, 90, 40]

 We can use built-in functions on a list such as len( ), sum( ), max( ), min( )
Example:
list3 = [10, 20, 30, 40, 50]
length = len (list3)
p = min (list3)
q = max (list3)
r = sum (list3)
print (length, p, q, r)
Output: 5 10 50 150
 We can use methods insert( ), remove( ), sort( ), reverse( )
Example:
list3 = [10, 20, 30, 40, 50]
[Link](2, 80) # Output: 10 20 80 40 50
[Link](20) # Output: 10 80 40 50
[Link]( ) # Output: 10 40 50 80
[Link]( ) # Output: 80 50 40 10

Nested list

L4 = [ [1, 2, 3] , [4, 5, 6, 7, 8] , [9 , 10] ]


L4 [0] # Output: [1, 2, 3]
L4 [0] [2] # Output: 3
L4 [2] [0] # Output: 9

Sorting words in a list:


words = [ 'big', 'seven', 'green', 'blue', 'after']
words. sort( )
print(words) # Output: after big blue green seven
words. sort ( key = str. lower)
print(words) # Output: seven green blue big after
Tuple
 Tuple contains items of different data types.
Tuple is similar to list
 List uses square brackets. But, Tuple uses parenthesis ( )
Example:
tuple1 = ('aman', 678, 20.4, 'saurav')
tuple2 = (456, 'rahul')
 List is modifiable. But, Tuple is not modifiable (data stored in tuple cannot be changed)
Example:
T1 = (10, 20, 30, 40)
T1[2] = 90
Output: Error 0 1 2 3
 Tuple allows +ve and -ve index
10 20 30 40
print (T1[-3])
-4 -3 -2 -1
Output: 20
 Value stored in a List can be retrieved using the slice operator :
Example:
tuple1 = ('aman', 678, 20.4, 'saurav')
tuple1[1 : 4]
Output: (678, 20.4, 'saurav')
tuple1[1 : 4 : 1]
Output: (678, 20.4, 'saurav')
tuple1[1 : 4 : 2]
Output: (678, 'saurav')
tuple1[ : : -1]
Output: ('saurav', 20.4, 678, 'aman')

 + is the concatenation operator and * is the repetition operator


Example: tuple1 + tuple2
Output: ('aman', 678, 20.4, 'saurav', 456, 'rahul')
Example: L1 * 3
Output: 10, 20, 30, 40 , 10, 20, 30, 40, 10, 20, 30, 40

 We can use built-in functions on a tuple such as len( ), sum( ), max( ), min( )
Example:
tuple3 = (10, 20, 30, 40, 50)
length = len (tuple3)
p = min (tuple3)
q = max (tuple3)
r = sum (tuple3)
print (length, p, q, r)
Output: 5 10 50 150
 We can following methods
count (x): number of items that is equal to x
index (x) : index of item that is equal to x
Example:
tuple3 = (30, 20, 10, 20, 10, 40, 50, 10)
print ([Link] (10) ) # Output: 3
print ([Link] (80) ) # Output: 0
print ([Link] (40) ) # Output: 1
print ([Link] (10) ) # Output: 2
Dictionary
 Dictionary is an unordered collection of items
 Dictionary has a key-value pair
Every pair is separated with comma
Key and value are separated with :
 Key must be a string or integer. But, Value can be anything.
 Dictionary is enclosed by curly braces { } and values can be retrieved by square brackets [ ]
Example:
d = { 'regno' : 84, 'name' : 'ram', 'dept' : 'cse' } # Here, keys are of string type
print(d) # output: { 'regno':84, 'name':'ram', 'dept':'cse' }
print([Link]( )) # output: ['regno' , 'name', 'dept']
print([Link]( )) # output: [84, 'ram', 'cse']
print(d['regno']) # output: 84
print(d['name']) # output: ram
print(d['dept']) # output: cse

 List is modifiable
d['name'] = 'ramakant'
print(d['name']) # output: ramakant
 We can following methods
clear( ) : remove all items from dictionaries
copy( ) : return a copy of dictionary

Nested Dictionary
Example:
d={ 'cse01' :
{ 'name' : 'ram' , 'marks' : [82, 75, 84, 92] } ,
'cse02' :
{ 'name' : 'gopal' , 'marks' : [91, 83, 86, 95] } ,
'cse03' :
{ 'name' : 'hari' , 'marks' : [84, 88, 75, 91] } ,
}

print ( d ['cse01'] ['name']) # output: ram


print ( d ['cse02'] ['marks'] [2]) # output: 86
print ( sum ( d ['cse03'] ['marks'] )) # output: 338
Set
 Set is an unordered collection of items
 Set does not allow +ve or -ve index or : operator (because set is unordered)
 Set is enclosed by curly braces { }
 Set does not allow duplicate elements
Example:
s = { 10, 20, 30, 10, 20, 40 }
print(s) # output: 10 20 30 40
print(len(s)) # output: 4
 We can following methods
add( ) : add an element to set
clear( ) : remove all elements from set
copy( ) : returns a copy of set
difference( ) : returns the difference of two or more set
union( ) : returns the union of sets
intersection( ) : returns the intersection of sets
issubset( ) : returns true if another set contains this set
issuperset( ) : returns true if this set contains another set
Example:
s = { 10, 20, 30, 40, 50, 60 }
s . add(70)
print(s) # output: 10 20 30 40 50 60 70

s1 = { 10, 20, 30, 40 }


s2 = { 30, 40, 50, 60 }
s3 = [Link](s2)
print(s3) # output: 10 20
s3 = [Link](s1)
print(s3) # output: 50 60
s3 = [Link](s2)
print(s3) # output: 30 40

s1 = { 10, 20, 30, 40, 50, 60 }


s2 = { 10, 20, 30, 40 }
print([Link](s2)) # output: False
print([Link](s2)) # output: True
print([Link](s1)) # output: True
print([Link](s1)) # output: False

Comment line
Python supports two types of comments.
1. Single lined comment:
For single line comment, you must begin with the symbol hash #
Example: a = 10 # Assigning value to variable a
2. Multi lined Comment:
Multi lined comment can be given inside triple single quotes(''') or triple double quotes('' '' '').
Example:
'''This
Is
Multi line comment'''
String
 String is a set of characters which are enclosed within quotes (single or double quotes).
Example: s = 'hello' # we can also write using single quote (') s = 'hello'
print(s[0]) # output: h 0 1 2 3 4
h e l l o
print(s[-4]) # output: e
-5 -4 -3 -2 -1
print(s[1 : 4]) # output: ell
 In Python, strings are immutable. That means the characters of a string cannot be changed.
s[0] = 'H'
print(s) # output: Type Error
 We use the == operator to compare two strings. If two strings are equal, the operator
returns True. Otherwise, it returns False.
str1 = "cuttack"
str2 = "bhubaneswar"
str3 = "cuttack"
# compare str1 and str2
print(str1 == str2) # output: False
# compare str1 and str3
print(str1 == str3) # output: True
 We can join (concatenate) two or more strings using the + operator
result = str1 + str2
print(result) # Output: cuttack bhubaneswar
 We can iterate through a string using for loop
str = 'Hello'
for k in str:
print(k)
# Output:
H
e
l
l
o
 len( ) method to find the length of a string
str = 'Hello'
print(len(str)) # Output: 5

String Membership Test


 We can test if a substring exists within a string or not, using the keyword in
print('a' in 'program') # Output: True
print('at' not in 'battle') # Output: False
Methods of String

Methods Description
upper( ) Converts the string to uppercase
lower( ) Converts the string to lowercase
replace( ) Replaces substring
find( ) Returns the index of the first occurrence of substring
split( ) Splits string
startswith( ) Checks if string starts with the specified string
isnumeric( ) Checks every character of string is numeric
index( ) Returns index of substring
rstrip( ) Removes trailing characters

str = 'Hello'
print([Link]( )) # Output: HELLO
print([Link]( )) # Output: hello

str = 'I am from India'


t = [Link]('I am', 'He is')
print(t) # Output: He is from India

text = 'Python is fun'


print([Link]( )) # Output: ['Python', 'is', 'fun']
print([Link]('Py')) # Output: True

pin = "523"
print([Link]( )) # Output: True

text = 'Python is fun'


result = [Link]('is')
print(result) # Output: 7 #substring is found at index 7

text = 'this is good '


print([Link]( )) # Output: this is good (Trailing spaces are removed)
str = "Pythonssssssssss"
print([Link]('s')) # Output: Python

String Formatting (f-Strings)


f-Strings makes it easy to print values and variables.
Example:
name = 'Sourav'
country = 'India'
print(f'{name} is from {country}')
# Output: Sourav is from India
Here, f'{name} is from {country}' is an f-string.
print( ) : It is a predefined output function
type( ) : This function returns type of variable
a = 10
b = 20
c = 30
print(a, b, c) #output: 10 20 30
print(type(b)) #output: <class 'int'>

input() : This function takes input from keyboard


This function returns in string format
Example: a = input(“enter first number ”)
b = input(“enter second number ”)
print(“ Sum is ”, a + b)
output: Sum is 10 20
int( ) : This function converts string to integer type
Example: a = int(input(“enter first number ”))
b = int(input(“enter second number ”))
print(“Sum is ”, a + b)
output: Sum is 30
Note: float( ) converts string to integer type

Type conversion
x = int("10")
y = float("10.25")
print(x, y)
Output: 10 10.25

Comment line
Python supports two types of comments.
1. Single lined comment:
For single line comment, you must begin with the symbol hash #
Example: a = 10 # Assigning value to variable a
2. Multi lined Comment:
Multi lined comment can be given inside triple single quotes(''') or triple double quotes('' '' '').
Example:
'''This
Is
Multi line comment'''
Conditional statements
Condition is a logical expression. Python provides following conditional statements.
1. If
2. If else
3. If elif else
if
Program to input three numbers from user and display the largest.
a = int(input("Enter the First number : "))
b = int(input("Enter the Second number : "))
c = int(input("Enter the third number : "))
if a > b:
large = a
if b > a:
large = b
if c > large:
large = c
print("The largest number is ", large)

if else
Syntax:
if condition:
line1----------- # line is called as statement
line2-----------
line3-----------
else :
line4-----------
line5-----------
line6-----------
line7-----------
line8-----------
If condition is True : lines 1, 2, 3, 7, 8
If condition is False: lines 4, 5, 6, 7, 8
Program to input two numbers from user and display the largest.
a = int(input("Enter the First number : "))
b = int(input("Enter the Second number : "))
if a>b:
large = a
else:
large = b
print("The largest number is ", large)

Program to check even or odd number.


n = int(input("Enter the Number:"))
if n % 2 == 0:
print("Given number is Even")
else:
print("Given number is Odd")

Program to Check if a Character is a Vowel or a Consonant


c = (input("Enter the Alphabet :"))
if c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u' :
print(c, "is a vowel")
else:
print(c, "is a consonant")
Program To Check If a Given Number is Amstrong number or Not
num = int(input("Enter a number: "))
a = num // 100
b = (num // 10) %1 0
c = num%10
r = (a**3) + (b**3) + (c**3);
if r == num:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

Program to Check Given Year is Leap Year or Not


year = int(input("Enter the Year : "))
if (year%400 == 0) or (year%4==0 and year%100!=0):
print("Leap Year")
else:
print("Not a Leap Year")

if elif else
elif means else if
We can write multiple elif inside one if-else
Syntax:
if condition:
line1-----------
line2-----------
elif condition: # 1st elif
line3-----------
line4-----------
elif condition: # 2nd elif
line5-----------
line6-----------
else :
line7-----------
line8-----------
line9-----------
line10-----------
If condition is True : lines 1, 2, 9, 10
If condition is False: Check 1st elif
1st elif is True : lines 3, 4, 9, 10
1st elif is False : Check 2nd elif
2nd elif is True : lines 5, 6, 9, 10
2 elif is False
nd
: lines 7, 8, 9, 10
Program to input three numbers from user and display the largest.
a = int(input("Enter the First number : "))
b = int(input("Enter the Second number : "))
c = int(input("Enter the third number : "))
if a > b and a>c :
large = a
elif b > a and b>c :
large = b
else :
large = c
print("The largest number is ", large)
Program to Calculate the Grade of a Student
mark = int(input('Enter the Mark:'))

if mark >= 90:


grade = 'O'
elif mark >= 80:
grade = 'E'
elif mark >= 70:
grade = 'A'
elif mark >= 60:
grade = 'B'
elif mark >= 50:
grade = 'C'
else:
grade = 'F'

print("The student Grade is ",grade)

Program to demonstrate ATM process


print("Welcome to State bank of India")
p = int(input("Enter your 4 digit pin number: "))
b = 50000
if (p == 1234):
print("1-Withdraw")
print("2-Balance Enquiry")
t = int(input("Please choose your transaction (1 or 2): "))
if (t == 1):
w = int(input("Enter withdraw amount: "))
if (w < b):

if (w % 100 == 0):
print("Withdraw successful. Please take your amount")
b=b–w
else:
print("Invalid amount")
else:
print("Insufficient balance")
elif (t == 2):
print("Your available amount : ",b)
else:
print("Wrong pin number")
Loops
Loop is a repetitive process of an operation. Python provides 2 types of loop
1. while loop
2. for loop
while loop
while loop is a repetitive process of unknown range. It execute a block of statements until the given
condition is true. Once the condition is evaluated as false, the program executes the line
immediately after the loop
while condition:
line1-----------
line2-----------
line3-----------
line4-----------
line5-----------
Here, lines 1,2,3 are inside while loop. But lines 4,5 are outside while loop
Python indentation is a way of grouping statements. The statements indented using the same
number of spaces are considered part of the same block.

Program to display 1 to 5
i=1
while i<=5:
print(i) # we can write print(i, end=””) for printing in the same line
i=i+1
print("Thank You")

Program to display sum of digits


n = int(input("enter a number"))
sum = 0
while(n != 0)
rem = n % 10
n = n //10
sum = sum + rem
print ("sum of digits is ", sum)

Program to display reverse of a number


n = int(input("enter a number"))
rev = 0
while(n != 0)
rem = n % 10
n = n //10
rev = rev * 10 + rem
print ("reverse of the given number is ", rev)
for Loop
for variable in sequence:
line1------------------
line2------------------ for block statements
line3------------------
line4------------------
other statements
line5------------------

In for loop, the sequence can be range( ) function

Example1:
numbers = [1, 2, 3, 4, 5]
for k in numbers : # Loop through the list
print(k) # By default, print function end with \n

# Output:
1
2
3
4
5
Example2:
for k in "ABIT" : # Loop through the string
print(k)
# Output:
A
B
I
T
range() Function
range( ) is a built-in function. It is used to produce a series or range of numbers.
By default, the sequence starts with zero, increments by 1.
Example: range(5) will produce 0 1 2 3 4
range(1 , 5) will produce 1 2 3 4
range(1 , 6 , 2) will produce numbers between 1 3 5

Program to print 1 to 10 & 10 to –1


for i in range(1 , 11):
print(i)
for i in range(10 , 0 , –1):
print(i)
Program to display multiplication table
m = int(input(" enter table number "))
for i in range(1 , 11):
print(m, "X", i , "=", m*i)

Nested Loop
 A loop which is defined inside another loop
for var1 in sequence:
for var2 in sequence:
statements(s)
Program to print pyramid
for i in range(1 , 6): # Outer loop for the number of lines(rows)
for j in range(i): # Inner loop for printing stars
print("*", end="")
print( ) # Move to the next line

# Output:
*
**
***
****
*****

Program to print pyramid


k=1
for i in range(1 , 5): # Outer loop for the number of lines(rows)
for j in range(i): # Inner loop for printing values
print(k, end=" ")
k=k+1
print( )
# Output:
1
23
456
78910

Program to print pyramid


for i in range(1 , 6): # Outer loop for the number of lines(rows)
for j in range(i): # Inner loop for printing values
print( i , end="")
print( )
# Output:
1
22
333
4444
55555
for i in range(1 , 6): # Outer loop for the number of lines(rows)
for j in range(5, i , –1): # Inner loop for printing space
print(" ", end="")
for k in range(i): # Inner loop for printing space
print("*", end="")
print( )
# Output:
*
**
***
****
*****

Continue Statement
Continue statement moves to the next iteration by skipping the current iteration of the loop.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for k in numbers:
if k == 4:
continue
print(k, end=" ")
# Output: 1 2 3 5 6 7 8 9 10

Break Statement
break statement can be used to stop the loop
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for k in numbers:
if k == 4:
break
print(k, end=" ")
# Output: 1 2 3

Pass Statement
Using the pass statement, we can write empty loops. If we need to leave the loop blank in any condition then
we use the pass statement.
numbers = [1, 2, 3, 4, 5]
for k in numbers:
if number % 2 == 0:
pass # Place for future code
else:
print(k "is an odd number")
# Output:
1 is an odd number
3 is an odd number
5 is an odd number
FUNCTION
 Function is a set of statement which performs an operation
Syntax:
def functionname ( ):
statement1-----------
statement2-----------
statement3-----------
Example:
def add ( ): # Function Definition
a = int (input ("Enter 1st number "))
b = int (input ("Enter 2nd number "))
c=a+b
print(" The addition=", c)
add ( ) # Function Call

Advantages of function
 Code reusability
 Easy to modify
 Easy to debug

Example:
def fun1( ):
print (" Function1 ")
def fun2 ( ):
print (" Function2 ")
def fun3 ( ):
print (" Function3 ")
fun1 ( )
fun2 ( )
fun3 ( )

Write a program to perform addtion, substraction, multiplication and division using


different function
def add ( ):
a = int (input (" Enter first Number "))
b = int (input (" Enter second number "))
c=a+b
print (" The addition is = " , c)

def sub ( ):
x = int (input (" Enter first Number "))
y = int (input (" Enter second Number "))
z=x–y
print (" The Subtraction is = “ , z)

def mul ( ):
m = int (input (" Enter first Number "))
n = int (input (" Enter second Number "))
o=m*n
print (" The Multiplication is = " , o)
def div ( ):
p = int (input (" Enter first Number "))
q = int (input (" Enter second Number "))
r = p // q
print (" The Division is = " , r)
add( ):
sub( ):
mul( ):
div( ):

Global variable
 The variable which is declared outside the function is called Global Variable
 The scope of the Variable is throughout the program
Example:
a = 100 # Global Variable
def display ( ):
a = 2000 # Local Variable
print(a)
def add( ):
a = 3000
print(a)
add ( ) # 3000
print (a) # 100
display ( ) # 2000

 We cannot modify Global variable inside a function


Example:
a = 100
def display ( ):
print (a)
a = 500 # Error, because we want to modify Global Variable

 We can access global variables using Global keywords


Example:
def display ( ):
global a
a = 1000
print(a)
display ( ) # 1000
print (a) # 1000

In Python, we can define a function in 4 ways:


1. Function Without Parameter and Without Return Type
2. Function With Parameter and Without Return Type
3. Function Without Parameter and With Return Type
4. Function With Parameter and With Return Type
Function Without Parameter and Without Return Type
Example:
def fun1( ) :
print (" ABIT ")
print (" CSE - B ")
fun1( )
Output: ABIT
CSE - B

Function With Parameter and Without Return Type


Example:
def fun1(x, y, z) :
print (x, y, z)
fun1(10, 20, 30)
fun1(" xyz", " pqr" , " mno")
Output: 10 20 30
xyz pqr mno

Function Without Parameter and With Return Type


Example:
def fun1( ):
a = 10
b = 20
return a + b
x = fun1( )
print (x)
Output: 30

Function With Parameter and With Return Type


Example:
def fun1 (a, b):
return a + b
x = fun1(10, 20)
print (x)
Output: 30

Recursion
 Recursion is a technique in which a function call itself
 Recursion uses stack data structure.

Program to find factorial of a number using recursion


def fact(num):
if num == 1 :
return 1
else :
return num * fact (num – 1)
result = fact (5)
print (" factorial is ", result)
Output: factorial is 120
EXCEPTION HANDLING
 Exception abnormally terminates the execution of the program.
Example: Divide by Zero and Array Index out of Bound Exception.
 In Python, we use Try….Except Block to handle the exception
Example 01:
try :
a = 18
b=0
c=a/b
print(c)
except :
print(" Divide by Zero Error ")
Output: Divide by Zero Error
Example 02:
try :
a = [10, 20, 30, 40]
print(a[5])
except Index_Error :
print(" Array Index Out of Bound ")
Output: Array Index Out Of Bound
NOTE: For one try block there can be multiple except block that allow us to handle each
exception differently.

CLASS AND OBJECT


 Class is the blueprint of an Objects.
 Object is the instance of a Class.
Example:
class Bike : # Define a Class
name = " "
gear = 0
bike1 = Bike() # Created the object of a Class
[Link] = " Honda " # Assign new values to member of object
[Link] = 5 # Assign new values to member of object

print(" Bike Name = ", [Link])


print(" Number of Gear = ", [Link])

CONSTRUCTOR
 Constructor is a special type of method in class.
 The name of the constructor should be def_init_(self).
 Constructor is used to initialize the instance variables.
 Constructor is executed automatically during object creation.
Example:
class Student:
def_init_(self, name, rollno ):
[Link] = name
[Link] = rollno
def display(self):
print("my name is " , [Link])
print("my rollno is " , [Link])
s1 = Student("Ram" , 83)
[Link]( )
Notes:
 Self is the default variables which points to the current object.
 Self should be the first parameter inside the constructor and method.

Default Constructor
class Person:
def_init_(self) :
[Link] = "Prakash"
self. age = 40
Person1 = Person( )
print ([Link])
print ([Link])

Parameterised Constructor
class Person :
def_init_(self, name, age ) :
[Link] = name
[Link] = age
Person1 = Person ("Prakash", 40)
print ([Link])
print ([Link])
PANDAS
 Pandas is a package for data analysis.
 Pandas is used for tabular data (data frame).
Uses of Pandas:
 Import dataset from database, databases, spreadsheets and csv files.
CSV = Comma Separate Value
 Clean dataset (Example: Dealing with missing values).
 Formatting the structure of dataset.
 Statistical Analysis.
 Visualization of dataset.

command to install Pandas: pip install pandas.


Outputting data in pandas:
df. to_csv ("[Link]", index = False)
Here, the data frame is called to a csv files using to csv method.
viewing dataframe:
 head( ) method displays number of rows from First row onwards.
[Link]( ) # By default first five rows are displayed
 tail( ) method display number of rows from last row onwards.
[Link]() # By default last five rows are displayed
[Link] (n=10) # Last 10 rows are displayed
 describe( ) method prints the summary statistics of all numeric columns (such as
count, mean, standard deviation, range, etc.).
[Link]( )
 info( ) method display data types, missing values and data sizes of a data frames.
[Link]( )
 isnull() checks the missing values
[Link]( )

Sorting data
To sort DataFrame by a specific column:
To Sort by Age in descending order, we can write following code
df.sort_values(by="Age", ascending=False, inplace=True) #

Using .loc[] and .iloc[] to fetch rows


 As we know, row number starts from 0. loc[] assume 1st row as row 1. But, iloc[]
assume 1st row as row 0
[Link][100:110] # displays row numbers 100 to 110
[Link][100:110] # displays row numbers 101 to 110

Display rows based on condition


# The code below selects the rows where Blood Pressure is 122
df[[Link] == 122]
# The code below displays the rows where Outcome column has value 1
df[[Link] == 1]
# The code below displays Pregnancies, Glucose, and BloodPressure column where
BloodPressure is greater than 100.
[Link][df['BloodPressure'] > 100, ['Pregnancies', 'Glucose', 'BloodPressure'
Replacing missing values
mean_value = df ['Pregnancies'].mean( ) # Get the mean of Pregnancies column
df = [Link](mean_value) # Fill missing values using .fillna()

You can remove all duplicate rows from the DataFrame using drop_duplicates() method.
df = df.drop_duplicates()
The DiabetesPedigreeFunction is renamed as DPF by using the code below:
[Link](columns = {'DiabetesPedigreeFunction':'DPF'}, inplace = True)

Data analysis in pandas


You can get the mean of each column value using the mean( )method.
[Link]()
Output:

The mode can be computed similarly using the mode() method.


[Link]( )

Similarly, the median of each column is computed with the median() method
[Link]()

Create new columns based on existing columns


The below code divides each value in the column Glucose with the corresponding value in
the Insulin column to compute a new column named Glucose_Insulin_Ratio
df ['Glucose_Insulin_Ratio'] = df ['Glucose'] / df ['Insulin']

Counting using value_counts( )


Category values can be counted using the .value_counts( )method.
Example: Consider the Outcome column. We want to see the number of observations
where Outcome is (1) and the number of observations where the Outcome is (0). The code
is written below.
df['Outcome'].value_counts( )
Output:
Data visualization in pandas
Line plots in pandas
Below is a line plot of BMI and Glucose versus the row index.
df[['BMI', 'Glucose']].[Link]()
Output:

You can select the choice of colors by using the color argument.
df[['BMI', 'Glucose']].[Link](figsize=(20, 10), color={"BMI": "red", "Glucose": "blue"})
Output:

All the columns of df can be plotted on different scales and axes by using the subplots
argument.
[Link](subplots=True)
Output:

Bar plots in pandas


bar plot over the category counts to visualize their distribution. The Outcome column with
binary values is visualized below.
df['Outcome'].value_counts().[Link]( )
Output:

Box plots in pandas


The quartile distribution of continuous variables can be visualized using a boxplot. The
code below lets you create a boxplot with pandas.
[Link](column=['BMI'], by='Outcome')
NUMPY
 NumPy is a Python library that performs numerical calculations.
 NumPy is generally used for working with arrays.
 NumPy provides mathematical functions such as linear algebra, Fourier transformation,
and random number generation, which can be applied on arrays.

import numpy as np
The above code imports the numpy library in our program as an alias np
Here, alias means a different name of numpy is np.

list1 = [2, 4, 6, 8]
array1 = [Link](list1) # Create Array using List
print(array1) # Output: [2 4 6 8]
We can directly pass list of elements as an argument as shown below:
array1 = [Link]([2, 4, 6, 8])

array2 = [Link](4) # create an array with 4 elements filled with zeros


print(array2)
Output: [0. 0. 0. 0.]
array3 = [Link](5) # create an array with values from 0 to 4
print(array3)
Output: [0 1 2 3 4]
array4 = [Link](1, 9, 2) # create an array with values from 1 to 8 with a step of 2
print(array4)
Output: [1 3 5 7]
array5 = [Link](5) # generate an array of 5 random numbers
print(array5)
Output: [0.08455648 0.56379034 0.66463204 0.97608605 0.30700052]

Create 2-D Array


Create a 2D array with 2 rows and 4 columns
array6 = [Link]([[1, 2, 3, 4],
[5, 6, 7, 8]])
print(array6)

Output:
[[1 2 3 4]
[5 6 7 8]]

Create 2D array with 2 rows and 3 columns filled with zeros


array7 = [Link]((2, 3))
print(array7)
Output:
[[0. 0. 0.]
[0. 0. 0.]]

print([Link])
Output: 2 # 2 is the number of dimensions (that means 2D array)
print([Link])
Output: 6 # 6 is the total number of elements in array7

print([Link])
Output: (2,3) # (2,3) means 2 rows and 3 columns.
NumPy Comparison Operators
import numpy as np
array1 = [Link]([1, 2, 3])
array2 = [Link]([3, 2, 1])
# less than operator
result1 = array1 < array2
print(result1) # Output: [ True False False]
# greater than operator
result2 = array1 > array2
print(result2) # Output: [False False True]
# equal to operator
result3 = array1 == array2
print(result3) # Output: [False True False]

NumPy Comparison Functions


import numpy as np
array1 = [Link]([9, 12, 21])
array2 = [Link]([21, 12, 9])
result = [Link](array1, array2)
print(result)
Output: [ True False False]
result = np.less_equal(array1, array2)
print(result)
Output: [ True True False]
result = [Link](array1, array2)
print(result)
Output: [False False True]
result = np.greater_equal(array1, array2)
print(result)
Output: [False True True]
result = [Link](array1, array2)
print(result)
Output: [False True False]
result = np.not_equal(array1, array2)
print(result)
Output: [ True False True]

NumPy Math Functions


1. Trigonometric Functions

Trigonometric Function Calculated in radians


sin() sine of an angle
cos() cosine of an angle
tan() tangent of an angle
arcsin() inverse sine
arccos() inverse cosine
arctan() inverse tangent
degrees() converts an angle in radians to degrees
radians() converts an angle in degrees to radians
Example:
import numpy as np
angles = [Link]([0, 1, 2]) # array of angles in radians
sine_values = [Link](angles) # compute the sine of the angles
print("Sine values:", sine_values)
inverse_sine = [Link](angles) # compute the inverse sine of the angles
print("Inverse Sine values:", inverse_sine)
Output
Sine values: [ 0. 0.84147098 0.90929743 ]
Inverse Sine values: [ 0. 1.57079633 nan ]
2. Arithmetic Functions

Arithmetic Function Operation


add() Addition
subtract() Subtraction
multiply() Multiplication
divide() Division
power() Exponentiation
mod() Modulus

Example:
import numpy as np
first_array = [Link]([1, 3, 5, 7])
second_array = [Link]([2, 4, 6, 8])
result = [Link](first_array, second_array)
print("Using the add() function:",result)
Output:
Using the add() function: [ 3 7 11 15]

Rounding functions:

Rounding Function Description


round() returns the value rounded to the desired precision
floor() returns the nearest integer that is less than element

ceil() returns the nearest integer that is greater than element

Example:
import numpy as np
numbers = [Link]([1.23456, 2.34567, 3.45678, 4.56789])
rounded_array = [Link](numbers, 2) # round the array to two decimal places
print(rounded_array)
Output: [1.23 2.35 3.46 4.57]

Example:
import numpy as np
array1 = [Link]([1.23456, 2.34567, 3.45678, 4.56789])
print("Array after floor():", [Link](array1))
print("Array after ceil():", [Link](array1))
Output:
Array after floor(): [1. 2. 3. 4.]
Array after ceil(): [2. 3. 4. 5.]
API
An API is a bridge between different applications.
Example: Imagine an API as a waiter in a restaurant. You tell the waiter what you want
(your order), and they communicate your request to the kitchen. The kitchen prepares
your food, and the waiter brings it back to you. Similarly, you send a request to an API,
and it processes your request and then returns the results from server.

Introduction to APIs in Python


First you need to install requests library using following code. This library helps for sending
HTTP requests. It helps to communicate with APIs and retrieve or send data.
pip install requests

GET requests
GET request is a type of HTTP request to get data from a server
Example: import requestsresponse = [Link]('[Link] data
= [Link]() print(data)
In this example, we are using a fictional API and printing the JSON response.

POST requests
While GET requests retrieve data, POST requests sends the data to a server. E.g.: create
new user or update existing user. For example: After filling out an online form, you click
submit button, i.e. you send a POST request of your information(data).
Example:
# Data to send (user information)
data = {'name': 'John Doe', 'email': '[Link]@[Link]'}
# Send the data to the API (replace the URL with the actual API endpoint)
response = [Link]('[Link] json=data)
# Check if the request was successful (usually a status code of 201 for creation)
If response.status_code == 201:
print("User created successfully!")
else:
print("Error:", response.status_code)
This example sends user information as JSON data to the API. We then check the response
status code to see if the user was created successfully.

Handling responses
When you make an API request, the server sends back a response that includes two
important information:
 Status Code: This code indicates the success or failure of the request. For example:
200 means success, while 404 means the resource wasn't found.
 Data: The information is often in JSON format. This is where the valuable content
resides.

Example:
response = [Link]('[Link]
if response.status_code == 200:
data = [Link]()
print(data)
else:
print(f"Request failed with status code {response.status_code}")
API Status Codes
API status codes are standardized responses that servers send back to indicate the result
of a client's request. Some Common status codes are written below:
 200 OK: This code indicates that the request was successful. For example, when you
make a GET request to retrieve data from an API, a 200 OK response means the data
was fetched correctly.
 404 Not Found: This code indicates that the server cannot find the requested resource.
For example, if you try to access an endpoint URL that doesn't exist, you'll receive a
404 Not Found error.
 500 Internal Server Error: This code signals that something went wrong on the server's
side. This error message occur due to various issues, such as bugs in the server code
or problems with the database.

Building Python APIs


Introduction to FastAPI
Now that, you know how to use APIs, let’s explore how we can build our own API.
FastAPI is a modern, fast (high-performance) web framework for building APIs with
Python.

Setting up FastAPI
To get started, you'll need Python and its package manager (pip install… ). Subsequently,
install FastAPI and Uvicorn (a high-performance ASGI server):
pip install fastapi uvicorn
Explanation of code:
The code snippet pip install fastapi uvicorn is used to install two Python packages: fastapi
and uvicorn.
 pip install: This command uses pip, the Python package manager, to install packages
from the Python Package Index (PyPI).
 fastapi: This is a modern, fast (high-performance) web framework for building APIs with
Python 3.6+.
 uvicorn: This is an ASGI server implementation, used to run ASGI applications like those
built with FastAPI. It is lightweight and fast.
This command aims to set up your environment with the necessary tools to develop and
run web applications using FastAPI.
Creating a simple API
Let's construct a straightforward API that returns a simple greeting message:
from fastapi import FastAPIapp = FastAPI()@[Link]("/")
def read_root():
return {"Hello": "World"}

To launch this API, execute the following command:


uvicorn main:app –reload
Explanation of code:
The code snippet uvicorn main:app --reload is a command to run a FastAPI application
using Uvicorn, an ASGI server.
 uvicorn: This command starts the Uvicorn server.
 main:app: This specifies the application to run. main refers to the Python file named as
[Link], and app is the FastAPI instance within that file.
 --reload: This flag enables auto-reloading, which means the server will automatically
restart if you make changes to the code.
This command initiates the Uvicorn server, serving your API on [Link]
Accessing this URL in a web browser will give the response {"Hello": "World"}.
Flask
 Flask is known as a lightweight WSGI application framework.
 Flask helps to build reliable, scalable, and maintainable web applications.
Installing Flask
Run the following commands on your terminal:
Create the virtual environment:
py -3 -m venv venv
Activate the virtual environment:
venv\Scripts\activate
Install Flask via pip:
pip install Flask

Example: Making a "Hello, World!" Flask Application


Prepare Your Application Directory
create a folder hello-world and put all our application code inside that. Go to your development directory (where you want to place your
code) and run the following command to create the hello-world folder:
mkdir hello-world

Now go to the hello-world folder and create a new python file called [Link]. Add the following lines to the [Link] file.
# [Link]
from flask import Flask

app = Flask(__name__)

@[Link]("/")
def hello_world():
return "Hello, World!"
Explanation of the above code:
 First we imported the Flask class.
 Then we've create an instance of the class and assigned that to app variable. This instance of the class will be our WSGI application.
 We then use the route() decorator to tell Flask what URL should trigger our function.
 The function is given a unique name and returns the message we want to display in the user’s browser.
Run the Application
You need to export the FLASK_APP environment variable. Also, you should turn on the debugging mode by setting
the FLASK_ENV environment variable to development.
Now, export FLASK_APP and FLASK_ENV variables on Command Prompt like this:
C:\path\to\app>set FLASK_APP=[Link]
C:\path\to\app>set FLASK_ENV=development
Then run:
python -m flask run

Now using your browser, head over to [Link] (opens new window), and you should see your 'Hello, world!' greeting.
File Handling
File handling is an important part of any web application.
Python has several functions for creating, reading, updating, and deleting files.
File Open
The open() function takes two parameters; filename, and mode.
There are four different methods (modes) for opening a file:
"r" - Read - Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode
"t" - Text mode
"b" - Binary mode (e.g. images)
Syntax
To open a file for reading it is enough to specify the name of the file:
f = open("[Link]")
The code above is the same as:
f = open("[Link]", "rt")
Because "r" for read, and "t" for text are the default values, you do not need to specify them.
Note: Make sure the file exists, or else you will get an error.
Assume we have the [Link] file, located in the same folder as Python:
To open the file, use the built-in open() function.
The open() function returns a file object, which has a read() method for reading the content of the file:
Example
f = open("[Link]")
print([Link]())

If the file is located in a different location, you will have to specify the file path, like this:
f = open("D:\\myfiles\[Link]")
print([Link]())
Using the with statement
You can also use the with statement when opening a file:
Example
with open("[Link]") as f:
print([Link]())
Then you do not have to worry about closing your files, the with statement takes care of that.
File Close
It is a good practice to always close the file when you are done with it.
If you are not using the with statement, you must write a close statement in order to close the file:
Example:
f = open("[Link]")
print([Link]())
[Link]()

Note: You should always close your files. In some cases, due to buffering, changes made to a file may not show until you close the file.

Read Only Parts of the File


By default the read() method returns the whole text, but you can also specify how many characters you want to return:
Example
Return the 5 first characters of the file:
with open("[Link]") as f:
print([Link](5))
Read Lines
You can return one line by using the readline() method:
Example
Read one line of the file:
with open("[Link]") as f:
print([Link]())
By calling readline() two times, you can read the two first lines:
Example
Read two lines of the file:
with open("[Link]") as f:
print([Link]())
print([Link]())

Python File Write


To write to an existing file, you must add a parameter to the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content

Example: Open the file "[Link]" and append content to the file:
with open("[Link]", "a") as f:
[Link]("Now the file has more content!")
#open and read the file after the appending:
with open("[Link]") as f:
print([Link]())

Overwrite Existing Content


To overwrite the existing content to the file, use the w parameter:
Example: Open the file "[Link]" and overwrite the content:
with open("[Link]", "w") as f:
[Link]("Woops! I have deleted the content!")

#open and read the file after the overwriting:


with open("[Link]") as f:
print([Link]())
Note: the "w" method will overwrite the entire file.

Create a New File


To create a new file in Python, use the open() method, with one of the following parameters:
"x" - Create - will create a file, returns an error if the file exists
"a" - Append - will create a file if the specified file does not exists
"w" - Write - will create a file if the specified file does not exists

Example
Create a new file called "[Link]":
f = open("[Link]", "x")
Result: a new empty file is created.
Note: If the file already exist, an error will be raised.

Delete a File
To delete a file, you must import the OS module, and run its [Link]() function:

Example: Remove the file "[Link]":


import os
[Link]("[Link]")
Django - Web Framework
 Django is a high-level Python web framework that allows developers to build web
applications quickly and efficiently.
 Django provides a set of tools and functionalities for handling common web development
tasks such as database operations, URL routing, template rendering, and user
authentication.
 Django follows the Model-View-Template (MVT) architectural pattern

History of Django:
Django was created in 2003 by Adrian Holovaty and Simon Willison while they were working
at the Lawrence Journal-World newspaper in Kansas, USA.

How does Django framework works?


 Django receives the URL, checks the [Link] file, and calls the view that matches the URL.
 The view, located in [Link], checks for relevant models.
 The models are imported from the [Link] file.
 The view then sends the data to a specified template in the template folder.
 The template contains HTML and Django tags, and with the data it returns finished HTML
content back to the browser.

1. Install Python
Before we use Django, we need to install python. Python includes a lightweight database
called SQLite, so you won't need to set up a database.
2. Install Django
To install Django, you must use a package manager like PIP. To check if your system has
PIP installed or not, run the command: pip –version
3. Create Virtual Environment
To create a virtual environment, decide upon a directory where you want to place it, and
run the venv module as a script with the directory path.
Create a new folder "django" and navigate to that folder location.
C:\Users\Skillzam> cd Desktop
C:\Users\Skillzam\Desktop> cd code
C:\Users\Skillzam\Desktop\code> mkdir django
C:\Users\Skillzam\Desktop\code> cd django
C:\Users\Skillzam\Desktop\code\django> py -m venv myDjangoEnv
This will set up a virtual environment, and create a folder named "myDjangoEnv" with
subfolders and files, like this:
myDjangoEnv
Include
Lib
[Link]
Scripts
4. Activate the Virtual Environment
We can activate the Virtual environment, by typing the below command:
Note: You must activate the virtual environment every time you open the command prompt
to work on your project.
C:\Users\Skillzam\Desktop\code\django> myDjangoEnv\Scripts\[Link]
5. Django installation
We need to be in virtual environment, in order to install Django.
Django is installed using pip, with the below command:
C:\Users\Skillzam\Desktop\code\django> py -m pip install Django

To verify that Django can be seen by Python, type py from your command prompt. Then at
the Python prompt, try to import django
C:\Users\Skillzam\Desktop\code\django> py
Python 3.11.1 (tags/v3.11.1:a7a450f, Dec 6 2022, 19:58:39) [MSC v.1934 64 bit
(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> print(django.get_version())
4.1.7
7. Create Django Project
Navigate to where in the file system we want to store the code (in the virtual environment),
and run this command in the command prompt:
C:\Users\Skillzam\Desktop\code\django\myDjangoEnv> django-admin startproject mysite
Django creates a mysite folder on the computer, with this content:
mysite/
[Link]
mysite/
__init__.py
[Link]
[Link]
[Link]
[Link]

These files are:


 The outer mysite/ root directory is just a container for your project. Its name doesn't
matter to Django; you can rename it to anything you like.
 [Link]: A command-line utility that lets you interact with this Django project in
various ways.
 The inner mysite/ directory is the actual Python package for your project. Its name is the
Python package name you'll need to use to import anything inside it (e.g. [Link] ).
 mysite/__init__.py: An empty file that tells Python that this directory should be
considered a Python package.
 mysite/[Link]: To apply ASGI middleware, or to embed Django in another ASGI
application, you can wrap Django's application object in this file.
 mysite/[Link]: Settings/configuration for this Django project.
 mysite/[Link]: The URL declarations for this Django project; a “table of contents” of your
Djangopowered site.
 mysite/[Link]: An entry-point for WSGI-compatible web servers to serve your project.

8. Run Django Project


To run the Django project, we need to navigate to the mysite folder and execute the below
command in the command prompt:
C:\Users\Skillzam\Desktop\code\django\myDjangoEnv\mysite> py [Link] runserver
Now open the browser - Google Chrome and type [Link] in the address bar
to see the below result.

We have just started the Django development server, a lightweightWeb server written
purely in Python. Django development server is included, so that we can develop things
rapidly, without having to deal with configuring a production server - such as Apache - until
you're ready for production.
Hello World - using Django framework
1. Navigate to the selected location where we want to store the app, in our case
the firstApp folder, and run the below command:
C:\Users\Skillzam\Desktop\code\django\myDjangoEnv\mysite> py [Link] startapp
firstApp

That'll create a directory firstApp, which is laid out like this:


firstApp/
migrations/
__init__.py
__init__.py
[Link]
[Link]
[Link]
[Link]
[Link]

2. Create first view


Django views are Python functions that takes http requests and returns http response, like
HTML documents. Views are usually put in a file called [Link] located on your app's folder.
Open the file mysite/firstApp/[Link] and put the following Python code in it:
from [Link] import render
from [Link] import HttpResponse
# Create your views here.
def index(request):
return HttpResponse("Hello World!")

3. Create file [Link]


To call the view, we need to map it to a URL - and for this we need a URLconf. To create a
URLconf in the mysite/firstApp/ directory, create a file called [Link]
Create a file named [Link] in the same folder as the [Link] file, and type this code in it:
from [Link] import path
from . import views

urlpatterns = [
path('index/', [Link], name='index'),
]

4. Point the root URLconf


The next step is to point the root URLconf at the [Link] module.
There is a file called [Link] on the mysite folder, open that file and add the include module
in the import statement, and also add a path() function in the urlpatterns[] list, with
arguments that will route users that comes in via [Link]:8000/
from [Link] import admin
from [Link] import include, path

urlpatterns = [
path('', include('[Link]')),
path('admin/', [Link]),
]

5. Run Django Project containing the App


To run the Django project, we need to navigate to the mysite folder and execute the below
command in the command prompt:
C:\Users\Skillzam\Desktop\code\django\myDjangoEnv\mysite> py [Link] runserver
Now open the browser - Google Chrome and type [Link] in the
address bar to see the below result.

You might also like