0% found this document useful (0 votes)
4 views41 pages

Unit - 1 - Introduction Python Part - 2

The document provides an introduction to Python, highlighting its features such as readability, dynamic typing, and ease of use. It covers various aspects of Python programming including data types, operators, and sets, as well as installation and execution methods. Additionally, it discusses constants, keywords, and command line arguments in Python.

Uploaded by

sk8662959
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)
4 views41 pages

Unit - 1 - Introduction Python Part - 2

The document provides an introduction to Python, highlighting its features such as readability, dynamic typing, and ease of use. It covers various aspects of Python programming including data types, operators, and sets, as well as installation and execution methods. Additionally, it discusses constants, keywords, and command line arguments in Python.

Uploaded by

sk8662959
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

voodoo

Chapter - 1

1
voodoo
Features of Python

IDE and Code Editor

Python Variables & Data Types

Basic Operators

Branching

Iterators

Break & Continue

Input

2
voodoo
Introduction to Python
 Python is a widely used general-purpose, high level programming language.
 It was initially designed by Guido van Rossum in 1991 and developed by Python Software
Foundation.
 It was mainly developed for emphasis on code readability, and its syntax allows
programmers to express concepts in fewer lines of code.
 Python is a programming language that lets you work quickly and integrate systems more
efficiently.

3
voodoo
Features of Python

Python is object-oriented

Indentation

It’s free (open source) Downloading python and installing python is free and easy

4
voodoo
Features of Python

• Dynamic typing
• Built-in types and tools
It’s Powerful • Library utilities
• Third party utilities (e.g. Numeric, NumPy, sciPy)
• Automatic memory management

It’s Portable

• No intermediate compile

• Python Programs are compiled automatically to an intermediate form called byte code,
which the interpreter then reads.
It’s easy to use and learn
• This gives python the development speed of an interpreter without the performance loss
inherent in purely interpreted languages.

• Structure and syntax are pretty intuitive and easy to grasp.


5
voodoo
Features of Python

Interpreted Language

Interactive Programming Users can interact with the python interpreter directly for writing the programs
Language

The formation of python syntax is simple and straight forward which also makes it
Straight forward syntax
popular.

6
voodoo
Installation
 There are many interpreters available freely to run Python scripts like IDLE (Integrated Development
Environment) which is installed when you install the python software from [Link]

 Steps to be followed and remembered:

Step 1: Select Version of Python to Install.

Step 2: Download Python Executable Installer.

Step 3: Run Executable Installer.

Step 4: Verify Python Was Installed On Windows.

Step 5: Verify Pip Was Installed.

Step 6: Add Python Path to Environment Variables (Optional)

7
voodoo
Working with Python
Python Code Execution:

 Python’s traditional runtime execution model: Source code you type is translated to byte code, which is then run by the
Python Virtual Machine (PVM).
 Your code is automatically compiled, but then it is interpreted.

8
voodoo
Working with Python

There are two modes for using the Python interpreter:

• Interactive Mode

• Script Mode

9
voodoo
Variables

10
voodoo
11
voodoo
Basic Data Types

Integer Float Complex Boolean

Integers are used to Float data type is Complex numbers Boolean is used for
represent whole used to represent are used to categorical o/p,
number values. decimal point represent since the o/p of
values. imaginary values. Boolean is either
Ex, x = 10 true or false.
Ex, x = 2.5 Ex, x = 2 + 3j
Ex. X = 1> 2
12
voodoo
Why integer when there is float ?????

13
voodoo
Python Operators
 Arithmetic operators

 Assignment operators

 Comparison operators

 Logical operators

 Identity operators

 Membership operators

 Bitwise operators

14
Python Arithmetic Operators

voodoo
X = 10 & Y = 6

Operator Name Example Output

+ Addition x+y 16

- Subtraction x-y 4

* Multiplication x*y 60

/ Division x/y 1.66

