Dsa (Week 1) - Python

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 57

DSA (WEEK 1)

Basics of Programming
Need Of Python Programming For DSA

• Being a High-Level and #1 Programming Language, using Python for Data Structure is
likely to be among the good choice due to its easy syntax and implementation.
• Python can be considered the best choice for DSA. Python is dynamically typed (no
need to declare types)and highly abstracted, it has a very clean and simplistic syntax. To
find a solution to any problem, you must first define the solution, analyze it and
implement the solution.

Which is best DSA with Python or Java?

Python is easier to understand. Python offers simplicity in its syntax, which makes it
easier to learn. you don't have to write the data types in Python, as it is a dynamic
language. For writing a simple statement such as "Hello World" in Java, you will need at
least 3-4 lines of coding
Advantages of Python 3
1. Python 3 has a simple syntax that is easy to learn and read, making it a good choice
for beginners.

2. Python 3 is a high-level language that has a large standard library and many third-
party libraries available, making it a versatile language that can be used for a wide
variety of applications.

3. Python 3 supports multiple programming paradigms, including object-oriented,


functional, and procedural programming.

4. Python 3 is an interpreted language, meaning that it does not need to be compiled


before running, making it easy to write and test code quickly.

5. Python 3 has good support for data analysis and scientific computing, with libraries
such as NumPy and Pandas.
How to Get Started With Python?
• Python is a cross-platform programming language, which means that it can run on
multiple platforms like Windows, macOS, Linux,
• It is free and open-source.
• Install Python
• here's how you can install and run Python on your computer.
1.Download the latest version of Python.
2.Run the installer file and follow the steps to install Python
During the install process, check Add Python to environment variables. This will
add Python to environment variables, and you can run Python from any part of the
computer.
 Once you finish the installation process, you can run
There are multiple ways to run Python on your System :
1. Using CMD
2. Using IDLE or other softwares (eg. VsCode, Pycharm, Jupyter Notebook)

1. Run Python in Immediate mode(CMD)


Once Python is installed, typing python in the command line will invoke the interpreter in
immediate mode. We can directly type in Python code, and press Enter to get the output.

Try typing in 1 + 1 and press enter. We get 2 as the output. This prompt can be used as a
calculator. To exit this mode, type quit() and press enter.
2. Run Python in the Integrated Development Environment (IDE)

We can use any text editing software to write a Python script file.

We just need to save it with the .py extension. But using an IDE can make our life a lot easier. IDE
is a piece of software that provides useful features like code hinting, syntax highlighting and
checking, file explorers, etc. to the programmer for application development.
Python Variables

• In other programming languages like C, C++, and Java, you will need to declare the
type of variables but in Python you don’t need to do that. Just type in the variable and
when values will be given to it, then it will automatically know whether the value given
would be an int, float, or char or even a String.
• Ex :-
 myNumber=2
 myNumber=True
 myNumber=‘ak’
 myNumber=5.6
Python Data Types
Python Data Types
1. Numbers Data Type
In Numbers, there are mainly 3 types which include Integer, Float, and Complex.

These 3 are defined as a class in Python. In order to find to which class the variable belongs to you can
use type () function.

Example:

a=5

print(a, "is of type", type(a)) //Output: 5 is of type <class ‘int’>

b = 2.5

print(b, "is of type", type(b))//Output: 2.5 is of type <class ‘float’>


c = 6+2j

print(c, "is a type", type(c))//(6+2j) is a type <class ‘complex’>

Note:-The type() method in Python can be used to determine variable’s data type. isinstance() determines
whether an object belongs to a specific class.

print(" Is this true or not?:", isinstance(1+3j,complex))


Numbers Data Type Cont…
Python numeric data type is used to hold numeric values like;

• int - holds signed integers of non-limited length.

• long- holds long integers(exists in Python 2.x, deprecated in Python 3.x).

• float- holds floating precision numbers and it’s accurate up to 15 decimal places.

• complex- holds complex numbers.


2. String Data Type
The string is a sequence of characters. Python supports Unicode characters. Generally,
strings are represented by either single or double-quotes.

a = "string in a double quote"

b= 'string in a single quote'

print(a)

print(b)

# using ',' to concatenate the two or several strings

print(a,"concatenated with",b)

#using '+' to concate the two or several strings

print(a+" concated with "+b)

Note:- Multi-line strings can be represented using triple quotes, ”’ or “””.


2. String Data Type Cont….
We can perform several operations in strings like Concatenation, Repetition, and Slicing.

Concatenation: It means the operation of joining two strings together.

Example:

String1 = "Welcome"

String2 ="To Python"

print(String1+String2)

//Output: Welcome To Python

Repetition: It means repeating a sequence of instructions a certain number of times.

Example:

