Introduction to Python Programming
Introduction to Python Programming
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.
NOTE: Path in the command prompt should be where you have saved your file.
In the above case file should be saved at desktop.
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
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:
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
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] } ,
}
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
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
pin = "523"
print([Link]( )) # Output: True
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)
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 (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")
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
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:
*
**
***
****
*****
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 ( )
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
Recursion
Recursion is a technique in which a function call itself
Recursion uses stack data structure.
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.
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) #
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)
Similarly, the median of each column is computed with the median() method
[Link]()
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:
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])
Output:
[[1 2 3 4]
[5 6 7 8]]
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]
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:
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.
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.
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"}
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.
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]())
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:
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.
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]
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
urlpatterns = [
path('index/', [Link], name='index'),
]
urlpatterns = [
path('', include('[Link]')),
path('admin/', [Link]),
]