0% found this document useful (0 votes)
13 views34 pages

Module 1

Python is a high-level, interpreted, and object-oriented programming language created by Guido van Rossum in 1989. It is known for its readability, ease of learning, and versatility in applications ranging from web development to scientific computing. The document outlines Python's features, history, applications, and basic programming concepts, including data types and debugging.

Uploaded by

ashvini297
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views34 pages

Module 1

Python is a high-level, interpreted, and object-oriented programming language created by Guido van Rossum in 1989. It is known for its readability, ease of learning, and versatility in applications ranging from web development to scientific computing. The document outlines Python's features, history, applications, and basic programming concepts, including data types and debugging.

Uploaded by

ashvini297
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Programming [1BPLC105B] Module 1

Introduction to Python
 Python is a general-purpose high-level programming language, interpreted, interactive
and object- oriented scripting language.
 The Python programming language has a wide range of syntactical constructions,
standard library functions, and interactive development environment features.
 It was developed by Guido van Rossum during 1989 at the National Research
Institute for Mathematics and Computer Science in the Netherlands.
 Python source code is also available under the GNU General Public License (GPL).
 Python is designed to be highly readable. It uses English keywords frequently where
as other languages use punctuation, and it has fewer syntactical constructions than
other languages.

Why to learn Python?


 Python is Interpreted − Python is processed at runtime by the interpreter. You do not
need to compile your program before executing it. This is similar to PERL and PHP.
 Python is Interactive − You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
 Python is Object-Oriented − Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
 Python is a Beginner's Language − Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from
simple text processing to WWW browsers to games.

Why the name Python?


 When Van Rossaum began implementing Python, he was also reading the published
scripts from “Monty Python’s Flying Circus”, a BBC comedy series from the 1970s.
 Van Rossum thought he needed a name that was short, unique, and slightly
mysterious, so he decided to call the language Python.

Features/Applications of Python
 Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.
 Easy-to-read − Python code is more clearly defined and visible to the eyes.
 Easy-to-maintain − Python's source code is fairly easy-to-maintain.

Dept. of CSE (Data Science) 1


Python Programming [1BPLC105B] Module 1

 A broad standard library − Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.
 Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
 Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
 Extendable − we can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
 Databases − Python provides interfaces to all major commercial databases.
 GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows MFC,
Macintosh, and the X Window system of Unix.
 Scalable − Python provides a better structure and support for large programs than
shell scripting.

Other Features include

 It supports functional and structured programming methods as well as OOP.


 It can be used as a scripting language or can be compiled to byte-code for building
large applications.
 It provides very high-level dynamic data types and supports dynamic type checking.
 It supports automatic garbage collection.
 It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

Characteristics of Python
 It supports functional and structured programming methods as well as OOP.
 It can be used as a scripting language or can be compiled to byte-code for building
large applications.
 It provides very high-level dynamic data types and supports dynamic type checking.
 It supports automatic garbage collection.
 It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

History of Python
 Python laid its foundation in the late 1980s.
 The implementation of Python was started in the December 1989 by Guido Van
Rossum at the National Research Institute for Mathematics and Computer Science in

Dept. of CSE (Data Science) 2


Python Programming [1BPLC105B] Module 1

the Netherlands . This release included exception handling, functions, and the core
data types of list, dict, str and others. It was also object oriented and had a module
system.
 In February 1991, van Rossum published the code (labeled version 0.9.0) to
[Link].
 In 1994, Python 1.0 was released with new features like: lambda, map, filter, and
reduce.
 Six and a half years later in October 2000, Python 2.0 was introduced. This release
included list comprehensions, a full garbage collector and it was supporting unicode.
 On December 3, 2008, Python 3.0 (also known as "Python 3000" and "Py3K") was
released. It was designed to rectify fundamental flaw of the language. Python 3 is not
backwards compatible with Python 2.x.
 ABC programming language is said to be the predecessor of Python language which
was capable of Exception Handling and interfacing with Amoeba Operating System.
 Python is influenced by following programming languages:
-ABC language.
-Modula-3
 Python is copyrighted. Like Perl, Python source code is now available under the GNU
General Public License (GPL).
 Python is now maintained by a core development team at the institute, although Guido
van Rossum still holds a vital role in directing its progress.

Applications of Python

 Web Applications: Python can be used to develop web applications. It provides


libraries to handle internet protocols such as HTML and XML, JSON, Email
processing, request, beautifulSoup, Feedparser etc. It also provides Frameworks such
as Django, Pyramid, Flask etc to design and delelop web based applications. Some
important developments are: PythonWikiEngines, Pocoo, PythonBlogSoftware etc.
 Desktop GUI Applications: Python provides Tk GUI library to develop user
interface in python based application. Some other useful toolkits wxWidgets, Kivy,
pyqt that are useable on several platforms. The Kivy is popular for writing multitouch
applications.

Dept. of CSE (Data Science) 3


Python Programming [1BPLC105B] Module 1

 Software Development: Python is helpful for software development process. It


works as a support language and can be used for build control and management,
testing etc.
 Scientific and Numeric: Python is popular and wiely used in scientific and numeric
