0% found this document useful (0 votes)
4 views

Python Notes 4th Sem AKTU

This document provides an introduction to Python, including its history, limitations, and fundamental concepts such as tokens, keywords, identifiers, literals, operators, and data types. It outlines the various types of literals (numeric, string, boolean, collection, and special literals) and details the operators available in Python for arithmetic, assignment, comparison, logical, identity, membership, and bitwise operations. Additionally, it explains the built-in data types in Python and how to determine and set the data type of variables.

Uploaded by

rockynoob002
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)
4 views

Python Notes 4th Sem AKTU

This document provides an introduction to Python, including its history, limitations, and fundamental concepts such as tokens, keywords, identifiers, literals, operators, and data types. It outlines the various types of literals (numeric, string, boolean, collection, and special literals) and details the operators available in Python for arithmetic, assignment, comparison, logical, identity, membership, and bitwise operations. Additionally, it explains the built-in data types in Python and how to determine and set the data type of variables.

Uploaded by

rockynoob002
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
You are on page 1/ 23

Unit 1(Introduction to Python)

Introduction
Python was created by Guido Van Rossum
 The language was released in February I991.
 Python got its name from a BBC comedy series from seventies- “Monty Python’s Flying
Circus”.
 Python can be used to follow both Procedural approach and Object Oriented approach of
programming.
 It is free to use.

Limitations (Minus) of Python


 Not the fastest language
 Lesser Libraries than C, Java, Perl
 Not Strong on Type-binding
 Not Easily convertible

Tokens
In a passage of text, individual words and punctuation marks are called tokens or lexical units or
lexical elements. The smallest individual unit in a program is known as Tokens.
Python has following tokens:
 Keywords
 Identifiers (Name)
 Literals
 Operators
 Punctuators

Keywords
Keywords are the reserved words and have special meaning for python interpreter. Every keyword
is assigned specific work and it can be used only for that purpose.

List of All Python Keywords


and Logical operators

break Break out of Python loops

class Used for defining Classes


continue Keyword used to continue with the Python loop by skipping the existing

def Keyword used for defining a function

del Used for deleting objects in python

elif Part of the if-elif-else conditional statement in python

else Same as above

for Define a Python for loop

if Used for defining an “if” condition

import Python keyword used to import modules

in Checks if specified values are present in an iterable object

is This keyword is used to test for equality.

not Logical operator to negate a condition

or A logical operator used when either one of the conditions needs to be true

while Used for defining a python while loop

Identifier
Python Identifier is the names given to different parts of program like variables, objects, classes,
functions etc.
Identifier forming rules of Python are:
 Is an arbitrarily long sequence of letters and digits.
 The first character must be letter or underscore
 Upper and lower case are different
 The digits 0-9 are allowed except for first character
 It must not be a keyword
 No special characters are allowed other than underscore is allowed.
 Space not allowed

Literals
 When speaking of literals in Python, they refer to fixed constant values that are assigned to
variables or used directly in expressions. The constant values are of varying types, such
as numbers, strings, Booleans, collections, or other special identifiers. Unlike the variables above,
literals are immutable, which means they cannot be changed after being defined.
 Literals in Python are the building blocks of a program. They are fixed, unchangeable values
of a specific data type. We encode literals directly into the script. In simple terms, Python
literals are static data stored within the source code.
 Literals are self-explanatory, and we don’t need to evaluate them. While variables are
containers storing values that can be changed, literals are constant data elements. We use
them directly in expressions to designate data that can’t be modified, such as data
specifying the software's operating parameters.

Example
1. x = 10 # Integer literal
2. print(x)

Literals are grouped under the following categories:

1. Numeric Literals: Integers, floating points, and even complex numbers.


2. String Literals: Literally any set of characters written in a string of quotes.
3. Boolean Literals: The two most commonly accepted values, True or False.
4. Collection Literals: Lists, tuples, dictionaries, and sets.
5. Special Literal: The keyword None signifies the lack of value.

Numeric Literals
Numeric literals are values that can be represented in Python, as their names suggest. They can be
assigned different values and are further described in three categories:

a) Integer (int)
Integer literals are defined as whole numbers without any decimals. They can be negative, positive or zero.
Python also allows the use of various formats of integer literals.

