0% found this document useful (0 votes)
3 views20 pages

UNIT 1 Python

This document provides an introduction to Python programming, highlighting its features, applications, and various programming concepts such as identifiers, keywords, statements, expressions, and data types. It covers Python's versatility in web development, data science, automation, and education, along with its syntax rules, variable scope, and built-in functions. Additionally, it discusses operator precedence, types of operators, and the importance of indentation in Python code.

Uploaded by

chandu34259
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)
3 views20 pages

UNIT 1 Python

This document provides an introduction to Python programming, highlighting its features, applications, and various programming concepts such as identifiers, keywords, statements, expressions, and data types. It covers Python's versatility in web development, data science, automation, and education, along with its syntax rules, variable scope, and built-in functions. Additionally, it discusses operator precedence, types of operators, and the importance of indentation in Python code.

Uploaded by

chandu34259
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

UNIT 1

Introduction to Python Programming

• Python is a general purpose, dynamic, high-level, and interpreted programming


[Link] supports Object Oriented programming approach to develop
applications. It is simple and easy to learn and provides lots of high-level data
structures.
• Python is easy to learn yet powerful and versatile scripting language, which makes it
attractive for Application Development.
• Python's syntax and dynamic typing with its interpreted nature make it an ideal
language for scripting and rapid application development.
• Python supports multiple programming patterns, including object-oriented,
imperative, and functional or procedural programming styles.
• Python is not intended to work in a particular area, such as web programming. That is
why it is known as multipurpose programming language because it can be used with
web, enterprise, 3D CAD, etc.

Python Features

[Link]: Python is very easy to learn and understand; any beginner can learn Python
easily. When writing code in Python, you need fewer lines of code compared to languages
like Java.
[Link]: It is interpreted( executed) line by line. This makes it easy to test and
debug.
[Link]-Oriented: The Python programming language supports classes and objects
and hence it is object-oriented.
[Link] and Open Source: The language and its source code are available to the public
for free; there is no need to buy a costly license.
[Link]: Since Python is open-source, you can run it on Windows, Mac, Linux or any
other platform. Your programs will work without any need to change it for every machine.
[Link] Programming: You can use it to develop a GUI (Graphical User Interface). One way
to do this is through Tkinter.

Applications of Python
• Web Development: Python is widely used for building dynamic web applications.
Frameworks like Django and Flask provide developers with powerful tools for rapid
development, scalability, and security.

Prof Kiran,Python Programming,KLE’S BCA Saundatti 1


UNIT 1

• Data Science and Machine Learning: Python has become the de facto language for
data science and machine learning due to its extensive libraries such as NumPy,
pandas, etc. These libraries facilitate data manipulation, analysis, visualization, and
implementation of machine learning algorithms.
• Automation and Scripting: Python's simplicity and readability make it ideal for
automating repetitive tasks and writing scripts. It is commonly used for tasks such as
system administration, file manipulation, and batch processing.
• Game Development: Python is increasingly being used in game development, both
for indie games and large-scale productions. Libraries like Pygame provide
developers with tools for building 2D games, while engines like Unity and Unreal
Engine offer support for scripting in Python
• Desktop GUI Applications: Python can be used to create desktop graphical user
interface (GUI) applications using libraries like Tkinter, PyQt, and wxPython. These
libraries allow developers to build cross-platform GUI applications with ease.
• Educational Purposes: Python's easy-to-understand syntax and extensive
documentation make it an excellent choice for teaching programming to beginners.
Many educational institutions use Python as an introductory language for computer
science courses.

Python Versions
Python has undergone several major releases since its inception. Some of the notable
versions:
❑ Python 1.x: The initial versions of Python, including 1.0 and 1.6, introduced
fundamental features of the language such as the core syntax and basic data
structures. These versions are no longer in active use.
❑ Python 2.x: Python 2 was a major release series that introduced significant
improvements and new features. The most widely used versions in this series were
Python 2.7, which became the stable version for many years. However, Python 2
reached its end-of-life on January 1, 2020, and is no longer maintained or supported.
❑ Python 3.x: Python 3 is the current and actively developed version of the language.
Notable versions in the Python 3 series include Python 3.0, Python 3.6, Python 3.7,
Python 3.8, Python 3.9, and Python 3.10 (the latest stable release as of my last
update). Python 3 is the recommended version for all new development.