% Modulus x%y 4

** Exponentiation x ** y 1000000

// Floor division x // y 1
15
voodoo
Python 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

%= x %= 3 x=x%3

//= x //= 3 x = x // 3

16
voodoo
Python Comparison
Operators

Operator Name Example


== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

17
voodoo
Python Logical
Operators

Operator Description Example


and Returns True if both statements are true x < 5 and x < 10

or Returns True if one of the statements is x < 5 or x < 4


true
not Reverse the result, returns False if the not(x < 5 and x < 10)
result is true

18
voodoo
Python Identity
Operators

Operator Name Example


is Returns True if both variables are the same x is y
object
is not Returns True if both variables are not the x is not y
same object

19
voodoo
Python Membership Operators

Operator Name Example

in Returns True if a sequence with the specified value x in y


is present in the object

not in Returns True if a sequence with the specified value x not in y


is not present in the object

20
Python Bitwise

voodoo
Operators

Operator Name Example

& AND Sets each bit to 1 if both bits are 1

| OR Sets each bit to 1 if one of two bits is 1

^ XOR Sets each bit to 1 if only one of two bits is 1

~ NOT Inverts all the bits

<< Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits
fall off

>> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and
let the rightmost bits fall off
21
voodoo
Python Input

 input()

 input().split(separator, maxsplit)

22
voodoo
Sets in Python

 A Set in Python is used to store a collection of items with the following properties.

 No duplicate elements. If you try to insert the same item again, it overwrites the

previous one.

 An unordered collection. When we access all items, they are accessed without any

specific order, and we cannot access items using indexes as we do in lists.

 Internally use hashing that makes the set efficient for search, insert and delete

operations. It gives a major advantage over a list for problems with these operations.

 Mutable, meaning we can add or remove elements after their creation, the individual

elements within the set cannot be changed directly.


23
voodoo
Sets in Python

 Example of Python Sets

s = {10, 50, 20}

print(s)

print(type(s))

OUTPUT –

{10, 50, 20}

<class 'set'>

Note : There is no specific order for set elements to be printed


24
voodoo
Sets in Python

 Check unique and Immutable with Python Set

 Python sets cannot have duplicate values. While you cannot modify the individual

elements directly, you can still add or remove elements from the set.

# a set cannot have duplicate values

s = {“NFSU", “IIT", “NFSU"}


print(s)

# values of a set cannot be changed

s[1] = "Hello"
print(s)

25
voodoo
Sets in Python

 Heterogeneous Element with Python Set

 Python sets can store heterogeneous elements in it, i.e., a set can store a mixture of

string, integer, boolean, etc datatypes.

s = {"Geeks", "for", 10, 52.7, True}


print(s)

OUTPUT –

{True, 'for', 'Geeks', 10, 52.7}

26
voodoo
Sets in Python

 Python Frozen Sets

 Frozen sets in Python are immutable objects that only support methods and operators

that produce a result without affecting the frozen set or sets to which they are applied.

 It can be done with the frozenset() method in Python.

 While elements of a set can be modified at any time, elements of the frozen set remain the

same after creation.

27
voodoo
Sets in Python
# Same as {"a", "b","c"}
s = set(["a", "b","c"])
print("Normal Set")
print(s)

# A frozen set
fs = frozenset(["e", "f", "g"])
print("\nFrozen Set")
print(fs)

OUTPUT –

Normal Set
set(['a', 'c', 'b'])

Frozen Set
frozenset(['e', 'g', 'f'])

28
voodoo
Methods for Sets
1) Adding elements to Python Sets – [Link]()

2) Union operation on Python Sets – [Link]() or you can also use ‘|’ Symbol

3) Intersection operation on Python Sets – [Link]() or you can also use ‘&’ Symbol

4) Finding Differences of Sets in Python – [Link]() or you can also use ‘-’ Symbol

5) Clearing Python Sets - [Link]()