1. Decimal (Base 10): Uses digits 0-9 (e.g., 100, -5, 0).
2. Binary (Base 2): Prefixed with 0b or 0B (e.g., 0b1010 for decimal 10).
3. Octal (Base 8): Prefixed with 0o or 0O (e.g., 0o12 for decimal 10).
4. Hexadecimal (Base 16): Prefixed with 0x or 0X (e.g., 0xA for decimal 10).

Example
1. integer_num = 10 # Decimal integer
2. binary_num = 0b1010 # Binary integer
3. octal_num = 0o12 # Octal integer
4. hexadecimal_num = 0xA # Hexadecimal integer

5. print(integer_num)
6. print(binary_num)
7. print(octal_num)
8. print(hexadecimal_num)
Execute Now

Output:

10
10
10
10
In the above example, we have initialized multiple variables using different forms of integer literal and
printed their values.

b) Floating-Point (float)
Floating-point literals represent numbers that contain a decimal point or are written in scientific notation.
They are used for precise calculations involving fractions or real numbers.

o Standard floating-point notation: (e.g., 3.14, -0.99, 2.5)


o Scientific notation (exponential form): Uses e or E to indicate powers of 10 (e.g., 2.5e3 for 2500.0).

Example
1. float_num = 20.5 # Standard floating-point number
2. scientific_num = 2.5e3 # Equivalent to 2500.0
3. negative_float = -0.99 # Negative floating-point number

4. print(float_num)
5. print(scientific_num)
6. print(negative_float)
Execute Now

Output:

20.5
2500.0
-0.99
In the above example, we have initialized multiple variables using different floating-point literals and
printed their values.

c) Complex Numbers (complex)


Python supports complex numbers, which consist of a real part and an imaginary part. The imaginary part
is denoted using j or J.

2. String Literals
String literals in Python are sequences of characters enclosed in either single (' '), double (" "), or triple (''' '''
or """ """) quotes. They are used to store text data, including words, sentences, or even multi-line
paragraphs.

Types of String Literals:

a) Single-Line Strings
These are enclosed within single or double quotes and are used for short textual data.

Example
1. single_string = 'Hello' # Single-quoted string
2. double_string = "Python" # Double-quoted string
3. print(single_string)
4. print(double_string)
Output:

Hello
Python
In the above example, we have initialized multiple variables using different format of single-line string
literal and printed their values.

b) Multi-Line Strings
Multi-line strings are enclosed within triple single (''' ''') or triple-double (""" """) quotes. They are used
when the text spans multiple lines, such as documentation or large text blocks.

Example
1. # multi-line string
2. multi_string = """This is a multi-line string.
3. It can span multiple lines.
4. Useful for documentation and long texts."""

5. print(multi_string)
Execute Now

Output:

This is a multi-line string.


It can span multiple lines.
Useful for documentation and long texts.
In the above example, we have initialized a multi-line string literal and printed its value.

c) Escape Characters in Strings


Python allows the use of escape characters to insert special characters within a string.

o \n - Newline
o \t - Tab
o \' - Single quote
o \" - Double quote
o \\ - Backslash

Example
1. escaped_string = 'Hello\nWorld' # Inserts a new line
2. print(escaped_string)
Execute Now

Output:

Hello
World
In the above example, we have initialized a multi-line string literal and printed its value.

d) String Concatenation and Repetition


Python allows strings to be combined using the + operator (concatenation) and repeated using the *
operator.

Example
1. string1 = "Hello "
2. string2 = "World"
3. concatenated = string1 + string2 # "Hello World"
4. repeated = string1 * 3 # "Hello Hello Hello"
5. print(concatenated)
6. print(repeated)
Execute Now

Output:

Hello World
Hello Hello Hello
In the above example, we have initialized two strings and then performed operations like concatenation
and repetition.

3. Boolean Literals
Boolean literals represent truth values in Python. There are only two Boolean literals:

1. True
2. False

Example
1. is_python_fun = True # Boolean literal
2. is_raining = False

3. print(is_python_fun)
4. print(is_raining)
Execute Now

Output:

True
False
In the above example, we have initialized and printed two variables with Boolean values.

4. Collection Literals
Collection literals represent groupings of values and include the following types:

1. List Literals: Ordered and mutable collection (e.g., [1, 2, 3]).