Identifiers An identifier in Python is a name used for identifying a variable, class, function,
object, module.

Prof Kiran,Python Programming,KLE’S BCA Saundatti 2


UNIT 1

Rules for Naming an Identifier


▪ An identifier can be a composition of alphabets (a-z) and numbers (0-9). The
alphabets can be in uppercase or lowercase.
▪ An identifier can not start with Number.
▪ Identifiers cannot be a keyword and Identifiers are case-sensitive.
▪ Whitespaces are not allowed.
▪ We cannot use special symbols like !, @, #, $, and so on.
▪ Identifier name length is unrestricted

Keywords
Keywords in python are the reserved words.
These words cannot be used as a variable name, function name, or any other identifier name.
The following table lists some keywords of python.
False await else import pass

None break except in raise

True class finally is return

and continue for lambda try

as def from nonlocal while

assert del global not with

async elif if or yield

Statements

• Statement is a unit of code that perform specific task or complete instructions that
tell the Python interpreter to perform an action. They don't necessarily return a value.
• A program is made up of one or more statements
• Statements can be used for various tasks like:
• Assigning values to variables (x = 5) (Assignment statement )
• Printing output to the console (print("Hello, world!")) (Function or Method call)

Prof Kiran,Python Programming,KLE’S BCA Saundatti 3


UNIT 1

• Creating control flow using if, for, and while statements (conditional and looping
statements)
• Defining functions (def my_function():)
• Importing modules (import math)

Expressions
• Expressions are combinations of values, variables, operators, and function calls that
evaluate to a single result.
• This result can be a number, a string, a Boolean value, or even another data structure.
• Expressions are often used within statements, but they don't perform actions on their
own.

Examples of Expression

• Numeric and Arithmetic Expressions- Ex x + y, x % y


• Relational Expressions - relational operator (> , < , >= , <=)(Boolean expression)
• Constant Expressions- x = 15 + 1.3 print(x)
• Logical Expressions: include and, or, not
• String expressions “python” +”world”, “python”
• Function call expression: len(“hello”), [Link](25)

Variables in Python
• Variables are containers for storing a value or named location in memory
• Python is dynamically typed, it means that there is no requirement of pre-declaration
of a variable or its type.
• The type (and value) are initialized on the assignment. Assignments are performed
using an equal sign (=).
• A variable is created the moment you first assign a value to it.
• Variables do not need to be declared with any particular type and can even change
type after they have been set.
• Following example depicts how to declare variables in python:
• >>> count = 10 # count is assigned with value 10
• name = 'Ram' # string Ram assigned to name
• Z = TRUE # Z is assigned to Boolean value true
• String variables in Python can be declared either by using single or double quotes.

Prof Kiran,Python Programming,KLE’S BCA Saundatti 4


UNIT 1

Operators in Python
Operators in Python are symbols that perform operations on variables and values.
Python supports various types of operators, including
❖ Arithmetic Operators
❖ Comparison Operators
❖ Logical Operators
❖ Bitwise Operators
❖ Assignment Operators
❖ Identity Operators and Membership Operators

Arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication, etc. For example,

Python Comparison Operators


Comparison operators compare two values/variables and return a boolean result: True or
False. For example,

Python Logical Operators


Logical operators are used to check whether an expression is True or False. They are used in
decision-making

Prof Kiran,Python Programming,KLE’S BCA Saundatti 5


UNIT 1

Python Assignment Operators


Assignment operators are used to assign values to variables

Python Bitwise Operators


Bitwise operators act on operands as if they were strings of binary digits. They operate bit by
bit, hence the name.
For example, 2 is 10 in binary, and 7 is 111.
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
1. Bitwise AND: x & y This compares each bit of x and y. If both bits are 1, the result is 1;
otherwise 0.
2. Bitwise OR: x | y This compares each bit of x and y. If either bit is 1, the result is 1.
3. Bitwise XOR: x ^ y This compares each bit of x and y. If the bits are different, the result
is 1; if same, 0.
4. Bitwise NOT: ~x This flips all bits of x:
5. Left Shift: x << 1 This shifts all bits of x left by 1 place (adds a 0 on the right),
6. Right Shift: x >> 1 This shifts all bits of x right by 1 place, like dividing by 2:

Prof Kiran,Python Programming,KLE’S BCA Saundatti 6


UNIT 1

Precedence and Association


➢ Precedence and Association In Python, operator precedence determines the order in
which operators are evaluated in an expression.
➢ While operator association defines the direction in which operators of the same
precedence are evaluated
Precedence:
➢ Operator precedence determines the order in which operators are evaluated in an
expression.
➢ Operators with higher precedence are evaluated before operators with lower
precedence

Association
• Operator association determines the direction in which operators of the same
precedence are evaluated.
• It's relevant when operators of equal precedence are present in an expression.
• Most operators in Python have left-to-right association, meaning they are evaluated
from left to right. o However, exponentiation (**) has right-to-left association,
meaning it's evaluated from right to left.
• For example, 2 ** 3 ** 2 is evaluated as 2 ** (3 ** 2), resulting in 512.

Prof Kiran,Python Programming,KLE’S BCA Saundatti 7


UNIT 1

DataTypes
▪ In Python, data types represent the type or category of data that a variable or object
can hold.
▪ Python is a dynamically-typed language, meaning that variables do not have fixed
types. Instead, the type of a variable is determined at runtime based on the value
assigned to it. Some of the primary data types in Python are:

Python Numeric Data type


❑ In Python, numeric data type is used to hold numeric values.
❑ Integers, floating-point numbers and complex numbers fall under Python numbers
category. They are defined as int, float and complex classes in Python.
❑ int - holds signed integers of non-limited length. Ex a=10
❑ float - holds floating decimal points and it's accurate up to 15 decimal places.
Ex. y = 3.14.
❑ complex - holds complex numbers. Example: z = 3 + 2j.
❑ We can use the type() function to know which class a variable or a value belongs to.
❑ Ex: num1 = 5
❑ print(num1, 'is of type', type(num1))
❑ Output→5 is of type <class 'int'>
❑ Boolean Type: bool: Booleans represent the truth values True and False. Note – True
and False with capital ‘T’ and ‘F’ are valid Booleans otherwise python will throw an
error.
None Type: None: Represents the absence of a value or a null value. Example: x = None.

Prof Kiran,Python Programming,KLE’S BCA Saundatti 8


UNIT 1

Indentation in Python
• Indentation is a unique and essential aspect of Python's syntax.
• Unlike many other programming languages that use curly braces { } to define code
blocks, Python relies on indentation to structure your code.
• breakdown of how indentation works in Python:
• Indentation Levels: Python uses consistent whitespace (usually 4 spaces) to define
the nesting of code blocks.
• Indentation Scope: Statements with the same indentation level belong to the same
block of code and are executed together.
• New Block, New Indentation: To create a new block of code (like within an if
statement or loop), you must indent the statements further to the right.

• Consistent Indentation: It's crucial to maintain consistent indentation throughout


your code. Mixing spaces and tabs or using inconsistent indentation levels will
lead to errors.

Python Functions
A function is a block of code that performs a specific task.
Create a Function
Let's create our first function.

def greet():

print('Hello World!')

Python Built-in Functions

• Python has several functions that are readily available for use. These functions are
called built-in functions.
• These functions help to perform a wide variety of operations on strings, iterators, and
numbers. For instance, the built-in functions like sum(), min(), and max() are used to
simplify mathematical operations.
How to Use Built-in Function in Python?
• To use built-in functions in your code, simply call the specific function by passing the
required parameter (if any) inside the parentheses. Since these functions are pre-
defined, you don't need to import any module or package.

Prof Kiran,Python Programming,KLE’S BCA Saundatti 9


UNIT 1

Built-in Functions- Console Input and Console Output

▪ In Python, you can use built-in functions to perform console input and output
operations.
▪ These functions allow you to interact with the user through the console (also known
as standard input and standard output).

Console Input

• input(): The input() function is used to receive input from the user via the console.
• It displays a prompt to the user (if provided) and waits for the user to enter a value
followed by pressing the Enter key.
• The function returns the input value as a string.

#using input() to take user input # Taking input as string