Print(String1*4)//Output: WelcomeWelcomeWelcomeWelcome
3. List Data Type
• A list can contain a series of values.
• List variables are declared by using brackets [ ]. A list is mutable, which means we can modify the list.
• list in Python is it can simultaneously hold different types of data.

Example:

List = [2,4,5.5,"Hi"]

print("List[2] = ", List[2])

Output: List[2] = 5.5

print("List[0:3] = ", List[0:3])

Output: List[0:3] = [2, 4, 5.5]

Updating the list:

List[3] = "Hello"

If we print the whole list, we can see the updated list.

print(List)
3. List Data Type Cont…
#list of having only integers

a= [1,2,3,4,5,6]

print(a)

#list of having only strings

b=["hello","john","reese"]

print(b)

#list of having both integers and strings

c= ["hey","you",1,2,3,"go"]

print(c)

#index are 0 based. this will print a single character

print(c[1]) #this will print "you" in list c


4. Python Tuple
• The tuple is another data type which is a sequence of data similar to a list. But it is immutable. That means data in a
tuple is write-protected. Data in a tuple is written using parenthesis and commas.
• #tuple having only integer type of data.
• a=(1,2,3,4)
• print(a) #prints the whole tuple
• #tuple having multiple type of data.
• b=("hello", 1,2,3,"go")
• print(b) #prints the whole tuple
• #index of tuples are also 0 based.
• print(b[4]) #this prints a single element in a tuple, in this case "go“.\.

Note:-As Tuples are immutable in Python, if we try to update the tuple, then it will generate an error.

Example:

Tuple[2]= "D"

Output: TypeError: ‘tuple’ object does not support item assignment


5. Dictionary Data Type
5. Dictionary Data Type Cont..
Python Dictionary is an unordered sequence of data of key-value pair form. It is similar to
the hash table type. Dictionaries are written within curly braces in the form key:value. It
is very useful to retrieve data in an optimized way among a large amount of data.

#a sample dictionary variable

a = {1:"first name",2:"last name", "age":33}

#print value having key=1

print(a[1])

#print value having key=2

print(a[2])

#print value having key="age"

print(a["age"])
6. Set Data Type
A set is an unordered collection of items. Set is defined by values separated by a comma
inside braces { }

Example:

Set = {5,1,2.6,"python"}

print(Set)

Output: {‘python’, 1, 5, 2.6}


6. Set Data Type cont…
In the set, we can perform operations like union and intersection on two sets.

We can perform Union operation by Using | Operator.

Example:

A = {'a', 'c', 'd'}

B = {'c', 'd', 2 }

print('A U B =', A| B)

Output: A U B = {‘c’, ‘a’, 2, ‘d’}


6. Set Data Type cont…
We can perform Intersection operation by Using & Operator.

A = {100, 7, 8}

B = {200, 4, 7}

print(A & B)

Output: {7}

Note:-As the set is an unordered collection, indexing has no meaning. Hence the slicing operator []
does not work.

Set[1] = 49.3

Output: TypeError: ‘set’ object does not support item assignment


7. Boolean Data Type
A set is an unordered collection of items. Set is defined by values separated by a comma
inside braces { }

True and False are the default values.

True is any non-zero number or the character 'T', while false is any non-zero value or the
character 'F‘.
data type conversion
• As the name says, it is converting the value of one data type to another. This process is
called data type conversion in Python.
How many types of conversion is there in Python?
• Similar to most languages, there are two types of conversion.
• Implicit Type Conversion
• Explicit Type Conversion
What is Implicit Type Conversion?

In implicit conversion, Python converts one data type into another data type without any
user involvement.

Let’s consider the following code.

int_number = 843

float_number = 8.43

result= int_number + float_number

print("Data Type of Integer:",type(int_number))

print("Data Type of Float:",type(float_number))

print("Result Value:",result)

print("Data Type of Result:",type(result))


What is Explicit Type Conversion?
• In this scenario, Python cannot handle data type conversion automatically. So, we use
Explicit conversion for these scenarios

