0% found this document useful (0 votes)
2 views43 pages

Elements of Python

The document outlines the fundamental elements of Python programming, including keywords, identifiers, literals, operators, comments, delimiters, and indentation. It emphasizes the importance of understanding these elements for writing correct and professional Python code. Additionally, it provides examples and best practices for using these elements effectively.

Uploaded by

kavya.gupta.ug25
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)
2 views43 pages

Elements of Python

The document outlines the fundamental elements of Python programming, including keywords, identifiers, literals, operators, comments, delimiters, and indentation. It emphasizes the importance of understanding these elements for writing correct and professional Python code. Additionally, it provides examples and best practices for using these elements effectively.

Uploaded by

kavya.gupta.ug25
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

Elements of Python

Building Blocks of Python Programs

1 / 43
Contents

1 Introduction
2 Keywords
3 Identifiers
4 Literals
5 Operators
6 Comments
7 Delimiters
8 Indentation
9 Complete Example
10 Practice
11 Summary

2 / 43
What are Elements of Python

Definition
Elements are the basic building blocks used to write Python programs.

Main Elements:
Keywords
Identifiers
Literals
Operators
Comments
Delimiters

3 / 43
Why Learn Elements

Understanding elements helps you:


Write correct Python code
Follow naming rules
Understand syntax
Avoid errors
Write professional code

4 / 43
Python Keywords

What are Keywords


Keywords are reserved words with special meaning in Python.

Important Points:
Cannot be used as variable names
Have predefined meaning
Case sensitive
Total 35 keywords in Python

5 / 43
Common Python Keywords

if else elif for


while break continue pass
def return class import
from as True False
None and or not
in is try except

6 / 43
Keywords Examples

# if , else keywords
if age > 18:
print ( " Adult " )
else :
print ( " Minor " )

# for keyword
for i in range (5) :
print ( i )

# while keyword
while x < 10:
x = x + 1

# def keyword
def greet () :
print ( " Hello " )

7 / 43
Keywords Cannot be Variable Names

Wrong Usage:
# ERROR - Keywords cannot be variables
if = 10 # Wrong
for = 20 # Wrong
class = 30 # Wrong

Correct Usage:
# Correct variable names
age = 10
count = 20
marks = 30

8 / 43
Identifiers

What are Identifiers


Identifiers are names given to variables, functions, classes, etc.

Examples:
Variable names: age, name, total
Function names: calculate, display
Class names: Student, Employee

9 / 43
Rules for Identifiers

Naming Rules:
1 Must start with letter or underscore
2 Can contain letters, digits, underscores
3 Cannot start with digit
4 Case sensitive
5 Cannot be a keyword
6 No special symbols except underscore

10 / 43
Valid and Invalid Identifiers

Valid Identifiers:
name
age
total_marks
student1
_temp
myVariable

Invalid Identifiers:
2 name # Starts with digit
total - marks # Contains hyphen
my variable # Contains space
for # Keyword
@value # Special character

11 / 43
Case Sensitivity

Python is case sensitive:


# These are different variables
name = " John "
Name = " Alice "
NAME = " Bob "

print ( name ) # Output : John


print ( Name ) # Output : Alice
print ( NAME ) # Output : Bob

12 / 43
Naming Conventions

Best Practices:
Use meaningful names
Variables: lowercase with underscores
Functions: lowercase with underscores
Classes: CapitalCase
Constants: UPPERCASE

Examples:
student name (variable)
calculate total() (function)
StudentRecord (class)
MAX VALUE (constant)

13 / 43
Literals

What are Literals


Literals are fixed values in the program.

Types of Literals:
Numeric Literals
String Literals
Boolean Literals
Special Literal (None)

14 / 43
Numeric Literals

Integer Literals:
age = 25
count = 100
negative = -50

Float Literals:
price = 99.99
height = 5.8
pi = 3.14159

15 / 43
String Literals

Single quotes:
name = ’ John ’
city = ’ Delhi ’

Double quotes:
message = " Hello World "
text = " Python Programming "

Triple quotes (multiline):


paragraph = " " " This is
a multiline
string " " "

16 / 43
Boolean and Special Literals

Boolean Literals:
is_student = True
is_passed = False

None Literal:
result = None
value = None

Note: None represents absence of value

17 / 43
Operators

What are Operators


Operators perform operations on values and variables.

Types of Operators:
Arithmetic Operators
Comparison Operators
Logical Operators
Assignment Operators

18 / 43
Arithmetic Operators

Operator Name Example


+ Addition 5+3=8
- Subtraction 5-3=2
* Multiplication 5 * 3 = 15
/ Division 10 / 2 = 5.0
// Floor Division 10 // 3 = 3
% Modulus 10 % 3 = 1
** Power 2 ** 3 = 8

19 / 43
Arithmetic Operators Example

# Basic arithmetic
a = 10
b = 3

