java and its benifits
java and its benifits
python
# This is a comment
print("Hello, World!")
Variables:
oDefinition: Named locations
used to store data.
oDynamic Typing: No need to
declare the type; it’s inferred
from the value.
oExample:
python
x = 10 # int
y = 3.14 # float
name = "Alice" # str
Types:
oCommon Types: int, float,
str, bool, list, tuple,
set, dict.
oType Conversion: Use functions
like int(), float(), str(),
etc.
python
age = "21"
age = int(age) #
Converts to integer
Flow Control:
If:
o Definition: Executes a block of
code if a condition is true.
o Syntax:
python
if condition:
# code block
If-else:
o Definition: Executes one block if
the condition is true, another
block if false.
o Syntax:
python
if condition:
# code block
else:
# another block UNIT-I:
Basics of Python Programming
Python Introduction:
Definition: Python is a high-level,
interpreted programming language
known for its simplicity and
readability. Created by Guido van
Rossum and first released in 1991,
Python emphasizes code readability
and allows programmers to express
concepts in fewer lines of code
compared to languages like C++ or
Java.
Key Features:
oInterpreted: Python code is
executed line-by-line, making
debugging easier.
oHigh-level: Python abstracts
away many of the complex
details of the computer's
hardware.
oDynamically Typed: Variable
types are determined at runtime,
not in advance.
oPortable: Python code can run
on various platforms without
modification.
Installing and Setting Python
Environment in Windows and Linux:
Windows:
1. Download the Python installer
from the official Python website.
2. Run the installer and ensure
you check the "Add Python to
PATH" option.
3. Verify installation by running
python --version in the
command prompt.
For Loop:
oDefinition: Iterates over a
sequence (e.g., list, tuple, string).
oSyntax:
python
for i in range(1, 10,
2):
print(i) # 1, 3,
5, 7, 9
Continue:
oDefinition: Skips the rest of the
code inside the loop for the
current iteration and moves to the
next iteration.
oSyntax:
python
for i in range(5):
if i == 3:
continue
print(i) # 0, 1,
2, 4
Pass:
oDefinition: Does nothing; used
as a placeholder.
oSyntax:
python
for i in range(5):
if i == 3:
pass #
Placeholder for future
code
print(i) # 0, 1,
2, 3, 4
Break:
oDefinition: Exits the loop
prematurely.
oSyntax:
python
for i in range(5):
if i == 3:
break
print(i) # 0, 1,
2
Strings:
Sequence Operations:
o Definition: Operations that can
be performed on sequences, like
strings.
o Example:
python
text = "hello"
print(text[0]) # 'h'
print(text[1:4]) #
'ell'
print(text + " world")
# 'hello world'
print(text * 2) #
'hellohello'
String Methods:
o Definition: Built-in methods for
manipulating strings.
o Example:
python
text = " Hello, World!
"
text = text.lower() #
' hello, world! '
text = text.upper() #
' HELLO, WORLD! python
for item in sequence:
# code block
While Loop:
oDefinition: Repeatedly executes
a block of code as long as a
condition is true.
oSyntax:
python
while condition:
# code block
Range Function:
oDefinition: Generates a sequence
of numbers.
oSyntax:
python
range(start, stop,
step)
o Example:
'
text = text.strip() #
'Hello, World!'
text =
text.find("World") #
7
text =
text.replace("Hello",
"Hi") # ' Hi, World!
'
Pattern Matching:
o Definition: Using regular
expressions (re module) to
search for patterns in strings.
o Example:
python
import re
pattern = r'\bword\b'
if re.search(pattern,
text):
print("Match
found!")
Removing Elements:
Use remove() to remove an
element from the set.
python
my_set.remove(3)
discard() Method: Similar to
remove(), but does not raise an
error if the element is not found.
python
my_set.discard(10) #
Does nothing since 10 is
not in the set
Set Operations:
Union: Combines elements from
both sets.
python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2
# {1, 2, 3, 4, 5}
Intersection: Returns common
elements from both sets.
python
intersection_set = set1
& set2 # {3}
Difference: Returns elements in the
first set but not in the second.
python
difference_set = set1 -
set2 # {1, 2}
Symmetric Difference: Returns
elements in either set, but not in
both.
python
symmetric_difference_set
= set1 ^ set2 # {1, 2,
4, 5}
Iteration:
Loop through elements in a set using
a for loop.
python
for item in my_set:
print(item)
Summary Comparison
Featu Dictiona
Lists Tuples Sets
re ries
def outer():
x = "enclosing"
def inner():
x = "local"
print(x) #
Output: local
inner()
print(x) # Output:
enclosing
outer()
print(x) # Output: global
Modules
Module Coding Basics:
A module is a file containing Python
definitions and statements. The file
name is the module name with the
suffix .py.
Example: mymodule.py
python
# mymodule.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Importing Programs as Modules:
Use the import statement to
include the module in your code.
python
import mymodule
print(mymodule.add(5,
3)) # Output: 8
From Import Statement: Import
specific functions or variables from
a module.
python
from mymodule import add
print(add(5, 3)) #
Output: 8
Executing Modules as Scripts:
Use the special variable __name__
to determine if the module is being
run on its own or being imported
somewhere else.
python
# mymodule.py
def main():
print("This is a
script")
if __name__ ==
"__main__":
main()
Compiled Python Files (.pyc):
When a Python script is run, the
Python interpreter compiles the code
to bytecode, which is stored in
.pyc files in the __pycache__
directory. This makes the program
start faster on subsequent runs.
Standard Modules:
Python comes with a standard
library of modules. Some useful
standard modules include:
o os Module: Provides a way to
interact with the operating
system.
python
import os
print(os.getcwd()) #
Output: Current
working directory
o sys Module: Provides access to
some variables used or
maintained by the interpreter and
to functions that interact with the
interpreter.
python
import sys
print(sys.version) #
Output: Python version
The dir() Function:
The dir() function is used to list
the names in the current local scope
or the attributes of a given object.
python
import mymodule
print(dir(mymodule)) #
Output: List of
attributes and functions
in mymodule
Packages:
A package is a way of structuring
Python’s module namespace by
using “dotted module names”. A
package is a collection of modules.
Creating a Package: Create a
directory and add an
__init__.py file to it, which
indicates that the directory is a
package.
o Directory Structure:
o mypackage/
o __init__.py
o module1.py
o module2.py
o Importing from a Package:
python
from mypackage import
module1
from mypackage.module2
import function
Summary Comparison
Topi Descrip
Example Code
c tion
Func Reusabl def greet(name):
tions e print(f"Hello,
blocks {name}!")<br>greet
of code ("Alice")
Topi Descrip
Example Code
c tion
that
perform
a
specific
task
Executi
Func ng a
tion functio greet("Alice")
Call n by its
name
Values def greet(name,
Argu passed greeting="Hello")
ment to a
:<br>greet("Alice"
s functio
, greeting="Hi")
n
Scop Variabl x =
e e "global"<br>def
Rules visibilit outer(): x =
y "enclosing" def
Topi Descrip
Example Code
c tion
governe
d by inner(): x =
LEGB "local" print(x)
rule
Files import
containi
Mod mymodule<br>print(
ng
ules mymodule.add(5,
Python
3))
code
Includi from mymodule
Impo
ng a import
rting
module
Mod add<br>print(add(5
in your
ules , 3))
code
Exec Runnin if __name__ ==
uting g a "__main__":
as module main()
Scrip as the
t main
Topi Descrip
Example Code
c tion
progra
m
.pyc
files
Com
created The .pyc files in the
piled
to
Pyth __pycache__
improv
on directory
e
Files
perform
ance
Pre-
installe import
Stan d os<br>print(os.get
dard module
cwd())<br>import
Mod s such
sys<br>print(sys.v
ules as os
ersion)
and
sys
dir( Lists import
Topi Descrip
Example Code
c tion
names
in the
current
local
)
scope mymodule<br>print(
Func
or dir(mymodule))
tion
attribut
es of a
given
object
Pack Collecti from mypackage
ages on of import
module module1<br>from
s mypackage.module2
structur import function
ed with
director
ies and
__ini
Topi Descrip
Example Code
c tion
t__.p
y files