computing. Some useful library and package are SciPy, Pandas, IPython etc. SciPy is
group of packages of engineering, science and mathematics.
 Business Applications: Python is used to build Business applications like ERP and e-
commerce systems. Tryton is a high level application platform.
 Console Based Application: Python is used to develop console based applications.
For example: IPython.
 Audio or Video based Applications: Python is awesome to perform multiple tasks
and can be used to develop multimedia applications. Some of real applications are:
TimPlayer, cplay etc.
 3D CAD Applications: To create CAD application Fandango is a real application
which provides full features of CAD.
 Enterprise Applications: Python can be used to create applications which can be
used within an Enterprise or an Organization. Some real time applications are:
OpenErp, Tryton, Picalo etc.
 Applications for Images: Using Python several applications can be developed for
image. Applications developed are: VPython, Gogh, imgSeek etc

The Python Programming Language

Python is an example of a high-level language; other high-level languages are C++, PHP,
Pascal, C#, and Java.

Low-level languages, sometimes referred to as machine languages or assembly languages.,


Computers can only execute programs written in low- level languages. Thus, programs
written in a high-level language have to be translated into something more suitable before
they can run. All programs are written in high-level languages because of their advantages:
programs take less time to write, they are shorter and easier to read, and they are more likely
to be correct. High-level languages are portable, meaning that they can run on different kinds
of computers with few or no modifications.

The engine that translates and runs Python is called the Python Interpreter: There are two
ways to use it: immediate mode and script mode. In immediate mode, we type Python

Dept. of CSE (Data Science) 4


Python Programming [1BPLC105B] Module 1

expressions into the Python Interpreter window, and the interpreter immediately shows the
result:

 Interactive shell in python can be launched using Python IDLE, which will be
installed with Python
 On Windows, open the Start menu, select All Programs à Python 3.3, and then select
IDLE (Python GUI). A window with the >>> prompt should appear; that’s the
interactive shell.
 On OS X, select Applications ▸ MacPython 3.3 à IDLE. On Ubuntu, open a new
Terminal window and enter idle3.
 To find sum of 2 numbers example, enter 2 + 2 at the prompt to have Python do some
simple math.
>>> 2 + 2 à will give 4 as an answer
 In Python, 2 + 2 is called an expression, which is the most basic kind of
programming instruction in the language.
 Expressions consist of values (such as 2) and operators (such as +), and they can
always evaluate (that is, reduce) down to a single value. That means you can use
expressions anywhere in Python code that you could also use a value.
 In the previous example, 2 + 2 is evaluated down to a single value, 4. A single value
with no operators is also considered an expression, though it evaluates only to itself,
as shown here
>>> 2 results in 2
Alternatively, we can write a program in a file and use the interpreter to execute the contents
of the file. Such a file is called a script. Scripts have the advantage that they can be saved to
disk, printed, and so on.
Working directly in the interpreter is convenient for testing short bits of code because
we get immediate feedback. When we are writing a script we need a text editor. A few
examples of text editors are Notepad, Notepad++, vim, emacs and sublime.

Dept. of CSE (Data Science) 5


Python Programming [1BPLC105B] Module 1

What is a Program?

A program is a sequence of instructions that specifies how to perform a computation.

Basic instructions in every programming language are:


input Get data from the keyboard, a file, or some other device such as a sensor.
output Display data on the screen or send data to a file or other device such as a motor.
math Perform basic mathematical operations like addition and multiplication.
conditional execution Check for certain conditions and execute the appropriate sequence of
statements.
repetition Perform some action repeatedly, usually with some variation.
What is Debugging?
Programming errors are called bugs and the process of tracking them down and correcting
them is called debugging. Three kinds of errors can occur in a program: syntax errors,
runtime errors, and semantic errors.
Syntax Errors
Python can only execute a program if the program is syntactically correct; otherwise, the
process fails and returns an error message. Syntax refers to the structure of a program and the
rules about that structure.
A syntax error occurs when the structure of the code violates the rules of the
programming language. Python’s interpreter reads program line by line, and if it finds a
statement it cannot understand, it will stop and display a message describing the error.
Examples include forgetting a colon at the end of an if statement or not matching parentheses
properly. These errors prevent the program from even starting.
Runtime Errors
Runtime errors occur after the program has successfully started running but then
encounters an illegal operation. For example, dividing a number by zero or trying to use a
variable that hasn’t been defined. Python stops executing the program when it encounters
such an error and usually displays an error message called an exception. Runtime errors are
often caused by unexpected input or situations that were not handled properly in the code.

Semantic Errors

A semantic error occurs when your program runs without crashing but produces the
wrong result. The syntax is correct, and Python can execute it, but the meaning of the code —
its semantics — doesn’t match what you intended. These are the hardest errors to find
Dept. of CSE (Data Science) 6
Python Programming [1BPLC105B] Module 1

because the program appears to work. For example, if you mistakenly write a formula that
calculates the area of a triangle incorrectly, Python will not complain, but the answer will be
wrong.

Experimental Debugging