print ( a + b) # 13
print ( a - b) # 7
print ( a * b) # 30
print ( a / b) # 3.333...
print ( a // b ) # 3
print ( a % b) # 1
print ( a ** b ) # 1000

20 / 43
Comparison Operators

Operator Name Example


== Equal to 5 == 5 (True)
!= Not equal 5 != 3 (True)
¿ Greater than 5 ¿ 3 (True)
¡ Less than 5 ¡ 3 (False)
¿= Greater or equal 5 ¿= 5 (True)
¡= Less or equal 3 ¡= 5 (True)

21 / 43
Comparison Operators Example

# Comparison operations
x = 10
y = 5

print ( x == y ) # False
print ( x != y ) # True
print ( x > y) # True
print ( x < y) # False
print ( x >= 10) # True
print ( y <= 5) # True

22 / 43
Logical Operators

Operator Description
and Returns True if both are True
or Returns True if one is True
not Reverses the result

Examples:
True and True = True
True and False = False
True or False = True
not True = False

23 / 43
Logical Operators Example

# Logical operations
age = 20
marks = 85

# and operator
if age > 18 and marks > 80:
print ( " Eligible for scholarship " )

# or operator
if age < 18 or marks < 50:
print ( " Special case " )

# not operator
is_student = True
if not is_student :
print ( " Not a student " )

24 / 43
Assignment Operators

Operator Example Same As


= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3

25 / 43
Assignment Operators Example

# Assignment operators
x = 10

x += 5 # x = x + 5 , now x = 15
print ( x )

x -= 3 # x = x - 3 , now x = 12
print ( x )

x *= 2 # x = x * 2 , now x = 24
print ( x )

x /= 4 # x = x / 4 , now x = 6.0
print ( x )

26 / 43
Comments

What are Comments


Comments are notes in code that Python ignores.

Purpose:
Explain code
Make code readable
Document your work
Temporarily disable code

27 / 43
Single Line Comments

Use hash symbol:


# This is a comment
print ( " Hello " )

age = 20 # This is also a comment

# Calculate total
total = price * quantity

28 / 43
Multi Line Comments

Use triple quotes:


"""
This is a
multi - line comment
explaining the program
"""

print ( " Program starts here " )

’’’
Another way to write
multi - line comments
’’’

29 / 43
Good Commenting Practice

# Good comments explain WHY

# Calculate discount for premium members


discount = price * 0.2

# Bad comments explain WHAT ( obvious )


# Add 5 to x
x = x + 5

30 / 43
Delimiters

What are Delimiters


Special characters that separate code elements.

Common Delimiters:
Parentheses: ( )
Brackets: [ ]
Braces: { }
Comma: ,
Colon: :
Semicolon: ;

31 / 43
Delimiters Usage

# Parentheses - function calls


print ( " Hello " )
result = max (10 , 20)

# Brackets - lists
numbers = [1 , 2 , 3 , 4 , 5]

# Braces - dictionaries
student = { " name " : " John " , " age " : 20}

# Colon - blocks
if age > 18:
print ( " Adult " )

# Comma - separating items


print ( " Name : " , name , " Age : " , age )

32 / 43
Indentation in Python

What is Indentation
Spaces at the beginning of a line to define code blocks.

Important Points:
Python uses indentation for blocks
Use 4 spaces (standard)
Must be consistent
No curly braces needed

33 / 43
Correct Indentation

# Correct indentation
if age > 18:
print ( " Adult " )
print ( " Can vote " )

for i in range (5) :


print ( i )
print ( " Number " )

def greet () :
print ( " Hello " )
print ( " Welcome " )

34 / 43
Incorrect Indentation

# Wrong - inconsistent indentation


if age > 18:
print ( " Adult " ) # Error
print ( " Can vote " ) # Error

# Wrong - mixed spaces


for i in range (5) :
print ( i )
print ( " Number " ) # Error

35 / 43
Program Using All Elements
# Student Grade Calculator
# This program calculates average marks

# Get student information


name = input ( " Enter name : " )
math = float ( input ( " Math marks : " ) )
science = float ( input ( " Science marks : " ) )

# Calculate average
total = math + science
average = total / 2

# Display result
if average >= 50:
print ( name , " Passed " )
print ( " Average : " , average )
else :
print ( name , " Failed " )
36 / 43
Elements in the Example

Elements used:
Keywords: if, else
Identifiers: name, math, science, total
Literals: ”Enter name:”, 50, 2
Operators: =, +, /, ¿=
Comments: Lines starting with #
Delimiters: ( ) , :
Indentation: Lines under if/else

37 / 43
Practice Exercise 1

Task: Identify elements in this code

Code:
age = 20
if age ¿ 18:
print(”Adult”)

Find:
Keywords
Identifiers
Literals
Operators

38 / 43
Exercise 1 Solution

Elements identified:
Keywords: if
Identifiers: age
Literals: 20, 18, ”Adult”
Operators: =, ¿
Delimiters: ( ) :
Comment: None

39 / 43
Practice Exercise 2

Which are valid identifiers?


1 my variable
2 2name
3 total-marks
4 temp
5 for
6 myVar123

40 / 43
Exercise 2 Solution

Valid Identifiers:
my variable (Yes)
2name (No - starts with digit)
total-marks (No - contains hyphen)
temp (Yes)
for (No - keyword)
myVar123 (Yes)

41 / 43
Important

Keywords are reserved words


Identifiers are user-defined names
Follow naming rules strictly
Literals are fixed values
Operators perform operations
Comments explain code
Indentation is mandatory
Use meaningful names

42 / 43
Quick Reference

Element Example
Keyword if, for, while
Identifier age, name, total
Literal 10, ”Hello”, True
Operator +, -, ==, and
Comment # This is comment
Delimiter ()[]: ,

43 / 43

You might also like