1st unit - Basics of Python
Features of Python:
Python is a versatile and widely-used programming language known for its
simplicity and readability. Here are some key features of Python:
1. Easy to Learn and Use: Python's syntax is straightforward and its code is
readable, making it a great language for beginners.
2. Interpreted Language: Python code is executed line-by-line, which makes
debugging easier and allows for dynamic typing.
3. Dynamically Typed: Variables in Python do not need explicit declaration to
reserve memory space. The declaration happens automatically when a
value is assigned to a variable.
4. Extensive Standard Library: Python comes with a vast standard library that
includes modules and packages for a wide range of tasks, from file I/O to
web development.
5. Open Source: Python is developed under an open-source license, making it
freely usable and distributable, even for commercial use.
6. Integration Capabilities: Python can easily integrate with other languages
and technologies, making it suitable for a variety of tasks, including web
development, scientific computing, artificial intelligence, and more.
7. Readability and Maintainability: Python's clear and concise syntax
improves code readability and maintainability, making it easier for
developers to understand and collaborate on projects.
8. Extensible: Python can be extended with modules and libraries, including
those written in C or C++, allowing for performance optimization.
These features make Python a popular choice for a wide range of applications,
from web development and data analysis to scientific computing and artificial
intelligence.
literal constants - numbers
1st unit - Basics of Python 1
In Python, literal constants are fixed values that are directly written into the
code. For numbers, Python supports several types of literal constants:
1. Integer Literals: Whole numbers without a fractional component.
a = 10
b = -5
c = 0
2. Floating-Point Literals: Numbers with a fractional component.
x = 3.14
y = -0.001
z = 2.0
3. Complex Literals: Numbers with a real and imaginary component.
complex_num1 = 3 + 4j
complex_num2 = -5j
These literals allow you to directly use numeric values in your Python
programs.
Variables:
Variables in Python are used to store data that can be referenced and
manipulated. Here’s how they perform with examples:
1. Creation and Assignment:
Variables are created the moment you first assign a value to them.
x = 10
name = "Alice"
is_valid = True
2. Multiple Assignment:
Assign values to multiple variables in one line.
1st unit - Basics of Python 2
a, b, c = 1, 2, 3
3. Swapping Values:
Easily swap the values of two variables.
a, b = 5, 10
a, b = b, a # a is now 10, b is now 5
4. Variable Types:
Python supports various types of variables, such as integers, floats,
strings, lists, tuples, dictionaries, etc.
age = 25 # Integer
pi = 3.14 # Float
greeting = "Hello" # String
names = ["Alice", "Bob", "Eve"] # List
point = (10, 20) # Tuple
user = {"name": "Alice", "age": 30} # Dictionary
5. Using Variables in Expressions:
Variables can be used in mathematical and logical expressions.
x = 5
y = x + 10 # y is 15
is_adult = age > 18 # is_adult is True
6. Deleting Variables:
You can delete a variable using the del keyword.
del x
Attempting to use x after deletion will result in an error:
# print(x) # NameError: name 'x' is not defined
1st unit - Basics of Python 3
These examples illustrate how variables in Python are flexible, easy to use, and
an integral part of programming in Python.
Identifiers:
Identifiers in Python are names used to identify variables, functions, classes,
modules, and other objects. Here are the key rules and conventions for creating
identifiers in Python:
1. Rules for Identifiers:
An identifier must start with a letter (a-z, A-Z) or an underscore (_).
The rest of the identifier can contain letters, digits (0-9), or
underscores.
Identifiers are case-sensitive (e.g., myVar and myvar are different).
Reserved words (keywords) cannot be used as identifiers.
Examples:
variable1 = 10
_variable = "hello"
my_var = 3.14
2. Naming Conventions:
Variable and Function Names: Use lowercase words separated by
underscores (snake_case).
total_sum = 100
def calculate_total():
pass
3. Reserved Words (Keywords):
Python has a set of reserved words that cannot be used as identifiers.
Examples include if , else , while , for , def , class , import , True , False ,
None , and many others.
To view the list of keywords in Python, you can use the following code:
1st unit - Basics of Python 4
import keyword
print(keyword.kwlist)
Identifiers are crucial for writing clear and maintainable code. Following the
naming conventions and rules ensures that your code is readable and free from
naming conflicts.
Note : for exam start preparing from data types
data types:
Python has several built-in data types that are used to store different kinds of
data. Here are the main data types along with examples:
1. Numeric Types:
Integer ( int ): Whole numbers, positive or negative, without a decimal
point.
a = 10
b = -5
Floating Point ( float ): Numbers with a decimal point.
x = 3.14
y = -0.001
2. Sequence Types:
String ( str ): Ordered collection of characters enclosed in single,
double, or triple quotes.
s = "Hello, World!"
multiline_string = '''This is a
multiline string.'''
List ( list ): Ordered collection of items that are changeable and allow
duplicate elements.
fruits = ["apple", "banana", "cherry"]
1st unit - Basics of Python 5
Tuple ( tuple ): Ordered collection of items that are unchangeable and
allow duplicate elements.
coordinates = (10.0, 20.0)
3. Mapping Type:
Dictionary ( dict ): Unordered collection of key-value pairs.
student = {"name": "Alice", "age": 25, "grade": "A"}
4. Boolean Type:
Boolean ( bool ): Represents one of two values: True or False .
is_active = True
is_logged_in = False
5. Range Type:
Range ( range ): Represents an immutable sequence of numbers and is
commonly used for looping a specific number of times in for loops.
numbers = range(1, 10)
These data types are the building blocks of Python programming and are used
to store and manipulate data in various ways. Understanding these types helps
in writing efficient and effective Python code.
Operations in Python:
Python supports a wide range of operations, including arithmetic, comparison,
logical, bitwise, assignment, and membership operations. Here’s a summary of
these operations with examples:
1. Arithmetic Operations
These are used to perform basic mathematical calculations.
Addition ( + )
1st unit - Basics of Python 6
result = 10 + 5 # result is 15
Subtraction ( )
result = 10 - 5 # result is 5
Multiplication ( )
result = 10 * 5 # result is 50
Division ( / )
result = 10 / 5 # result is 2.0
Floor Division ( // )
result = 10 // 3 # result is 3
Modulus ( % )
result = 10 % 3 # result is 1
Exponentiation ( * )
result = 2 ** 3 # result is 8
2. Comparison Operations
These operations compare two values and return a boolean ( True or False ).
Equal to ( == )
result = (10 == 10) # result is True
Not equal to ( != )
result = (10 != 5) # result is True
1st unit - Basics of Python 7
Greater than ( > )
result = (10 > 5) # result is True
Less than ( < )
result = (10 < 5) # result is False
Greater than or equal to ( >= )
result = (10 >= 5) # result is True
Less than or equal to ( <= )
result = (10 <= 5) # result is False
3. Logical Operations
These operations are used to combine conditional statements.
Logical AND ( and )
result = (10 > 5) and (10 < 20) # result is True
Logical OR ( or )
result = (10 > 5) or (10 < 5) # result is True
Logical NOT ( not )
result = not (10 > 5) # result is False
These operations form the core of working with data and performing
calculations in Python. Understanding and using these operations effectively is
fundamental to programming in Python.
STRING FUNCTIONS:
In string functions we have the following methods:
1st unit - Basics of Python 8
1. Capitalize
2. Case fold
3. Count
4. Copy
5. Clear
6. Ends with
7. Find
8. Index
9. Title
10. Lower
11. Upper
12. Replace
CAPITALIZE: Here the first letter of the string will be replaced to upper case
letter.
Example :-
name = “prajitha tammana”
name.capitalize()
Output : ‘prajitha tammana’
CASE FOLD: Here the string will be converted into lower case letters.
Example :-
name = “PRAJITHA TAMMANA”
name.casefold()
Output : ‘prajitha tammana’
COUNT: It tells us how many times a letter has been repeated in that string
Example :-
1st unit - Basics of Python 9
name = “prajitha tammana”
name.count(“a”)
Output : 5
CLEAR: It clears the entire string.
ENDSWITH: It tells us if the string ends with that letter or not.
Example :-
name = “prajitha tammana”
name.endswith(“p”)
Output : False
FIND: It finds the index of a given letter in the string.
Example :-
name = “prajitha tammana”
name.find(“a”)
Output : 2
INDEX: It tells the index value of the given letter in that string
Example :-
name = “prajitha tammana”
name.index(“t”)
Output : 5
NOTE: If the given letter occurs more than one time in a string it gives the
index value of the first time it occurred.
TITLE: It converts the first letter of the word into upper case letter.
Example :-
1st unit - Basics of Python 10
name = “prajitha tammana”
Name.title()
Output : ‘Prajitha Tammana’
LOWER: It converts the entire string into lower case letters.
Example :-
name = “ PRAJITHA TAMMANA “
name.lower()
Output : ‘prajitha tammana’
UPPER: It converts the entire string into upper case letters.
Example :-
name = “prajitha tammana”
name.upper()
Output : ‘PRAJITHA TAMMANA’
REPLACE: It replaces the given letter into our desired letter.
Example :-
name = “prajitha tammana”
name.replace(“p”,”a”)
Output : ‘arajitha tammana’
IF-ELSE:
If else conditions are used to print the statements based on the condition if it is
true or false
These are denoted as:
if (condition):
1st unit - Basics of Python 11
Statement
else:
Statements
EVEN OR ODD:
n=10
if n%2==0:
print("n=10
if n%2==0:
print("The number is even")
else:
print("The number is odd")
Output : The number is even
TO CHECK WHETHER THE NUMBER IS POSITIVE, NEGATIVE OR ZERO:
Example :
n= int (input(“Enter a number:”))
if n>0:
print("The number is positive")
elif n==0:
print("The number is zero")
else:
print("The number is negative")
Output :
Enter a number: 4
The number is positive
GRADING THE MARKS:
n= int (input("Enter your marks:"))
if n>=90:
print("O")
elif 80<=n<90:
print("A")
elif 70<=n<=80:
1st unit - Basics of Python 12
print("B")
else:
print("C")
Output :
Enter your marks: 92
O
COMPARISON OF THREE NUMBERS:
a = int (input("Enter a value: "))
b = int (input("Enter b value: "))
c = int (input("Enter c value: "))
if b<a>c:
print("a is bigger")
elif a<b>c:
print("b is bigger")
else:
print("c is bigger")
Output :
Enter a value: 10
Enter b value: 15
Enter c value: 12
b is bigger
Loops in Python:
Definition:
Loops in Python are used to repeat a block of code multiple times. There are
two main types:
for loops and while loops.
Types of Loops
1. for Loop:
Iterates over a sequence (e.g., list, string, range).
Syntax:
1st unit - Basics of Python 13
for item in sequence:
# code block
Example:
for i in range(5):
print(i)
More examples :
for a in range(1,11):
print(n,"*",a,"=",n*a)
Output :
2
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20
1. while Loop:
Repeats as long as a condition is true.
Syntax:
while condition:
# code block
Example:
i = 0
while i < 5:
1st unit - Basics of Python 14
print(i)
i += 1
Loops are fundamental for automating repetitive tasks and iterating over data
structures in Python.
Loop Control Statements
1. break :
Exits the loop prematurely.
Example:
for i in range(10):
if i == 5:
break
print(i)
2. continue :
Skips the current iteration and moves to the next.
Example:
for i in range(5):
if i == 2:
continue
print(i)
3. else :
Executed after the loop finishes normally (not by break ).
Example:
for i in range(5):
print(i)
else:
print("Loop completed")
1st unit - Basics of Python 15