Debugging is not just fixing mistakes — it is a systematic way of thinking and


experimenting. When you encounter an error, you should form a hypothesis about what
might be wrong, make a small change to test that hypothesis, and observe the result. This
experimental method is very similar to the scientific method.

Formal and Natural Languages


Natural languages are the languages that people speak, such as English, Spanish, and
French. They were not designed by people, they evolved naturally.
Formal languages are languages that are designed by people for specific applications.
Programming languages are formal languages that have been designed to express
computations.
The First Program
The classic first program in many languages: display Hello, World!. In Python:
print("Hello, World!")
The print function displays its argument. The quotes (“ “) delimit the string literal; they don’t
appear in the output.
Comments
A comment in a computer program is text that is intended only for the human reader
— it is completely ignored by the interpreter. In Python, the # token starts a comment. The
rest of the line is ignored.
Values and Datatypes
A value is one of the fundamental things — like a letter or a number — that a
program manipulates. In Python, data is represented as values. Every value belongs to a type
— a category that determines what kind of data it is and what operations can be performed on
it.
What is a Value?
A value is a basic unit of data that a program manipulates. Examples of values in
Python:
1 # integer
Dept. of CSE (Data Science) 7
Python Programming [1BPLC105B] Module 1

3.14 # floating-point number "Hello" # string


True # boolean
Each of these is a value, and each has a particular type.
Types of Values
1. Integers (int)
o Whole numbers without a decimal point.
o Examples: -3, 0, 25, 1000
o Can be used for counting, indexing, and arithmetic operations.
2. Floating-Point Numbers (float)
o Numbers that contain a decimal point.
o Examples: 3.14, -2.5, 0.0, 1.0
o Represent real numbers (approximation using binary fractions).
o Operations like division usually return a float.
3. Strings (str)
o Sequence of characters enclosed in quotes (single ' ' or double " ").
o Examples: 'hello', "Python", "123"
o Strings represent text data, even if it contains digits.
4. Booleans (bool)
o Represent truth values: True or False.
o Used in logical expressions and conditions.
A data type is a classification that specifies which type of a value a variable has. A data type
is a category for values, and every value belongs to exactly one data type.

Common Data types


The values -2 and 30, are said to be integer values. The integer (or int) data type indicates
values that are whole numbers. Numbers with a decimal point, such as 3.14, are called
floating-point numbers (or floats). Note that even though the value 42 is an integer, the value
42.0 would be a floating-point number. "Hello, World!" is a string.

Dept. of CSE (Data Science) 8


Python Programming [1BPLC105B] Module 1