num = input('Enter a number: ') color = input("What color is rose?: ")
print('You Entered:', num) print(color)
print('Data type of num:', # Taking input as int
type(num)) # Typecasting to int
o/p n = int(input("How many roses?: "))
Enter a number: 10 print(n)
You Entered: 10 # Taking input as float
Data type of num: <class 'str'> # Typecasting to float
price = float(input("Price of each rose?: "))
print(price)
Output
What color is rose?: red
red
How many roses?: 10
10
Price of each rose?: 15.50
15.5

Python Variable Scope


The scope of a variable in Python is defined as the specific area or region where the variable
is accessible to the user. The scope of a variable depends on where and how it is defined. In
Python, a variable can have either a global or a local scope.
There are two types of variables in Python

Prof Kiran,Python Programming,KLE’S BCA Saundatti 10


UNIT 1

Local variable
Global variable.

Local Variable
Local variables are the variables that declared inside the function and have scope within the
function. Example:
# Declaring a function
def add():
# Defining local variables. They has scope only within a function
a = 20
b = 30
c=a+b
print("The sum is:", c)
# Calling a function
add()
Output:
The sum is: 50

Global Variables
Global variables can be used throughout the program, and its scope is in the entire program.
We can use global variables inside or outside the function.
A variable declared outside the function is the global variable by default. Python provides the
global keyword to use global variable inside the function. If we don't use the global keyword,
the function treats it as a local variable.
Example:
# Declare a variable and initialize it
x = 101
# Global variable in function
def mainFunction():
# printing a global variable
global x
print(x)
# modifying a global variable
x = 'Welcome To MCA Sem’
print(x)
mainFunction()
print(x)

Prof Kiran,Python Programming,KLE’S BCA Saundatti 11


UNIT 1

Output:
101
Welcome To MCA Sem
Welcome To MCA Sem

Prof Kiran,Python Programming,KLE’S BCA Saundatti 12


UNIT 1

Python Conditional Execution


Python provides several control flow constructs to enable conditional execution, looping,
and branching
1. Conditional Statements:
Used to make decisions based on certain conditions.
❖ if statement
❖ else
❖ elif

IF Condition

In Python, an if condition is used to execute a block of code only if a certain condition is true.
Python uses indentation to identify a block. So the block under the Python if statements will
be identified as shown in the below example:
if condition:
statement1
statement2

Prof Kiran,Python Programming,KLE’S BCA Saundatti 13


UNIT 1

ELSE Statement
Provides an alternative block of code to execute if the condition in the if statement is False.

ELIF Statement
Allows you to check multiple conditions sequentially.

Looping Statements
Used to repeat a block of code multiple times
[Link] loop:
Iterates over a sequence of items (like a list or string) and executes a block of code for each
item.
For Loop Syntax:
for iterator_var in sequence:
statements(s)

Prof Kiran,Python Programming,KLE’S BCA Saundatti 14


UNIT 1

languages = ['Swift', 'Python', 'Go']


# access elements of the list one by one
for i in languages:
print(i)
Output
Swift
Python
Go
Example: Loop Through a String
language = 'Python'
# iterate over each character in language
for x in language:
print(x)
Output
P
y
t
h
o
n

for Loop with Python range()


In Python, the range() function returns a sequence of numbers. For example,
values = range(4)
Here, range(4) returns a sequence of 0, 1, 2 ,and 3.
Since the range() function returns a sequence of numbers, we can iterate over it using a for
loop. For example,
# iterate from i = 0 to i = 3
for i in range(4):
print(i) o/p 1,2,3

ii while loop:. Continues executing a block of code as long as a specified condition


remains True.
while Loop Syntax
while condition:

Prof Kiran,Python Programming,KLE’S BCA Saundatti 15


UNIT 1

# body of while loop


For example,
number = 1
while number <= 3:
print(number)
number = number + 1

Break And Continue Statements


Used within loops to prematurely exit the loop when a certain condition is met
for i in range(10):
if i == 5:
break
print(i)

o/p 1,2,3,4

Continue Statement

The continue statement skips the current iteration of the loop and the control flow of the
program goes to the next iteration.

for item in iterable:


if condition:
continue
# code after continue (this will be skipped if continue runs)

for i in range(1, 6):


if i % 2 == 0:
continue O/P 1,3,5
print(i)

words = ["apple", "banana", "skip", "cherry"]


for word in words:
if word == "skip":
continue
print("Processing:", word) o/p apple,banana,cherry