int_number = 843
string_number = “843”
print("Data Type of Integer:",type(int_number ))
print("Data Type of String before
casting:",type(string_number ))
string_number = int(string_number )
print("Data Type of String after
casting:",type(string_number ))
result = int_number + string_number
print("Result:",result )
print("Data type of result :",type(result ))
What is Explicit Type Conversion?
• In Explicit conversion, the user has to convert the data type of an object to the desired
data type as per requirement. One can achieve the above using the default functions –
float(), int(), string().
• This process is sometimes called typecasting of data, as the user casts the data type of
any object.
• Consider the code below.

int_number = 843
string_number = “843”
print("Data Type of Integer:",type(int_number))
print("Data Type of String:",type(string_number))
print(int_number + string_number)
More About String Operations
• A string in Python can contain as many characters as you wish. The only limit is your
machine’s memory resources. A string can also be empty:
• What if you want to include a quote character as part of the string itself?

SyntaxError: invalid syntax


• If you want to include either type of quote character within the string, the simplest way
is to delimit the string with the other type. If a string is to contain a single quote, delimit
it with double quotes and vice versa:
• A string in Python can contain as many characters as you wish. The only limit is your
machine’s memory resources. A string can also be empty:
• What if you want to include a quote character as part of the string itself?

SyntaxError: invalid syntax


• If you want to include either type of quote character within the string, the simplest way
is to delimit the string with the other type. If a string is to contain a single quote, delimit
it with double quotes and vice versa:
Raw Strings
• A raw string literal is preceded by r or R, which specifies that escape sequences in the
associated string are not translated. The backslash character is left in the string:
Triple-Quoted Strings
• There is yet another way of delimiting strings in Python. Triple-quoted strings are
delimited by matching groups of three single quotes or three double quotes

Because newlines can be included without escaping them, this also allows for
multiline strings:
Escape Sequences in Strings
Sometimes, you want Python to interpret a character or sequence of characters within a string
differently. This may occur in one of two ways:
•You may want to suppress the special interpretation that certain characters are usually given within a
string.
•You may want to apply special interpretation to characters in a string which would normally be taken
literally.

Suppressing Special Character Meaning


• Ordinarily, a newline character terminates line input. So pressing Enter in the middle of
a string will cause Python to think it is incomplete:

• To break up a string over more than one line, include a backslash before each newline,
and the newlines will be ignored:
• To include a literal backslash in a string, escape it with a backslash:
Manipulate Strings With Method
• Strings come bundled with special functions called string methods that you can use to
work with and manipulate strings

• Convert a string to uppercase or lowercase

• Remove whitespace from a string

• Determine if a string begins or ends with certain characters


• Converting String Case To convert a string to all lowercase letters, you use the
string’s .lower() method. This is done by tacking .lower() onto the end of the string
itself:
• >>> “Hello".lower()
• hello
• String methods don’t just work on string literals. You can also use .lower() on a string
assigned to a variable:
• >>> name = “Welcome To Class"
• >>> name.lower()
• ‘welcome to class‘
• The opposite of .lower() is .upper(), which converts every character in a string to
uppercase
• len() is a stand-alone function. If you want to determine the length of the name string,
then you call the len() function directly:
• >>> len(name)
• 16
• There are three string methods that you can use to remove whitespace from a string:
• 1. .rstrip() =>.rstrip() removes whitespace from the right side of a string
• 2. .lstrip()=>lstrip() works just like .rstrip(), except that it removes whitespace from the
left-hand side of the string
• 3. .strip()=>To remove whitespace from both the left and the right sides of the string at
the same time, use .strip():
Interact With User Input
• Enter the following into IDLE’s interactive window: >>> input()
• When you press Enter , it looks like nothing happens. The cursor moves to a new line,
but a new >>> doesn’t appear. Python is waiting for you to enter something!

• The text you entered is repeated on a new line with single quotes. That’s because input()
returns as a string any text entered by the user.
• To see how input() works, type the following code into IDLE’s editor window

• The single space at the end of the string "Hey, what's up? " makes sure that when the
user starts to type, the text is separated from the prompt with a space. When the user
types a response and presses Enter , their response is assigned to the user_input variable
• Once you have input from a user, you can do something with it. For example, the
following program takes user input, converts it to uppercase with .upper(), and prints
the result:

• response = input("What is your name? ")


• user_response = response.upper()

• print("Welcome..." + user_response)
Operators and Expressions in python
Arithmetic Operators in Python

.These Python arithmetic operators include Python operators for basic mathematical
operations.
Note:-“The % symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left
hand operand by right-hand operand. It's used to get the remainder of a division problem.”
2. Python Relational Operator
3. Python Assignment Operator
4. Python Logical Operator
Special operators
Python language offers some special types of operators like the identity operator and the membership
operator.

Identity operators

In Python, is and is not are used to check if two values are located on the same part of the memory. Two
variables that are equal does not imply that they are identical.

Operator Meaning Example

is True if the operands are identical x is True


(refer to the same object)

is not True if the operands are not x is not True


identical (do not refer to the same
object)
Membership operators
In Python, in and not in are the membership operators. They are used to test whether a value or variable is
found in a sequence (string, list, tuple, set and dictionary).

In a dictionary we can only test for presence of key, not the value.

Operator Meaning Example

in True if value/variable is found in 5 in x


the sequence

not in True if value/variable is not 5 not in x


found in the sequence
Comments:

• Single-line comments begins with a hash(#) symbol and is useful in mentioning that the
whole line should be considered as a comment until the end of line.
• A Multi line comment is useful when we need to comment on many lines. In python,
triple double quote(“ “ “) and single quote(‘ ‘ ‘)are used for multi-line commenting.

You might also like