If we are not sure what class a value falls into, Python has a function called type which can
tell us. Python provides a built-in function type() to check the data type of any value.
>>> type("Hello, World!")
<class 'str'>
>>> type(17)
<class 'int'>
>>> type(3.2)
<class 'float'>
strings belong to the class str and integers belong to the class int. numbers with a decimal
point belong to a class called float, because these numbers are represented in a format called
floating-point.
>>> type("17")
<class 'str'>
>>> type("3.2")
<class 'str'>
Strings are textual, while numbers are quantitative."123" (a string) is not the same as 123
(an integer). We can’t perform arithmetic on a string unless you first convert it into a number
using int() or float().
Strings in Python can be enclosed in either single quotes (') or double quotes ("), or three of
each (' ' ' or """).
>>> type('This is a string.')
<class 'str'>
>>> type("And so is this.")
<class 'str'>
>>> type("""and this.""")
<class 'str'>
>>> type('''and even this...''')
<class 'str'>
>>> print('''"Oh no", she exclaimed, "Ben's bike is broken!"''')
"Oh no", she exclaimed, "Ben's bike is broken!"
Triple quoted strings can even span multiple lines:
>>> message = """This message will
... span several
... lines."""
>>> print(message) This message will span several lines.
>>>
When we type a large integer, we might to use commas between groups of three
digits, as in 42,000. The same goes for entering Dutch-style floating point numbers using a
comma instead of a decimal dot. This is not a legal integer in Python, but it does mean
something else, which is legal: Because of the comma, Python chose to treat this as a pair of
values.

Dept. of CSE (Data Science) 9


Python Programming [1BPLC105B] Module 1

>>> 42000
42000
>>> 42,000
(42, 0)

Variables
A variable is a name that refers to a value. A variable is the name of computer’s memory
location where single value can be stored. Values are stored in a variable using Assignment
Statement. A good variable name describes the data it contains.
Assignment statement consists of name of the variable, assignment operator (=) and a
value.
>>> a = 7.7
>>> a #outputs 7.7
>>> b = 3.3
>>> a+b #outputs 11.0
A variable is initialized (or created) the first time a value is stored in it (spam = 'Hello'). After
that, variable can be used in expressions with other variables and values (s=spam). When a
variable is assigned a new value, the old value is forgotten. (spam = 'Goodbye‘).
Rules for Variable names
 Variable names are case sensitive.
 It has to be only one word
 It should contain only letters, numbers, under score character.
 It can’t begin with a number.
 Valid Variables:
o balance, curBal, acc4
 Invalid Variables
o cur-bal (hyphan not allowed)
o cur bal (spaces are not allowed)
o 4acc (Can’t begin with a number)
o tot_$um ( Special characters are not allowed)

Dept. of CSE (Data Science) 10


Python Programming [1BPLC105B] Module 1

Variable names and keywords

Keywords define the language’s syntax rules and structure, and they cannot be used as
variable names. Python has thirty-something keywords.

and as assert break class continue

def del elif else except exec

finally for from global if import

in is lambda nonlocal not or

pass raise return try while with

yield True False None

Statements
A statement is an instruction that the Python interpreter can execute. Each line of code in
Python is usually a statement.
Example:
x=5
print(x)

The first line (x = 5) is an assignment statement. The second line (print(x)) is a print
statement that produces output. Python executes statements one after another, in sequential
order (top to bottom), unless told otherwise by loops or conditionals.

Dept. of CSE (Data Science) 11


Python Programming [1BPLC105B] Module 1

Evaluating Expressions
An expression is a combination of values, variables, operators, and calls to functions. If you
type an expression at the Python prompt, the interpreter evaluates it and displays the result:
>>> 1 + 1
2
>>> len("hello")
5
In this example, len is a built-in Python function that returns the number of characters in a
string. The evaluation of an expression produces a value, which is why expressions can
appear on the right-hand side of assignment statements. A value all by itself is a simple
expression, and so is a variable.
>>> 17
17
>>> y = 3.14
>>> x = len("hello")
>>> x
5
>>> y
3.14

Operators and Operands


Operators are special tokens that represent computations like addition, multiplication
and division. The values the operator uses are called operands.
The following are all legal Python expressions whose meaning is more or less clear:
20+32 hour*60+minute minute/60 5**2 (5+9)*(15-7)
The tokens +, -, and *, and the use of parenthesis for grouping, mean in Python what they
mean in mathematics. The asterisk (*) is the token for multiplication, and ** is the token for
exponentiation.
>>> 2**3
8
>>>3**2
9
When a variable name appears in the place of an operand, it is replaced with its value before
the operation is performed.
>>> minutes = 645
>>> hours = minutes / 60
>>> hours
10.75
Dept. of CSE (Data Science) 12
Python Programming [1BPLC105B] Module 1

Floor division operator: //


Its result is always a whole number — and if it has to adjust the number it always moves it to
the left on the number line.
>>> 7 / 4
1.75
>>> 7 // 4
1
>>> minutes = 645
>>> hours = minutes // 60
>>> hours
10

Type Converter Functions


int, float and str functions convert their arguments into types int, float and str respectively. We
call these- type converter functions
The int function can take a floating point number or a string, and turn it into an int. For
floating point numbers, it discards the decimal portion of the number — a process we call
truncation towards zero on the number line.
>>> int(3.14) 3
>>> int(3.9999) 3
>>> int(3.0) 3
>>> int(-3.999)
-3
>>> int(minutes / 60) 10
>>> int("2345") 2345
>>> int(17) 17
>>> int("23 bottles")
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '23 bottles'

The type converter float can turn an integer, a float, or a syntactically legal string into a float:
>>> float(17)
17.0
>>> float("123.45")
123.45

The type converter str turns its argument into a string:


>>> str(17)
'17'
>>> str(123.45)
'123.45'

Order of Operations
Dept. of CSE (Data Science) 13
Python Programming [1BPLC105B] Module 1

When more than one operator appears in an expression, the order of evaluation depends on
the rules of precedence. Python follows the same precedence rules for its mathematical
operators that mathematics does. The acronym PEM- DAS is a useful way to remember the
order of operations:
Parentheses have the highest precedence and can be used to force an expression to
evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1)
is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read,
as in (minute * 100) / 60, even though it doesn’t change the result.
Exponentiation has the next highest precedence, so 2**1+1 is 3 and not 4, and
3*1**3 is 3 and not 27.
Multiplication and both Division operators have the same precedence, which is higher
than Addition and Subtraction, which also have the same precedence. So 2*3-1 yields 5
rather than 4, and 5-2*2 is 1, not 6.
Operators with the same precedence are evaluated from left-to-right. In algebra we
say they are left-associative. So in the expression 6-3+2, the subtraction happens first,
yielding 3. We then add 2 to get the result 5. If the operations had been evaluated from right
to left, the result would have been 6-(3+2), which is 1.

Operator Operation Example Evaluates to ..

** Exponent 2 ** 3 8

% Modulus / Remainder 2%8 6

// Integer Division / Floor Quotient 22 // 8 2

/ Division 22 // 8 2.75

* Multiplication 3*5 15

- Subtraction 5–2 3

+ Addition 2+2 4

Evaluate
>>> 2 + 5 * 6 #32
>>> 29 // 6 #4
>>> (6 -1) * ((7+2)/(3-1)) #22.5

Evaluating expression

Dept. of CSE (Data Science) 14


Python Programming [1BPLC105B] Module 1

>>> 2 ** 3 ** 2 # The right-most ** operator gets done first!


512
>>> (2 ** 3) ** 2 # Use parentheses to force the order you want!
64

Operations on strings:
String Concatenation (+)
>>> ‘Hello! #Syntax error : EOL while scanning string literal (closing Single
#quote is missing)

When + operator is used between strings it will act as Concatenation Operator


Ex : >>> ‘Alice’ + ‘Bob’ #‘AliceBob’

If + operator is used between string and integer, an error message will be displayed
>>>’Alice’ + 5 #TypeError : Can’t convert ‘int’ object to str implicitly

Replication Operator (*)


When * operator is used between string value and an integer value it becomes String
replication operator.
>>> ‘Alice’ * 3 #AliceAliceAlice’
Operator can be used between 2 numbers or between a string and integer otherwise error will
be displayed
>>>’Alice’ * ‘Bob’ #TypeError : Can’t multiply sequence of non-int of #type ‘str’
>>>’Alice’ * 5.0 #TypeError : Can’t multiply sequence by non-int of #type ‘float’

Input
There is a built-in function in Python for getting input from the user:
name = input("Please enter your name: ")
The user of the program can enter the name and click OK, and when this happens the text that
has been entered is returned from the input function, and in this case assigned to the variable
name.
Even if you asked the user to enter their age, you would get back a string like "17". It would
be your job, as the programmer, to convert that string into a int or a float, using the int or float
converter functions.
Program to calculate area of a circle.
response = input("What is your radius? ")
r = float(response)
area = 3.14159 * r**2
print("The area is ", area)

The modulus operator

The modulus operator works on integers (and integer expressions) and gives the
remainder when the first number is divided by the second. In Python, the modulus operator is

Dept. of CSE (Data Science) 15


Python Programming [1BPLC105B] Module 1

a percent sign (%). The syntax is the same as for other operators. It has the same precedence
as the multiplication operator. So 7 divided by 3 is 2 with a remainder of 1.
>>> q = 7 // 3
>>> print(q)
2
>>> r = 7 % 3
>>> print(r)
1

let’s write a program to ask the user to enter some seconds, and we’ll convert them into
hours, minutes, and remaining seconds.
total_secs = int(input("How many seconds, in total?"))
hours = total_secs // 3600
secs_still_remaining = total_secs % 3600
minutes = secs_still_remaining // 60
secs_finally_remaining = secs_still_remaining % 60

print("Hrs=", hours, " mins=", minutes, "secs=", secs_finally_remaining)

Flow Control
Flow control statements can decide which Python instructions to execute under which
conditions. Flow control statements directly correspond to the symbols in a flowchart

Boolean Values
Boolean data type has only 2 values: True and False. (True and False are keywords).
(Boolean is capitalized because the data type is named after mathematician George Boole.)
>>> spam = True
>>> spam #True
>>> true #NameError: name 'true' is not defined
>>> True #True
>>> True+2 #3
>>> True=2+2 #SyntaxError: can't assign to keyword

Dept. of CSE (Data Science) 16


Python Programming [1BPLC105B] Module 1

Boolean values are used in expressions and can be stored in variables. If you don’t use the
proper case or you try to use True and False for variable names, Python will give you an error
message.

Comparison Operators
Comparison operators compare two values and evaluate down to a single Boolean value.

Operator Meaning

== Equal to

!= Not Equal to

< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to

Operators evaluate to True or False depending on the values you give them.
>>> 42 == 42 #True
>>> 42 == 99 #False
>>> 2 != 3 #True
>>> 2 != 2 #False

== (equal to) evaluates to True when the values on both sides are the same, and != (not equal
to) evaluates to True when the two values are different.
>>> 'hello' == 'hello‘ #True
>>> 'hello' == 'Hello‘ #False
>>> 'dog' != 'cat‘ #True
>>> True == True #True
>>> True != False #True
>>> 42 == 42.0 #True
>>> 42 == '42‘ #False

The <, >, <=, and >= operators, on the other hand, work properly only with integer and
floating- point values.
>>> 42 < 100 #True
>>> 42 > 100 #False
>>> 42 < 42 #False
>>> eggCount = 42
>>> eggCount <= 42 #True
>>> myAge = 29
>>> myAge >= 10 #True
Dept. of CSE (Data Science) 17
Python Programming [1BPLC105B] Module 1

Boolean Operators

== vs =
 The == operator (equal to / Comparison) asks whether two values are the same as
each other.
 The = operator (assignment) puts the value on the right into the variable on the left.
 The three Boolean operators (and, or, and not) are used to compare Boolean values.
 Boolean operators evaluate the expressions down to a Boolean value.

Binary Boolean Operators (and)


 The and and or operators takes two Boolean values (or expressions), so
they’re considered as binary operators.
 The order of preference among Boolean operators are not, and, or
 The and operator evaluates an expression to True if both Boolean values are
True; otherwise, it evaluates to False.
>>> True and True #True
>>> True and False #False
 The and Operator’s Truth Table
Expression Evaluates to ….

True and True True

True and False False

False and True False

False and False False

Binary Boolean Operators (or)


The or operator evaluates an expression to True if either of the two Boolean values is True.
If both are False, it evaluates to False.
>>> True or True #True
>>> False or False #False
>>> True or False #True
The or Operator’s Truth Table

Expression Evaluates to ….

Dept. of CSE (Data Science) 18


Python Programming [1BPLC105B] Module 1

True or True True

True or False True

False or True True

False or False False

Binary Boolean Operators (not)


 The not operator operates on only one Boolean value (or expression).
 The not operator simply evaluates to the opposite Boolean value.
>>> not True #False
>>> not not not not True #True

Expression Evaluates to ….

not True False

not False True

Mixing Boolean and Comparison Operators


Boolean expressions that use comparison operators into the interactive shell
>>> (4 < 5) and (5 < 6) #True
>>> (4 < 5) and (9 < 6) #False
>>> (1 == 2) or (2 == 2) #True
>>> 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2 #True
The Boolean operators have an order of operations just like the math operators do.
After any math and comparison operators evaluate, Python evaluates the not operators first,
then the and operators, and then the or operators.

Dept. of CSE (Data Science) 19


Python Programming [1BPLC105B] Module 1

Elements of Flow Control


Flow control statements often start with a part called the condition, and all are followed by a
block of code called the clause.
Conditions
Condition is a flow control statement which always evaluates to True or False. Condition is
just a more specific name in the context of flow control statements.
A flow control statement decides what to do based on whether its condition is True or False,
and almost every flow control statement uses a condition.
Blocks of Code
Lines of Python code can be grouped together in blocks.
Indentation of lines is used to identify beginning of block and end of block
There are three rules for blocks.
 Blocks begin when the indentation increases.
 Blocks can contain other blocks.
 Blocks ends when the indentation decreases to zero or to a containing block’s
 indentation.
 Blocks are easier to understand by looking at some indented code
if name == 'Ravi':
print('Hello Ravi')
if password == 'Ra@123':
print('Access granted.')
else:
print('Wrong password.')

if Statement
An if statement’s clause (the block following the if statement) will execute if the statement’s
condition is True. The clause is skipped if the condition is False. An if statement could be
read as, “If this condition is true, execute the code in the clause.”
In Python, an if statement consists of the following:
o The if keyword
o A condition (that is, an expression that evaluates to True or False)
o A colon
o Starting on the next line, an indented block of code (called the if clause)
Syntax
if <condition>:
statements
Ex:-
if name == ‘Alice’:
print(‘Hi Alice’)

Dept. of CSE (Data Science) 20


Python Programming [1BPLC105B] Module 1

if-else Statements
An if clause can optionally be followed by an else Statement. The else clause is executed only
when the if statements condition is False. An else statement could be read as, “If this
condition is true, execute this code. Or else, execute that code.”
An else statement doesn’t have a condition, and in code, an else statement always
consists of the following:
o The else keyword
o A colon
o Starting on the next line, an indented block of code (called the else clause)

Syntax:
if <condition>:
statements
else:
statements

Example:
if name == ‘Alice’:
print(‘Hi Alice’)
else:
print(‘Hello Stranger’)

Flow chart

elif Statements
The elif statement is an “else if” statement that always follows an if or another elif statement.

Dept. of CSE (Data Science) 21


Python Programming [1BPLC105B] Module 1

It provides another condition that is checked only if any of the previous conditions were
False.
In code, an elif statement always consists of the following:
o The elif keyword
o A condition (that is, an expression that evaluates to True or False)
o A colon
o Starting on the next line, an indented block of code (called the elif clause)
Example 1:
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')

Example 2:
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
elif age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif age > 100:

Dept. of CSE (Data Science) 22


Python Programming [1BPLC105B] Module 1

print('You are not Alice, grannie.')

The for Loop


Purpose & Motivation
Before the for loop, to repeat actions (say, "move, turn, move, turn") one had to write each
step explicitly. If you wanted to draw a polygon with many sides, that becomes tedious and
error prone. The for loop provides a convenient mechanism to iterate — repeat a block of
code multiple times
Syntax & Components
• Loop variable: a variable name (e.g. name, f, etc.) that takes successive values from a
sequence (list, range, etc.).
• Sequence / iterable: an expression that produces multiple values (e.g. a list ["Joe",
"Amy", ...]) over which the loop variable will iterate
• Loop body: the indented statements under the for header. These are executed once per
iteration.
Syntax:
for variable in iterable:
# code to be executed for each item in the iterable
# (indented block)
Example:
for name in ["Joe", "Amy", "Brad"]:
print("Hi", name, "please come to my party!")
Here:
• name is the loop variable
• ["Joe", "Amy", "Brad"] is the list (sequence)
• print(…) is in the loop body On each iteration:
Python checks if there is another item in the sequence. If yes, it assigns that item to the loop
variable. Executes the loop body. When the list is exhausted, the loop terminates, and
execution continues with statements following the loop.
Termination & Control Flow

Dept. of CSE (Data Science) 23


Python Programming [1BPLC105B] Module 1

The terminating condition is that there are no more elements in the sequence to assign
to the loop variable. The loop changes the usual “top-to-bottom, one statement at a time” flow
(control flow) by jumping back to the loop header after each iteration until termination.
Conceptually, Python keeps a “pointer” to which statement is coming up next (control
flow), and the loop redirects that flow repeatedly within its body until exhaustion of items.

Advantages & Use Cases


• Avoids code duplication when repeating actions.
• Makes code easier to change for different numbers of iterations (you just change the
list or range).
• Can iterate over different data types (lists, tuples, ranges, strings, etc.) when you
extend your knowledge.
• Useful for drawing repeated patterns (especially in turtle graphics), processing lists of
data, etc.

The while Statement


Purpose
A while loop is used when you don’t know in advance how many times to repeat an action.
It repeats while a condition is true.
Syntax
while condition:
body_statement(s)

Execution Flow
1. Evaluate the condition.
2. If True, execute the loop body.
3. Re-evaluate the condition.
4. Repeat until the condition becomes False.
5. Then continue with the next statement after the loop.

Example
count = 0
while count < 5:
print("Count is", count) count += 1
print("Done!")
Dept. of CSE (Data Science) 24
Python Programming [1BPLC105B] Module 1

Output:
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4 Done!
The Collatz 3n + 1 Sequence Definition
The Collatz sequence (or 3n + 1 problem) is a famous unsolved problem in mathematics.
Algorithm (steps)
1. Start with any positive integer n.
2. If n is even → divide by 2
3. If n is odd → multiply by 3 and add 1
4. Repeat until n becomes 1.

Example
n = int(input("Enter a number: "))
while n != 1:
print(n, end=" ")
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1 print(n)

If you enter 6, output:


6 3 10 5 16 8 4 2 1

Tables
A table is a systematic way to display values — usually two columns:
• one for input
• one for output (f of x)
Tables help visualize relationships between variables.
Example – Square Table
for x in range(1, 6):
print(x, x**2)
Dept. of CSE (Data Science) 25
Python Programming [1BPLC105B] Module 1

Output:
11
24
39
4 16
52
Two-Dimensional Tables
When data depend on two variables (e.g., multiplication table), use nested loops.
Example – Multiplication Table
for row in range(1, 6):
for col in range(1, 6):
print(row * col, end="\t")
print()
Output:
12345
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

The break Statement

 Exits the loop immediately, regardless of the loop condition.

Syntax Example

while True:
n = int(input("Enter a positive number: "))
if n < 0:
break
print("You entered:", n)
print("Loop terminated.")

If a negative number is entered, the loop stops.


Use Cases

Dept. of CSE (Data Science) 26


Python Programming [1BPLC105B] Module 1

 Stop when a special value or error is encountered.


 Early exit from an infinite loop.

The continue Statement


 Continue statements are used inside loops. When the program execution reaches a
continue statement, the program execution immediately jumps back to the start of the
loop and re-evaluates the loop’s condition.
 Skips the rest of the current iteration and jumps back to the loop header.

Example
for n in range(1, 10):
if n % 2 == 0:
continue
print(n)

Output: 1 3 5 7 9 (Evens are skipped.)

Paired Data

Paired data are two lists that contain related information — e.g., student names and marks.

Example

names = ["Alice", "Bob", "Carol"]


marks = [85, 90, 78]
for i in range(len(names)):
print(names[i], marks[i])
Output:
Alice 85
Bob 90
Carol 78

Dept. of CSE (Data Science) 27


Python Programming [1BPLC105B] Module 1

Nested Loops for Nested Data

When data contain lists within lists (e.g., matrix), use nested loops.
Example – Matrix Traversal
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for value in row:
print(value, end=" ")
print()

Output:
123
456
789
Examp1e 2:
students = [
("John", ["CompSci", "Physics"]),
("Vusi", ["Maths", "CompSci", "Stats"]),
("Jess", ["CompSci", "Accounting", "Economics", "Management"]),
("Sarah", ["InfSys", "Accounting", "Economics", "CommLaw"]),
("Zuki", ["Sociology", "Economics", "Law", "Stats", "Music"])]

for name, subjects in students:


print(name, "takes", len(subjects), "courses")

output:
John takes 2 courses
Vusi takes 3 courses
Jess takes 4 courses
Sarah takes 4 courses
Zuki takes 5 courses
Example 3:

Dept. of CSE (Data Science) 28


Python Programming [1BPLC105B] Module 1

counter = 0
for name, subjects in students:
for s in subjects: # A nested loop!
if s == "CompSci":
counter += 1
print("The number of students taking CompSci is", counter)

output: The number of students taking CompSci is 3


The Starting, Stopping, and Stepping Arguments to range()
range() to follow any sequence of integers, including starting at a number other than
zero.
for i in range(12, 16):
print(i) # prints 12 13 14 15

The range() function can also be called with three arguments. The first two arguments
will be the start and stop values, and the third will be the step argument. The step is the
amount that the variable is increased by after each iteration.
for i in range(0, 10, 2): #Begin: 0 End: 10 (Exclude) interval: 2
print(i) #prints 0 2 4 6 8

The range() function is flexible in the sequence of numbers it produces for for loops.
for i in range(5, -1, -1):
print(i) #5 4 3 2 1 0

The pre-test loop — standard loop behaviour


for and while loops do their tests at the start, before executing any part of the body. They’re
called pre-test loops.

The middle-test loop flowchart

Dept. of CSE (Data Science) 29


Python Programming [1BPLC105B] Module 1

The middle-test loop with the exit test is in the middle of the body, rather than at the
beginning or at the end.
total = 0
while True:
response = input("Enter the next number.
(Leave blank to end)")
if response == "" or response == "-1":
break
total += int(response)
print("The total of the numbers you entered is ",
total)

The Post test loop


A post-test loop that puts its exit test as the last thing in the body. Post-test loops are used
when you want to be sure that the loop body always executes at least once (because the first
test only happens at the end of the execution of the first loop body).
while True:
play_the_game_once()
response = input("Play again? (yes or no)")
if response != "yes":
break
print("Goodbye!")

Functions
In Python, a function is a named sequence of statements that belong together. Their primary
purpose is to help us organize programs into chunks that match how we think about the
problem.
The syntax for a function definition is:

def <NAME>( <PARAMETERS> ):

<STATEMENTS>

• A function is a block of organized, reusable code that is used to perform a single,


related action.
Dept. of CSE (Data Science) 30
Python Programming [1BPLC105B] Module 1

• It provides better modularity to application and a high degree of code reusing.


• A function is like a mini-program within a program.
• Python provides several built-in functions like print(), input(), and len() functions, but
you can also write your own functions.
Defining a Function
• Function block begins with a keyword def followed by the function name and
parenthesis
• Any number of input parameters should be placed within these parentheses
• A colon
• Starting on the next line an indented block of code.
• The return statement at the end of code block exits a function. A return statement with
no arguments is the same as return None
Syntax:
def functionname(parameters):
function block
return [expression]
Example
def printme(str):
print(str)
return
printme(“Abc”)

Calling a function
• It can be called by name of the function and passing arguments.
• Ex:- printme(‘Vemana Institute of Technology’)
Example :
def hello(name):
print('Hello ' + name)
hello('Alice') #Hello Alice
hello('Bob') # Hello Bob

The None Value

 In Python there is a value called None, which represents the absence of a value.

Dept. of CSE (Data Science) 31


Python Programming [1BPLC105B] Module 1

 None is the only value of the NoneType data type. (Other programming languages
might call this value null, nil, or undefined.)
 None must be typed with a capital N.
 To know the return value of None
>>> spam = print('Hello!') #Hello!, here spam doesnot have value
>>> None == spam #True
>>> type(spam) #<class 'NoneType'>
Parameters and Arguments
• The information into the functions can be passed as the parameters. The parameters
are specified in the parentheses. We can give any number of parameters, but we have to
separate them with a comma.
Example 1
#defining the function
def func (name):
print("Hai ",name); #print(‘Hai’+name)
#calling the function
func("Manu")

Example 2: Finding sum of 2 numbers


#python function to calculate the sum of two variables #defining the function
def sum (a,b):
return a+b;
#taking values from the user
a = int(input("Enter a: "))
b = int(input("Enter b: "))
#printing the sum of a and b
print("Sum = ",sum(a,b))

Example 3: Print Hai Message


>>> def print_twice(bruce):
print(bruce) #print hai 5 times
print(bruce) #print hai 5 times
>>> print_twice('Hai')#prints Hai Hai (2 times)
>>>print_twice('Hai '*5) #prints Hai Hai Hai Hai Hai (twice)
Dept. of CSE (Data Science) 32
Python Programming [1BPLC105B] Module 1

• Function definition cannot be empty, otherwise error


• To define empty function, use pass keyword
Example
def sum(a,b):
pass
sum(10,20)

Functions that require arguments


Most functions require arguments: the arguments provide for generalization. For example, if
we want to find the absolute value of a number, we have to indicate what the number is.
Python has a built-in function for computing the absolute value:
>>> abs(5)
5
>>> abs(-5)
5
The built-in function pow takes two arguments, the base and the exponent
>>> pow(2, 3)
8
>>> pow(7, 4)
2401
max can be passed any number of arguments, separated by commas, and will return the
largest value passed
>>> max(7, 11)
11
>>> max(4, 1, 17, 2, 12)
17
>>> max(3 * 11, 5**3, 512 - 9, 1024**0)
503

Functions that return values


The return statement ends a function and sends a value back to the caller. It can return any
data type, multiple values (packed into a tuple), or None if no value is given.

Dept. of CSE (Data Science) 33


Python Programming [1BPLC105B] Module 1

Syntax:
return [expression]

Parameters: return ends the function, [expression] is the optional value to return (defaults to
None).

biggest = max(3, 7, 2, 5)
x = abs(3 - 11) + 10
Example 1:
def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2
print(square_value(2))
print(square_value(-4))

Example 2:
def evenOdd(x):
if (x % 2 == 0):
return "Even"
else:
return "Odd"

print(evenOdd(16))
print(evenOdd(7))

Dept. of CSE (Data Science) 34

You might also like