[go: up one dir, main page]

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

PYTHON - 1

The document provides an overview of Python programming concepts including algorithms, variables, data types, control structures, functions, and data structures like lists, tuples, dictionaries, and sets. It explains the representation of algorithms, operator precedence, implicit and explicit conversions, and the use of escape sequences. Additionally, it covers the use of libraries such as random and math, and introduces date and time functions in Python.

Uploaded by

6s29qnyzsm
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)
13 views18 pages

PYTHON - 1

The document provides an overview of Python programming concepts including algorithms, variables, data types, control structures, functions, and data structures like lists, tuples, dictionaries, and sets. It explains the representation of algorithms, operator precedence, implicit and explicit conversions, and the use of escape sequences. Additionally, it covers the use of libraries such as random and math, and introduces date and time functions in Python.

Uploaded by

6s29qnyzsm
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
You are on page 1/ 18

PYTHON – 1 (NOTES)

- By SIMRAN KAUR(CSE-G7)

ALGORITHM AND ITS REPRESENTATION –


Algorithm should be represented from the mental thoughts into a form which others can understand.
There are primarily two ways of representing an algorithm:

Flow chart: Diagrammatic way of representing the algorithm.

Pseudo-code: Representing the algorithm between a program and normal English.

VARIABLES AND OPERATORS-


Variables are like containers of data and the value of variable can vary in the pseudo code.

"=" is an assignment operator. It is used to assign values to the variables.

Like assignment operator, there are other operators which can be used to perform various operations.

1. Arithmetic operators: Used for performing arithmetic operations.

// operator indicates integer division. E.g.- 11//2=5

2. Relational operators: Also known as comparison operators are used to compare values. Result of a
relational expression is always either true or false.
3. Logical operators are used to combine one or more relational expressions.

DATATYPES IN PYTHON-
Python supports following data types-

Numeric - INT, LONG, COMPLEX - [123, 36722534]


Numeric with decimal point - FLOAT - [45.67, 3.89]

Alphanumeric - STRING - [hello, code]

BOOLEAN - [True, False (None, False, 0, empty string)]

In Python, the data type of a value can be identified by using type(value) .

e.g. -

print(type(3)) #O/P - <class 'int'>

print(type("Hello World")) #O/P - <class 'str'>

print(type(False)) #O/P - <class 'bool'>

print(type(2.0)) #O/P - <class 'float'>

NOTE--Here, print() function is used to print the type of data type using type() function.

PRECEDENCE –
Precedence of an operator can be identified based on the rule - BODMAS. Brackets followed by Orders
(Powers, Roots), followed by modulo, Division and Multiplication, followed by Addition and Subtraction.

1. Brackets have the highest precedence followed by orders.

2. Modulo, Division and Multiplication have the same precedence. Hence if all appear in an expression, they
are evaluated from Left to Right.

3. 3. Addition and Subtraction have the same precedence. Hence if both appear in an expression, they are
evaluated from Left to Right.

IMPLICIT CONVERSION –
Take a look at the code: num=1 + 1.0 #interpreter assumed 1 s 1.0

The result is 2.0 ! #1.0+1.0=2.0

EXPLICIT CONVERSION –
Take a look at the below code: num=1 + int(1.0) #1.0 converted to 1

The result will be 2 ! #1+1=2

NOTE-

*Converting a floating point value to integer would result in loss of decimal point values.

*A larger data type if converted to smaller data type will result in loss of data as the number will
be truncated.

* num=str(10) ----- Value of num will be “10”

ESCAPE SEQUENCES –
1. \n = next line
2. \t = tab space
3. \” = “ in string
4. \\\\ = \\ and \\ = \
5. , end=" " = joins strings of 2 different print statements

E.g. - print("Did you see I start here", end=" ")

print("and I end in the same line although from a different print?")


OUTPUT- Did you see I start here and I end in the same line although from a different print?

FUNCTIONS –
A function is a block of code that performs a particular task. In python, functions are declared using the
keyword def. INDENTATION is very important in programs.

def calculate_sum(data1, data2):

#All the statements in the block of code must have the same level of indentation

result_sum = data1+data2

return result_sum

result = calculate_sum(10,20)

print(result)

Flow of Execution in Functions

Analyze this code to observe:

 Function call

 Actual arguments being copied to formal arguments

 Execution of function body

 Return from function


CODE –
OUTPUT – Passport is valid

“RETURN” in FUNCTION –

USE OF VALUES RETURNED FROM FUNCTION –


CONTROL STRUCTURES –

SELECTION- if-else, nested if-else(if-else inside if-else)


if(condition):

Do this

else: do this

ITERATION- for loop , while loop , nested loops

A) for loop >>>

B) while loop >>> while(condition): do this and iterate


## We can create a sequence of values in Python using range(x,y,step). It creates a sequence from x to y-1 with a difference of step
between each value.

## 1. start - Starting number of the sequence

2. end - Generate number up to end, but not including this number

3. step - Difference between each number in the sequence

##It is not mandatory to give step. The default value of step is 1.


OUTPUT: The current number is 1