Prof Kiran,Python Programming,KLE’S BCA Saundatti 16


UNIT 1

Python Libraries
Python libraries are collections of pre-written code modules that provide functionalities
for various tasks.
They extend the capabilities of the Python language and allow you to perform complex
operations without writing everything from scratch.
The Python Standard Library contains the exact syntax, semantics, and tokens of Python.
It contains built-in modules that provide access to basic system functionality like I/O and
some other core modules.
Importing Libraries
1. Importing the Entire Library:
Use the import statement followed by the library name to import all functionalities from
the library.
Example:

2. Importing Specific Functions or Classes:


You can import specific functions or classes from a library using the from ... import syntax.
Example:

3. Giving Aliases to Libraries: For long library names, you can assign shorter aliases using the
as keyword. Example

Other than this, there are several other libraries in Python that make a programmer’s life
easier. Let’s have a look at some of the commonly used libraries:
TensorFlow: It is also used in machine learning and deep learning algorithms
Matplotlib: responsible for plotting numerical data. used in data analysis.
Pandas: an important library for data scientists

Prof Kiran,Python Programming,KLE’S BCA Saundatti 17


UNIT 1

SciPy: for high-level scientific computations


Numpy:It consists of in-built mathematical functions for easy computations
PyGame:used for developing video games
PyBrain:(Python Based Reinforcement Learning, Artificial Intelligence, and Neural Networks
library):

Range () And Exit () Functions In Python


1. range() Function:
The range() function generates a sequence of numbers within a specified range.
It is commonly used with loops to iterate over a sequence of numbers.
The range() function can take one, two, or three arguments: range(stop), range(start, stop),
or range(start, stop, step).
By default, range() starts from 0 and increments by 1.
Syntax
range()
range(start, stop, step)
Example:
range(5) # 0, 1, 2, 3, 4
range(2, 6) # 2, 3, 4, 5
range(1, 10, 2) # 1, 3, 5, 7, 9
range(10, 0, -2) # 10, 8, 6, 4, 2

Exit() Function
The exit() function is used to terminate the execution of the Python interpreter.
It can be used to exit the current script or Python session immediately.
It is part of the sys module and can also be accessed as [Link]().
for i in range(5):
if i == 3:
exit() # or use quit() or [Link]()
print(i)

Python Modules
As our program grows bigger, it may contain many lines of code. Instead of putting everything
in a single file, we can use modules to separate codes in separate files as per their
functionality. This makes our code organized and easier to maintain.
Module is a file that contains code to perform a specific task. A module may contain
variabes, functions, classes etc. Let's see an example.

Prof Kiran,Python Programming,KLE’S BCA Saundatti 18


UNIT 1

Let us create a module. Type the following and save it as [Link].


# Python Module addition
def add(a, b):
result = a + b
print(result)

Import modules in Python


We can import the definitions inside a module to another module or the interactive
interpreter in Python.
We use the import keyword to do this. To import our previously defined module example, we
type the following in the Python prompt.
import example
This does not import the names of the functions defined in example directly in the current
symbol table. It only imports the module name example there.

Using the module name we can access the function using the dot . operator. For example:
[Link](4,5) # returns 9
import Python Standard Library Modules
The Python standard library contains well over 200 modules. We can import a module
according to our needs.
Suppose we want to get the value of pi, first we import the math module and use [Link].
For example,
# import standard math module
import math
# use [Link] to get value of pi
print("The value of pi is", [Link])

Python import with Renaming


In Python, we can also import a module by renaming it. For example,
# import module by renaming it
import math as m
print([Link])
# Output: 3.141592653589793
Here, We have renamed the math module as m. This can save us typing time in some cases.
Note that the name math is not recognized in our scope. Hence, [Link] is invalid, and [Link]
is the correct implementation.

Prof Kiran,Python Programming,KLE’S BCA Saundatti 19


UNIT 1

Import all names


In Python, we can import all names(definitions) from a module using the following construct:
# import all names from the standard module math
from math import *
print("The value of pi is", pi)

Python from...import statement (specific classes from module)


We can import specific names from a module without importing the module as a
whole. For example,
# import only pi from math module
from math import pi
print(pi)
# Output: 3.141592653589793

*****

Prof Kiran,Python Programming,KLE’S BCA Saundatti 20

You might also like