2. Tuple Literals: Ordered and immutable collection (e.g., (1, 2, 3)).
3. Dictionary Literals: Key-value pairs (e.g., {'name': 'Alice', 'age': 25}).
4. Set Literals: Unordered collection of unique items (e.g., {1, 2, 3}).

Example
1. list_literal = [10, 20, 30] # List literal
2. tuple_literal = (10, 20, 30) # Tuple literal
3. dict_literal = {'a': 1, 'b': 2} # Dictionary literal
4. set_literal = {10, 20, 30} # Set literal

5. print(list_literal)
6. print(tuple_literal)
7. print(dict_literal)
8. print(set_literal)
Execute Now
Output:

[10, 20, 30]


(10, 20, 30)
{'a': 1, 'b': 2}
{10, 20, 30}
In the above example, we have initialized a list, tuple, dictionary and set and printed them for users.

5. Special Literal
Python has a special literal called None, which represents the absence of a value.

When we print a variable without assigning it a value, it returns None as output. If we compare None with anything, it
returns False. We use None at the end of a Python list.

Example
1. val = None
2. print(val)
Output:

None

Python Operators
Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

Python Arithmetic Operators


Arithmetic operators are used with numeric values to perform common mathematical
operations:
Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

 Python Assignment Operators


 Assignment operators are used to assign values to variables:

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

**= 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

:= print(x := 3) x=3
print(x)

Python Comparison Operators


Comparison operators are used to compare two values:

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

Python Logical Operators


Logical operators are used to combine conditional statements:

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 true x < 5 or x < 4

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

Python Identity Operators


Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:

Operator Description 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

Python Membership Operators


Membership operators are used to test if a sequence is presented in an object:

Operator Description 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

Python Bitwise Operators


Bitwise operators are used to compare (binary) numbers:

Operator Name Description Example


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

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

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


1

~ NOT Inverts all the bits ~x

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

>> Signed Shift right by pushing copies of the x >> 2


right shift leftmost bit in from the left, and let the
rightmost bits fall off

Python Data Types


Built-in Data Types
In programming, data type is an important concept.

Variables can store data of different types, and different types can do different things.

Python has the following data types built-in by default, in these categories:

Text Type: str


Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Boolean Type: bool

None Type: NoneType

Getting the Data Type


You can get the data type of any object by using the type() function:

Example
Print the data type of the variable x:

x = 5
print(type(x))

Output:
<Class ‘int’>

Setting the Data Type


In Python, the data type is set when you assign a value to a variable:

Example Data Type

x = "Hello World" str

x = 20 int

x = 20.5 float
x = 1j complex

x = ["apple", "banana", "cherry"] list

x = ("apple", "banana", "cherry") tuple

x = range(6) range

x = {"name" : "John", "age" : 36} dict

x = {"apple", "banana", "cherry"} set

x = True bool

x = b"Hello" bytes

x = None NoneType

Unit2
(Python Program Flow Control Conditional
blocks)
Python Conditions and If statements
Python supports the usual logical conditions from mathematics:

 Equals: a == b
 Not Equals: a != b
 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements" and
loops.

An "if statement" is written by using the if keyword.

Example
If statement:

a = 33
b = 200
if b > a:
print("b is greater than a")

Indentation
Python relies on indentation (whitespace at the beginning of a line) to define scope in the
code. Other programming languages often use curly-brackets for this purpose.

Example
If statement, without indentation (will raise an error):

a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error

Elif
The elif keyword is Python's way of saying "if the previous conditions were not true,
then try this condition".

Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")

Else
The else keyword catches anything which isn't caught by the preceding conditions.

Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")

In this example a is greater than b, so the first condition is not true, also
the elif condition is not true, so we go to the else condition and print to screen that "a
is greater than b".

You can also have an else without the elif:

Example
a = 200
b = 33
if b > a:
print ("b is greater than a")
else:
print ("b is not greater than a")

Short Hand If
If you have only one statement to execute, you can put it on the same line as the if
statement.

Example
One line if statement:

if a > b: print("a is greater than b")

And
The and keyword is a logical operator, and is used to combine conditional statements:

Example
Test if a is greater than b, AND if c is greater than a:

a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")

Or
The or keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, OR if a is greater than c:

a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")

Not
The not keyword is a logical operator, and is used to reverse the result of the conditional
statement:

Example
Test if a is NOT greater than b:

a = 33
b = 200
if not a > b:
print("a is NOT greater than b")

Nested If
You can have if statements inside if statements, this is called nested if statements.

Example
x = 41

if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")

The pass Statement


if statements cannot be empty, but if you for some reason have an if statement with no
content, put in the pass statement to avoid getting an error.

Example
a = 33
b = 200

if b > a:
pass
For Loop
A for loop in Python is a control flow statement that is used to repeatedly
execute a group of statements as long as the condition is satisfied.

Example
a=10

for i in range(a):

print(i)

Output:

0
1
2
3
4
5
6
7
8
9

Example
Loop through the letters in the word "banana":

for x in "banana":
print(x)
Output:
b
a
n
a
n
a

Python Collections (Arrays)


There are four collection data types in the Python programming language:

 List is a collection which is ordered and changeable. Allows duplicate members.


 Tuple is a collection which is ordered and unchangeable. Allows duplicate
members.
 Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate
members.
 Dictionary is a collection which is ordered** and changeable. No duplicate
members.

Tuple
Tuples are used to store multiple items in a single variable.

Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Set, and Dictionary, all with different qualities and usage.

A tuple is a collection which is ordered and unchangeable.

Tuples are written with round brackets.

Example
Create a Tuple:

tuple = ("apple", "banana", "cherry")


print(tuple)
Output:
(‘apple’, ’banana’, ’cherry’)

Python for Loops


A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary,
a set, or a string).

This is less like the for keyword in other programming languages, and works more like an
iterator method as found in other object-orientated programming languages.

With the for loop we can execute a set of statements, once for each item in a list, tuple,
set etc.

Example
Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)

The for loop does not require an indexing variable to set beforehand.

Looping Through a String


Even strings are iterable objects, they contain a sequence of characters:
Tuple Items
Tuple items are ordered, (Mutable) Unchangeable, and allow duplicate values.

Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered
When we say that tuples are ordered, it means that the items have a defined order, and
that order will not change.

Mutable (Unchangeable)
Tuples are unchangeable, meaning that we cannot change, add or remove items after the
tuple has been created.

Allow Duplicates
Since tuples are indexed, they can have items with the same value:

Example
Tuples allow duplicate values:

tuple = ("apple", "banana", "cherry", "apple", "cherry")


print(tuple)
Output:
("apple", "banana", "cherry", "apple", "cherry")

Tuple Length
To determine how many items a tuple has, use the len() function:

Example
Print the number of items in the tuple:

thistuple = ("apple", "banana", "cherry")


print(len(thistuple))

Output:

Tuple Items - Data Types


Tuple items can be of any data type:

Example
String, int and boolean data types:

tuple1 = ("apple", "banana", "cherry")


tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)

Output:

("apple", "banana", "cherry")


(1, 5, 7, 9, 3)
(True, False, False)

Access Tuple Items


You can access tuple items by referring to the index number, inside square brackets:

Example
Print the second item in the tuple:

tuple = ("apple", "banana", "cherry")


print(tuple[1])
Output:
banana

The break Statement


With the break statement we can stop the loop before it has looped through all the items:

Example
Exit the loop when x is "banana":

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
if x == "banana":
break

Example
Exit the loop when x is "banana", but this time the break comes before the print:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)

The continue Statement


With the continue statement we can stop the current iteration of the loop, and continue
with the next:

Example
Do not print banana:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
continue
print(x)

The range() Function


To loop through a set of code a specified number of times, we can use
the range() function,

The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.

Example
Using the range() function:

for x in range(6):
print(x)

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.

The range() function defaults to 0 as a starting value, however it is possible to specify


the starting value by adding a parameter: range(2, 6), which means values from 2 to 6
(but not including 6):

Example
Using the start parameter:

for x in range(2, 6):


print(x)

The range() function defaults to increment the sequence by 1, however it is possible to


specify the increment value by adding a third parameter: range(2, 30, 3):
Example
Increment the sequence with 3 (default is 1):

for x in range(2, 30, 3):


print(x)

Else in For Loop


The else keyword in a for loop specifies a block of code to be executed when the loop is
finished:

Example
Print all numbers from 0 to 5, and print a message when the loop has ended:

for x in range(6):
print(x)
else:
print("Finally finished!")

You might also like