29
voodoo
Literals in Python
1) Literals in Python are fixed values written directly in the code that
represent constant data.

2) They provide a way to store numbers, text, or other essential


information that does not change during program execution.

3) Python supports different types of literals, such as numeric literals,


string literals, Boolean literals, and special values like None.

4) For example:

10, 3.14, and 5 + 2j are numeric literals.


'Hello' and "Python" are string literals.
True and False are Boolean literals. 30
voodoo
Python Constant
1) In Python, constants are variables whose values are intended to
remain unchanged throughout a program.

2) They are typically defined using uppercase letters to signify their


fixed nature, often with words separated by underscores (e.g.,
MAX_LIMIT).

3) For Example :
# Mathematical constant
PI = 3.14159

# Acceleration due to gravity


GRAVITY = 9.8

print(PI)
print(GRAVITY) 31
voodoo
Python Constant
Rules while declaring a Constant

1) Python constant and variable names can include:


Lowercase letters (a-z)
Uppercase letters (A-Z)
Digits (0-9)
Underscores (_)
2) Naming rules for constants:
Use UPPERCASE letters for constant
Do not start a constant name with a digit.
Only the underscore (_) is allowed as a special character
3) Best practices for naming constants:
Use meaningful and descriptive names to make the code clearer and easier
to understand.
32
voodoo
Python Constant
How to create immutable constants?

The example using namedtuple is correct and demonstrates how to


create immutable constants. Here's why this works:

A namedtuple creates a lightweight, immutable object where fields


can be accessed like attributes.

While you can access values using [Link], you cannot modify
them.

33
voodoo
Python Constant
How to create immutable constants?

from collections import namedtuple

Constants = namedtuple('Constants', ['PI', 'GRAVITY'])


constants = Constants(PI=3.14159, GRAVITY=9.8)

# [Link] = 3.14
print([Link])

34
voodoo
Python Keywords and Identifiers
1) Python Keywords are reserved words with fixed meanings that
define Python’s syntax. Cannot be used as names.

2) Python Identifiers are user-defined names for variables, functions,


or classes. Must follow naming rules (no digits at start, only _
allowed).

3) Keywords in Python

Predefined and reserved words with special meanings.


Used to define the syntax and structure of Python code.
Cannot be used as identifiers, variables, or function names.
Written in lowercase, except True and False.
Python 3.11 has 35 keywords.
35
voodoo
Python Keywords and Identifiers
The keyword module provides:

1) iskeyword() → checks if a string is a keyword.

1) kwlist → returns the list of all keywords.

Rules for Keywords in Python


Python keywords cannot be used as identifiers. All the keywords in
Python should be in lowercase except True and False.

import keyword

print([Link])

36
voodoo
Command Line Arguments in Python
The arguments that are given after the name of the program
in the command line shell of the operating system are
known as Command Line Arguments.

Python provides various ways of dealing with these types


of arguments.

37
voodoo
Command Line Arguments in Python
Using [Link]

The sys module provides functions and variables used to manipulate different parts
of the Python runtime environment.

This module provides access to some variables used or maintained by the


interpreter and to functions that interact strongly with the interpreter.

One such variable is [Link] which is a simple list structure.

It's main purpose are:

It is a list of command-line arguments.


len([Link]) provides the number of command line arguments.
[Link][0] is the name of the current Python script.

38
voodoo
Command Line Arguments in Python
import sys

# total arguments
n = len([Link])
print("Total arguments passed:", n)

# Arguments passed
print("\nName of Python script:", [Link][0])

print("\nArguments passed:", end = " ")


for i in range(1, n):
print([Link][i], end = " ")

# Addition of numbers
Sum = 0
# Using argparse module
for i in range(1, n):
Sum += int([Link][i])

print("\n\nResult:", Sum) 39
voodoo
Command Line Arguments in Python

40
voodoo
References

• [Link]

[Link]

[Link]

41

You might also like