The current number is 3

The current number is 5

The current number is 7

The current number is 9

#use of loops

‘BREAK’ STATEMENT – When we want to stop a loop or break away from it we can use break statement.

‘CONTINUE’ STATEMENT - When we want to skip the remaining portion of loop statements and continue with the next
iteration, we can use continue statement.

ECLIPSE –
Eclipse is a modern IDE. IDE stands of Integrated Development Environment, where all the necessary tools for developing your code
are integrated into one piece.

LIST IN PYTHON –
It can be used to store a group of elements together in a sequence.

ticket_list = [78808, 26302, 93634, 13503, 48306]


# Each element in the list has a position in the list known as an index.

# The list index starts from zero. Index positions actually help us to directly access a value from the list.

# list_name[index] can be used to directly access the list element at the mentioned index position.

# We can also use it to directly modify an element in the list. e.g. - ticket_list[3]=13504

# We cannot access values beyond the total number of elements in the list. e.g. - print(ticket_list[5]) will result in
index out of bound error.

SAMPLE CODE FOR LIST IN PYTHON –


** We can also use loop to access elements of list –

list_of_airlines=["AI","EM","BA"]

print("Iterating the list using range()")

for index in range(0,len(list_of_airlines)):

print(list_of_airlines[index]) #prints AI, EM, BA with new line

print("Iterating the list using keyword in")

for airline in list_of_airlines:

print(airline) #prints AI, EM, BA with new line

** If we just want to find out whether an element is there in a list, we need not iterate through the list. Instead
we can check using if..in syntax.

list_of_airlines=["AI","EM","BA"]

airline="AI"

if airline in list_of_airlines:

print("Airline found")

else:

print("Airline not found") # OUTPUT – Airline found

SLICING IN LISTS –
e.g. -

sub_list = list_of_airlines[1:4] provides a sub list from index position 1 to 3 (i.e., 1 to (4-1)).

Indices may also be considered negative as shown above. This is normally used to count from right.

For example: To fetch the second last airline in the list, we can write list_of_airlines[-2].

This is equivalent to list_of_airlines[len(list_of_airlines)-2].


Negative indices can also be used for slicing.

For example: list_of_airlines[-4:-1] will give us the same output as list_of_airlines[1:4]

## If we want to store the airline details of all airlines operating from an airport, we may use a list of lists as
shown in the code below.

LIST FUNCTIONS –
TUPLE IN PYTHON –
Like list, tuple can also store a sequence of elements but the value of the elements cannot be changed.
(i.e. tuples are IMMUTABLE). Elements can be homogeneous or heterogeneous but they are
READ-ONLY.

Suppose it is mandatory to have the following types of food in the lunch menu of the passengers.

Welcome Drink, Veg Starter, Non-Veg Starter, Veg Main Course, Non-Veg Main Course, Dessert

# Other operations are similar to list.

# DIFFERENCE BETWEEN LIST AND TUPLE –

STRING IN PYTHON –
Alphabetical or alpha numerical values are called strings. Each value in a string is called a character.

Just like list elements, we can access the characters in a string based on its index position.

In Python, string is a data type and anything enclosed in a single quote or double quote is considered to
be a string. All the remaining operations are similar to lists. But like tuple, strings are also IMMUTABLE.

Here is a code to explain different operations performed on strings.

1. Length of string
2. Slicing a string
3. Concatenating two strings

STRING FUNCTIONS –
CHOOSING BETWEEN LIST, TUPLE AND STRING –

row1 = (101,"Dallas",3.5)

row2 = (102,"Atlanta",5.6)

row3 = (103,"Tokyo",9.8)

table = [row1,row2,row3]

print(table[0]) #prints (101, 'Dallas', 3.5)

print(table[1]) #prints (102, 'Atlanta', 5.6)

print(table[2]) #prints (103, 'Tokyo', 9.8)

### Here,

 “Dallas”, “Atlanta”, “Tokyo” are Strings


 row1, row2, row3 are Tuples
 Table is a List
DICTIONARY IN PYTHON –
Dictionary allows to store key-value pairs where each key is unique.

One of the advantage of using dictionary is that it allows very fast search for value based on key.

The key should be unique and can be of any immutable data type.

Like lists, dictionaries are mutable.

Dictionary in Python also have many inbuilt functions.

SETS IN PYTHON –
A set is an unordered group of values with no duplicate entries.

Set can be created by using the keyword set or by using curly braces {}.

Set function is used to eliminate duplicate values in a list.

RANDOM LIBRARY IN PYTHON –


Python has many inbuilt packages and modules. One of the most useful modules is random.
This module helps in generating random numbers.

The code given below generates a random number between x and y-1 (both inclusive) using
the randrange function of the random module.

CODE - import random

x=10

y=50

print(random.randrange(x,y))

MATH LIBRARY –
math is another useful module in Python. Once you have imported the math module, you can
use some of the below functions:

DATE AND TIME FUNCTIONS –


Python has inbuilt modules called time and datetime. They are very helpful in finding details of
time. (GMT = Greenwich Mean Time)

You might also like