[go: up one dir, main page]

0% found this document useful (0 votes)
6 views37 pages

Python Basics

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 37

9/20/23, 10:21 AM Day 1 - Basics OF Python

Python Output
In [1]: # Python is case sensitive
print('Hello World')

Hello World

In [50]: print(hey) # it throws error beacuse only string is always in " "

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_9556\1311815035.py in <module>
----> 1 print(hey) # it throws error beacuse only string always in " "

NameError: name 'hey' is not defined

In [3]: print(7)

In [4]: print(True)

True

In [5]: # how print function strng in python -- it print all the values which we want to pr
print('Hello',3,4,5,True)

Hello 3 4 5 True

In [6]: # sep
print('Hello',3,4,5,True,sep='/') # sep is separator where in print function space

Hello/3/4/5/True

In [7]: print('hello')
print('world')

hello
world

In [8]: # end
print('you',end="=")
print ('me')

you=me

Data Types

1. Integers
In [9]: print(8)

2. Float (Decimal)
In [10]: print(8.44)
localhost:8888/nbconvert/html/Downloads/Pythoon 100 Days/100_Days_OF_Python/Day 1 - Basics OF Python.ipynb?download=false 1/7
9/20/23, 10:21 AM Day 1 - Basics OF Python

8.44

3. Boolean
In [11]: print(True)
print(False)

True
False

4. String (Text)
In [12]: print('Hello gem')

Hello gem

5. Complex
In [13]: print(5+6j)

(5+6j)

6. List
In Python, a list is a data type used to store a collection of values. It is one of the built-in
data types and is classified as a sequence type. Lists are ordered, mutable (which means you
can change their contents), and can contain elements of different data types, including
integers, floats, strings, or even other lists.

You can create a list in Python by enclosing a comma-separated sequence of values within
square brackets [ ]. For example:

In [ ]: print([1,2,3,4])

7. Tuple
In Python, a tuple is another data type used to store a collection of values, similar to a list.
However, there are some key differences between tuples and lists:

Immutable: The most significant difference is that tuples are immutable, meaning once
you create a tuple, you cannot change its contents (add, remove, or modify elements).
Lists, on the other hand, are mutable, and you can modify them after creation.

Syntax: Tuples are created by enclosing a comma-separated sequence of values within


parentheses (). Lists are created with square brackets []. For example:

Performance: Due to their immutability, tuples can be more efficient in terms of


memory and performance for certain use cases compared to lists.

Tuples are often used when you have a collection of values that should not be changed
during the course of your program. For example, you might use tuples to represent

localhost:8888/nbconvert/html/Downloads/Pythoon 100 Days/100_Days_OF_Python/Day 1 - Basics OF Python.ipynb?download=false 2/7


9/20/23, 10:21 AM Day 1 - Basics OF Python

coordinates (x, y), dates (year, month, day), or other data where the individual components
should remain constant.

In [14]: print((1,2,3,4))

(1, 2, 3, 4)

8. sets
In Python, a set is a built-in data type used to store an unordered collection of unique
elements. Sets are defined by enclosing a comma-separated sequence of values within curly
braces {} or by using the built-in set() constructor. Sets automatically eliminate duplicate
values, ensuring that each element is unique within the set.

In [15]: print({1,2,3,4,5})

{1, 2, 3, 4, 5}

9. Dictionary
In Python, a dictionary is a built-in data type used to store a collection of key-value pairs.
Each key in a dictionary maps to a specific value, creating a relationship between them.
Dictionaries are also known as associative arrays or hash maps in other programming
languages.

In [16]: print({'name':'Nitish','gender':'Male','weight':70})

{'name': 'Nitish', 'gender': 'Male', 'weight': 70}

How to know which type of Datatype is?


In [18]: type([1,2,3,4])

list
Out[18]:

In [19]: type({'age':20})

dict
Out[19]:

3. Variables
In Python, variables are used to store data values. These values can be numbers, strings,
lists, dictionaries, or any other data type. Variables are essential for manipulating and
working with data in your programs. Here's how you declare and use variables in Python:

1. Variable Declaration: You declare a variable by assigning a value to it using the


assignment operator '='.

In [21]: x = 5 # Assigning the integer value 5 to the variable 'x'


name = "Alice" # Assigning a string value to the variable 'name'

localhost:8888/nbconvert/html/Downloads/Pythoon 100 Days/100_Days_OF_Python/Day 1 - Basics OF Python.ipynb?download=false 3/7


9/20/23, 10:21 AM Day 1 - Basics OF Python

1. Variable Names: Variable names (also known as identifiers) must adhere to the
following rules:

They can contain letters (a-z, A-Z), digits (0-9), and underscores (_).
They cannot start with a digit.
Variable names are case-sensitive, so myVar and myvar are treated as different
variables.
Python has reserved keywords (e.g., if, for, while, print) that cannot be used as variable
names.

1. Data Types: Python is dynamically typed, which means you don't need to declare the
data type of a variable explicitly. Python will determine the data type automatically
based on the assigned value.

In [22]: x = 5 # 'x' is an integer variable


name = "Alice" # 'name' is a string variable

1. Reassignment: You can change the value of a variable by assigning it a new value.

In [23]: x = 5
x = x + 1 # Updating the value of 'x' to 6

In [24]: print(x)

Multiple Assignment: Python allows you to assign multiple variables in a single line.

In [26]: a, b, c = 1, 2, 3 # Assigning values 1, 2, and 3 to variables a, b, and c, respect

In [28]: print(a)

In [29]: a = 1
b = 2
c = 3
print(a,b,c)

1 2 3

In [30]: a=b=c= 5
print(a,b,c)

5 5 5

What is comments in Python?


In Python, comments are used to annotate and provide explanations within your code.
Comments are not executed by the Python interpreter; instead, they are meant for human
readers to understand the code better. Comments are ignored by the interpreter during
program execution.

Python supports two types of comments:


localhost:8888/nbconvert/html/Downloads/Pythoon 100 Days/100_Days_OF_Python/Day 1 - Basics OF Python.ipynb?download=false 4/7
9/20/23, 10:21 AM Day 1 - Basics OF Python

1. Single-line Comments: Single-line comments start with the hash symbol ( # ) and
continue until the end of the line. They are used to add comments on a single line.

# This is a single-line comment


x = 5 # Assigning a value to 'x'
Everything after the # symbol on that line is considered a comment.

In [32]: # This is a single-line comment


x = 5 # Assigning a value to 'x'

1. Multi-line or Block Comments: Python does not have a specific syntax for multi-line
comments like some other languages (e.g., C, Java). However, you can create multi-line
comments by using triple-quotes ( ''' or """ ) as a string delimiter. These strings are
not assigned to any variable and are ignored by the interpreter. This is a common
practice for writing docstrings (documentation within functions and modules).

In [34]: '''
This is a multi-line comment.
It can span multiple lines.
'''
def my_function():
"""
This is a docstring.
It provides documentation for the function.
"""
pass

While these triple-quoted strings are not technically comments, they are often used as a
way to document code effectively.

Comments are crucial for making your code more understandable, both for yourself and for
others who may read your code. They help explain the purpose of variables, functions, and
complex algorithms, making it easier to maintain and debug code. Good commenting
practices can significantly improve code readability and maintainability.

4. User Input
How to get Input from the user in python?

In [35]: input('Enter Email')

Enter EmailSagar@95
'Sagar@95'
Out[35]:

In [36]: # take input from users and store them in a variable


fnum = int(input('enter first number'))
snum = int(input('enter second number'))
#print(type(fnum),type(snum))
# add the 2 variables
result = fnum + snum
# print the result

localhost:8888/nbconvert/html/Downloads/Pythoon 100 Days/100_Days_OF_Python/Day 1 - Basics OF Python.ipynb?download=false 5/7


9/20/23, 10:21 AM Day 1 - Basics OF Python

print(result)
print(type(fnum))

enter first number1


enter second number2
3
<class 'int'>

5. Type Conversion
How to covert One Datatypeinto another In python?

int(): Converts a value to an integer data type. This is useful when you want to convert a
string or a floating-point number to an integer.

In [44]: str_number = "123"


int_number = int(str_number) # Converts the string "123" to an integer
int_number

123
Out[44]:

float(): Converts a value to a floating-point data type. It is used to convert integers or


strings containing numeric values to floating-point numbers.

In [45]: int_value = 42
float_value = float(int_value) # Converts the integer 42 to a float
float_value

42.0
Out[45]:

In [37]: a = 23
b = "24"

print(a+b)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_9556\3112067906.py in <module>
2 b = "24"
3
----> 4 print(a+b)

TypeError: unsupported operand type(s) for +: 'int' and 'str'

It Gives error beacause We do not add float into integer datatyupe so we have to convert
above opeartion

In [38]: a = 23
b = "24"

print(float(a)+float(b))

47.0

6. Literals
localhost:8888/nbconvert/html/Downloads/Pythoon 100 Days/100_Days_OF_Python/Day 1 - Basics OF Python.ipynb?download=false 6/7
9/20/23, 10:21 AM Day 1 - Basics OF Python

In Python, literals are used to represent fixed values in your code. These values are not
variables or expressions but rather constants that have a specific value and data type
associated with them. Python supports various types of literals,

In [46]: a = 0b1010 #Binary Literals


b = 100 #Decimal Literal
c = 0o310 #Octal Literal
d = 0x12c #Hexadecimal Literal

#Float Literal
float_1 = 10.5
float_2 = 1.5e2 # 1.5 * 10^2
float_3 = 1.5e-3 # 1.5 * 10^-3

#Complex Literal
x = 3.14j

print(a, b, c, d)
print(float_1, float_2,float_3)
print(x, x.imag, x.real)

10 100 200 300


10.5 150.0 0.0015
3.14j 3.14 0.0

In [48]: # binary
x = 3.14j
print(x.imag)

3.14

In [49]: string = 'This is Python'


strings = "This is Python"
char = "C"
multiline_str = """This is a multiline string with more than one line code."""
unicode = u"\U0001f600\U0001F606\U0001F923"
raw_str = r"raw \n string"

print(string)
print(strings)
print(char)
print(multiline_str)
print(unicode)
print(raw_str)

This is Python
This is Python
C
This is a multiline string with more than one line code.
😀😆🤣
raw \n string

localhost:8888/nbconvert/html/Downloads/Pythoon 100 Days/100_Days_OF_Python/Day 1 - Basics OF Python.ipynb?download=false 7/7


9/21/23, 11:03 AM Day2 - Operators_in_Python

Operators In Python

1.Arithmetic Operators:
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Floor Division (//)
Modulus (%)
Exponentiation (**)

In [2]: print(5+6) # Addtion -> adding the numbers

print(5-6) # subtraction-> subtract the number

print(5*6) # Multiplication -> Multiply the number

print(5/2) # Divsion -> Divide the numnber

print(5//2) # Floor Division -> It trasform into integer number= 2.5 convert into 2

print(5%2) # Modulus -> It Provides remainder of the Divsion

print(5**2) # Exponential -> raising a number to a certain power.(raised to power)

11
-1
30
2.5
2
1
25

2. Comparison Operators/ Relational Opeartors:


Equal to (==)
Not equal to (!=)
Less than (<)
Greater than (>)
Less than or equal to (<=)
Greater than or equal to (>=)

In [5]: print(4==4)

print(4!=4)

print(4<5)

print(4>5)

print(4<=4)

localhost:8888/nbconvert/html/Downloads/Pythoon 100 Days/100_Days_OF_Python/Day2 - Operators_in_Python.ipynb?download=false 1/3


9/21/23, 11:03 AM Day2 - Operators_in_Python

print(4>=4)

True
False
True
False
True
True

2. Logical Operators:
Logical AND (and)
Logical OR (or)
Logical NOT (not)

In [7]: p = True
q = False

print(p and q) # true and false -> 1 and 0 = 0


print(p or q) # true or false -> 1 or 0 = 1
print(not p)

False
True
False

3. Assignment Operators:
Assignment (=)
Add and Assign (+=)
Subtract and Assign (-=)
Multiply and Assign (*=)
Divide and Assign (/=)
Floor Divide and Assign (//=)
Modulus and Assign (%=)
Exponentiate and Assign (**=)

In [12]: x = 10
x += 5
print(x) # Equivalent to x = x + 5

15

In [16]: x = 10
x -= 3 # Equivalent to x = x - 3
x *= 2 # Equivalent to x = x * 2
x /= 4 # Equivalent to x = x / 4
x //= 2 # Equivalent to x = x // 2
x %= 3 # Equivalent to x = x % 3
x **= 2 # Equivalent to x = x ** 2

4.Bitwise Operators:
Bitwise AND (&)

localhost:8888/nbconvert/html/Downloads/Pythoon 100 Days/100_Days_OF_Python/Day2 - Operators_in_Python.ipynb?download=false 2/3


9/21/23, 11:03 AM Day2 - Operators_in_Python

Bitwise OR (|)
Bitwise XOR (^)
Bitwise NOT (~)
Left Shift (<<)
Right Shift (>>)

In [23]: m = 5 # 101 in binary


n = 3 # 011 in binary
bitwise_and = m & n # 001 (1 in decimal)
print(bitwise_and)

bitwise_or = m | n # 111 (7 in decimal)


print(bitwise_or)

bitwise_xor = m ^ n # 110 (6 in decimal)


print(bitwise_xor)

bitwise_not_m = ~m # -6 (in decimal)


print(bitwise_not_m)

left_shift = m << 1 # 010 (2 in decimal)


print(left_shift)

right_shift = m >> 1 # 010 (2 in decimal)


print(right_shift)

1
7
6
-6
10
2

These are the basic operators in Python. You can use them to perform various operations on
variables and values in your Python programs.

localhost:8888/nbconvert/html/Downloads/Pythoon 100 Days/100_Days_OF_Python/Day2 - Operators_in_Python.ipynb?download=false 3/3


9/24/23, 10:21 AM Day5 - Strings in Python

Strings In Python (part-1)


In Python, a string is a sequence of characters enclosed within either single (' '), double (" "),
or triple (''' ' ''', """ """ or ''' '''') quotes. Strings are used to represent text data and are one of
the fundamental data types in Python

Strings are sequence of Characters

In Python specifically, strings are a sequence of Unicode Characters

Immutable: Strings in Python are immutable, meaning once you create a string, you
cannot change its content. You can create new strings based on the original string, but
the original string remains unchanged.

1. Creating Strings
In [ ]: # create string with the help of single quotes
s = 'Hello World'
print(s)

Hello World

In [ ]: # create string with the help of Double quotes


s = "Hello World"
print(s)

Hello World

when we use single and double quotes?

-> In Python, you can create strings using both single quotes (') and double quotes ("), and
they are functionally equivalent. The choice between using single or double quotes mainly
depends on your personal preference or specific coding style guidelines.

If your string contains a quotation mark character (either a single quote or double quote),
you can use the other type of quote to define the string without escaping the inner quotes.
This can make your code more readable:

In [ ]: single_quoted_string = 'He said, "Hello!"'


double_quoted_string = "He said, 'Hello!'"
# here we use single and double quotes
print(single_quoted_string)
print(double_quoted_string)

He said, "Hello!"
He said, 'Hello!'

In [ ]: # multiline strings
s = '''hello'''
s = """hello"""
s = str('hello')
print(s)

file:///C:/Users/disha/Downloads/Day5 - Strings in Python.html 1/3


9/24/23, 10:21 AM Day5 - Strings in Python

hello

2. Accessing Substrings from a String

Indexing
Indexing in Python refers to the process of accessing individual elements or characters
within a sequence, such as a string. Strings in Python are sequences of characters, and you
can access specific characters in a string using indexing. Indexing is done using square
brackets [ ], and Python uses a zero-based indexing system, meaning the first element has
an index of 0, the second element has an index of 1, and so on.

we have two types of Indexing:

1. Positive indexing
2. Negative Indexing

In [ ]: s = "Hello World"

# Accessing individual characters using positive indexing


print(s[0]) # Accesses the first character, 'H'
print(s[1]) # Accesses the second character, 'e'

H
e

In [ ]: # Accessing individual characters using negative indexing (counting from the end)
print(s[-1]) # Accesses the last character, 'd'
print(s[-2]) # Accesses the second-to-last character, 'l'

d
l

Slicing
In Python, slicing is a technique used to extract a portion of a string, list, or any other
sequence-like data structure. When it comes to strings, slicing allows you to create a new
string by specifying a range of indices to extract a substring from the original string.

In [ ]: # string[start:end]

string: The original string you want to slice.


start: The index from which the slicing begins (inclusive).
end: The index at which the slicing ends (exclusive).

In [ ]: s = 'hello world'
print(s[1:5]) # from 1 index that is e to 4 index=o
print(s[:6]) # from 0 to 5
print(s[1:]) # from 1 to all
print(s[:]) # all string
print(s[-5:-1]) # with negative slicing

file:///C:/Users/disha/Downloads/Day5 - Strings in Python.html 2/3


9/24/23, 10:21 AM Day5 - Strings in Python

ello
hello
ello world
hello world
worl

In [ ]: # we use step function in slicing


s = 'hello world'
print(s[6:0:-2])
print(s[::-1])

wol
dlrow olleh

In [ ]: s = 'hello world'
print(s[-1:-6:-1])

dlrow

3. Editing and Deleting in Strings


In [ ]: s = 'hello world'
s[0] = 'H'
# it throws error
# Python strings are immutable

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_4564\2237226474.py in <module>
1 s = 'hello world'
----> 2 s[0] = 'H'
3
4 # Python strings are immutable

TypeError: 'str' object does not support item assignment

Immutable: Strings in Python are immutable, meaning once you create a string, you cannot
change its content. You can create new strings based on the original string, but the original
string remains unchanged.

file:///C:/Users/disha/Downloads/Day5 - Strings in Python.html 3/3


9/25/23, 10:26 AM Day6 - Strings in Python part 2

Strings In Python (part-2)

operations on strings
In Python, strings are sequences of characters and are very versatile. You can perform a wide
range of operations on strings, including but not limited to:

1. Concatenation
You can concatenate (combine) two or more strings using the '+' operator:

In [ ]: # Arithmatic opertion in string


a = 'Hello'
b = 'world'
print(a + b)

# if we want space
print(a + " " + b)

Helloworld
Hello world

In [ ]: # how to print delhi 14 times


print("delhi"*14)

delhidelhidelhidelhidelhidelhidelhidelhidelhidelhidelhidelhidelhidelhi

In [ ]: print("*"*50)

**************************************************

2. Indexing and Slicing


You can access individual characters of a string using indexing, and you can extract
substrings using slicing

In [ ]: s = "Hello world"

In [ ]: s[3] # it slice one word from the string

'l'
Out[ ]:

In [ ]: s[4:9]

'o wor'
Out[ ]:

3. String Methods
Python provides many built-in string methods for common operations like converting to
uppercase, lowercase, finding substrings, replacing, and more

Upper
file:///C:/Users/disha/Downloads/Day6 - Strings in Python part 2.html 1/3
9/25/23, 10:26 AM Day6 - Strings in Python part 2

In [ ]: text = "Hello, World!"


uppercase_text = text.upper() # Convert to uppercase
print(uppercase_text)

HELLO, WORLD!

Lower

In [ ]: lowercase_text = text.lower() # Convert to lowercase


print(lowercase_text)

hello, world!

find

In [ ]: index = text.find("World") # Find the index of a substring


print(index)

replace

In [ ]: new_text = text.replace("Hello", "Hi") # Replace a substring


print(new_text)

Hi, World!

4. String Formatting
You can format strings using f-strings or the str.format() method

In [ ]: name = 'nitish'
gender = 'male'

'Hi my name is {} and I am a {}'.format(name,gender)

'Hi my name is nitish and I am a male'


Out[ ]:

3. String Splitting and Joining


You can split a string into a list of substrings using the split() method and join a list of strings
into one string using the join() method

In [ ]: 'hi my name is KHAN '.split()

['hi', 'my', 'name', 'is', 'KHAN']


Out[ ]:

In [ ]: " ".join(['hi', 'my', 'name', 'is', 'KHAN'])

'hi my name is KHAN'


Out[ ]:

4. String Length
You can find the length of a string using the len() function

file:///C:/Users/disha/Downloads/Day6 - Strings in Python part 2.html 2/3


9/25/23, 10:26 AM Day6 - Strings in Python part 2

In [ ]: text = "Hello, World!"


length = len(text) # Returns the length of the string (13 in this case)
print(length)

13

5. Strip
In [ ]: 'hey '.strip() # it drop the Unwanted space prenet

'hey'
Out[ ]:

In [ ]:

file:///C:/Users/disha/Downloads/Day6 - Strings in Python part 2.html 3/3


9/26/23, 12:29 PM Day7- Problems on Strings

Problems on Strings
1 . Find the length of a given string without using the len() function

In [ ]: s = input('enetr the string')

counter = 0

for i in s:
counter += 1

print(s)
print('lenght of string is',counter)

Dishant
lenght of string is 7

2. Extract username from a given email.

Eg if the email is xyz76@gmail.com


then the username should be xyz76

In [ ]: s = input('enter the mail')

pos = s.index('@')

print(s)
print(s[0:pos])

xyz123@gmail.com
xyz123

3. Count the frequency of a particular character in a provided string.

Eg 'hello how are you' is the string, the frequency of h in this string is 2.

In [ ]: s = input('enter the email')


term = input('what would like to search for')

counter = 0
for i in s:
if i == term:
counter += 1

print('frequency',counter)

frequency 1

4. Write a program which can remove a particular character from a string.

In [ ]: s = input('enter the string')


term = input('what would like to remove')

file:///C:/Users/disha/Downloads/Day7- Problems on Strings.html 1/3


9/26/23, 12:29 PM Day7- Problems on Strings

result = ''

for i in s:
if i != term:
result = result + i

print(result)

hi how are you

5. Write a program that can check whether a given string is palindrome or not.

abba
malayalam

In [ ]: s = input('enter the string')


print(s)
flag = True
for i in range(0,len(s)//2):
if s[i] != s[len(s) - i -1]:
flag = False
print('Not a Palindrome')
break

if flag:
print('Palindrome')

abba
Palindrome

6. Write a program to count the number of words in a string without split()

In [ ]: s = input('enter the string')


print(s)
L = []
temp = ''
for i in s:

if i != ' ':
temp = temp + i
else:
L.append(temp)
temp = ''

L.append(temp)
print(L)

hi how are you


['hi', 'how', 'are', 'you']

7. Write a python program to convert a string to title case without using the title()

In [ ]: s = input('enter the string')


print(s)

L = []
for i in s.split():

file:///C:/Users/disha/Downloads/Day7- Problems on Strings.html 2/3


9/26/23, 12:29 PM Day7- Problems on Strings

L.append(i[0].upper() + i[1:].lower())

print(" ".join(L))

how can i help you


How Can I Help You

8. Write a program that can convert an integer to string.

In [ ]: number = int(input('enter the number'))


print(number)

digits = '0123456789'
result = ''
while number != 0:
result = digits[number % 10] + result
number = number//10

print(result)
print(type(result))

143243
143243
<class 'str'>

In [ ]:

file:///C:/Users/disha/Downloads/Day7- Problems on Strings.html 3/3


9/27/23, 11:09 AM Day8- Interview Question based on Basic-Oprators-If-else-and-Strings-in-Python

Interview Question Based on Basics-


Operators-If-else-loops-and-Strings-In-
PYTHON
1. What is Python? What are the benefits of using Python?
Python is a high-level, interpreted, general-purpose programming language. Being a
general-purpose language, it can be used to build almost any type of application with
the right tools/libraries. Additionally, python supports objects, modules, threads,
exception-handling, and automatic memory management which help in modelling real-
world problems and building applications to solve these problems.

Benefits of using Python:

Python is a general-purpose programming language that has a simple, easy-to-learn


syntax that emphasizes readability and therefore reduces the cost of program
maintenance. Moreover, the language is capable of scripting, is completely open-
source, and supports third-party packages encouraging modularity and code reuse.
Its high-level data structures, combined with dynamic typing and dynamic binding,
attract a huge community of developers for Rapid Application Development and
deployment.

2. What is Python, and why is it often called a "high-level"


programming language?
Python is a high-level programming language known for its simplicity and readability. It
is called "high-level" because it abstracts low-level details and provides a more human-
readable syntax, making it easier to write and understand code.

3. What is an Interpreted language?


An Interpreted language executes its statements line by line. Languages such as Python,
Javascript, R, PHP, and Ruby are prime examples of Interpreted languages. Programs
written in an interpreted language runs directly from the source code, with no
intermediary compilation step.

4. What is PEP 8 and why is it important?


PEP stands for Python Enhancement Proposal. A PEP is an official design document
providing information to the Python community, or describing a new feature for Python
or its processes. PEP 8 is especially important since it documents the style guidelines for
Python Code. Apparently contributing to the Python open-source community requires
you to follow these style guidelines sincerely and strictly.

file:///C:/Users/disha/Downloads/Pythoon 100 Days/100_Days_OF_Python/Day8- Interview Question based on Basic-Oprators-If-else-and-String… 1/4


9/28/23, 10:51 AM Day9 - List in python

List in Python (Part-1)

What are Lists?


List is a data type where you can store multiple items under 1 name. More technically, lists
act like dynamic arrays which means you can add more items on the fly.

Alt text

Characterstics of a List:
Ordered
Changeble/Mutable
Hetrogeneous
Can have duplicates
are dynamic
can be nested
items can be accessed
can contain any kind of objects in python

Creating a List
In [ ]: # Empty
print([])

# 1D -> Homo
print([1,2,3,4,5])

# 2D
print([1,2,3,[4,5]])

# 3D
print([[[1,2],[3,4]]])

# Heterogenous
print([1,True,5.6,5+6j,'Hello'])

# Using Type conversion


print(list('hello'))

[]
[1, 2, 3, 4, 5]
[1, 2, 3, [4, 5]]
[[[1, 2], [3, 4]]]
[1, True, 5.6, (5+6j), 'Hello']
['h', 'e', 'l', 'l', 'o']

Accessing Items from a List

file:///C:/Users/disha/Downloads/Day9 - List in python.html 1/4


9/28/23, 10:51 AM Day9 - List in python

Indexing
Slicing

In [ ]: # indexing
L = [[[1,2],[3,4]],[[5,6],[7,8]]]
L1 = [1,2,3,4]

# Positive Indexing
print(L1[1:4])

print(L[0][0][1]) # for 2

#How to extract 6
print(L[1][0][1])

[2, 3, 4]
[]
2
6

In [ ]: # Negative indexing
L = [[[1,2],[3,4]],[[5,6],[7,8]]]
L1 = [1,2,3,4]

print(L[-1])

# how to extract 8 with negative


print(L[-1][-1][-1])

[[5, 6], [7, 8]]


8

In [ ]: # Slicing
L = [1,2,3,4,5,6]

print(L[::-1])

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

Adding Items to a List


In [ ]: # Apend -> The append method is used to add an item to the end of a list.
L = [1,2,3,4,5]
L.append(True)
print(L)

[1, 2, 3, 4, 5, True]

In [ ]: # Extend -> The extend method is used to append elements from an iterable (e.g., an
L = [1,2,3,4,5]
L.extend([2])
L

[1, 2, 3, 4, 5, 2]
Out[ ]:

In [ ]: # insert -> The insert method allows you to add an item at a specific position in t
l = [1,2,3,4]

l.insert(1,100)
print(l)

file:///C:/Users/disha/Downloads/Day9 - List in python.html 2/4


9/28/23, 10:51 AM Day9 - List in python
[1, 100, 2, 3, 4]

Editing items in a List


In [ ]: l = [1,2,3,4,5,6]

# editing with indexing


l[-1] = 300
print(l)

# editong with slicing


l[1:4] = [200,300,400]
print(l)

[1, 2, 3, 4, 5, 300]
[1, 200, 300, 400, 5, 300]

Deleting items from a List


In [ ]: # del -> The del statement is used to remove an item from a list based on its index
l = [1,2,3,4,5]

#indexing
del l[2]
print(l)

# slicing
del l[2:4]
print(l)

[1, 2, 4, 5]
[1, 2]

In [ ]: # remove -> The remove method is used to remove the first occurrence of a specific
l = [1,2,3]

l.remove(2)

print(l)

[1, 3]

In [ ]: # pop -> The pop method is used to remove and return an item from the list based on
# If you don't provide an index, it will remove and return the last item by default
L = [1,2,3,4,5]

L.pop()

print(L)

[1, 2, 3, 4]

In [ ]: # clear -> The clear method is used to remove all items from the list, effectively
L = [1,2,3,4,5]

L.clear()

print(L)

[]

In [ ]:

file:///C:/Users/disha/Downloads/Day9 - List in python.html 3/4


9/28/23, 10:51 AM Day9 - List in python

In [ ]:

In [ ]:

file:///C:/Users/disha/Downloads/Day9 - List in python.html 4/4


9/29/23, 9:51 AM Day10 - List in python(part-2)

List in Python (Part-2)

Operations on Lists:
There are three types of Opeartion in List:

1. Arithmatic
2. Membership
3. Loop

In [ ]: # Arithmatic opeartion (+, *)

L1 = [1,2,3,4,5]
L2 = [9,8,7,6,5]

# concatenation/Merge
print(L1 + L2)

print(L1*3)
print(L2*4)

[1, 2, 3, 4, 5, 9, 8, 7, 6, 5]
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
[9, 8, 7, 6, 5, 9, 8, 7, 6, 5, 9, 8, 7, 6, 5, 9, 8, 7, 6, 5]

In [ ]: # membership
L1 = [1,2,3,4,5]
L2 = [1,2,3,4,[5,6]]

print(5 not in L1)


print([5,6] in L2)

False
True

In [ ]: # loops
L1 = [1,2,3,4,5]
L2 = [1,2,3,4,[5,6]]
L3 = [[[1,2],[3,4]],[[5,6],[7,8]]]

for i in L2:
print(i)

1
2
3
4
[5, 6]

List Functions
In [ ]: # len/min/max/sorted
L = [2,1,5,7,0]

print(len(L))

file:///C:/Users/disha/Downloads/Day10 - List in python(part-2).html 1/4


9/29/23, 9:51 AM Day10 - List in python(part-2)
print(max(L))
print(min(L))
print(sorted(L))

5
7
0
[0, 1, 2, 5, 7]

In [ ]: # count
l = [1,2,3,456,67867]

l.count(456)

1
Out[ ]:

In [ ]: # index
l = [3,5,7,9,3,23]

l.index(5)

1
Out[ ]:

In [ ]: # reverse
l = [1,2,3,4,6,78]

l.reverse()
print(l)

[78, 6, 4, 3, 2, 1]

In [ ]: # sort vs sorted
L = [2,1,5,7,0]
print(L)

print(sorted(L))

print(L)

L.sort()

print(L)

[2, 1, 5, 7, 0]
[0, 1, 2, 5, 7]
[2, 1, 5, 7, 0]
[0, 1, 2, 5, 7]

If you want to sort a list in-place, you should use the sort method. If you want to create a
new sorted list without modifying the original list, you should use the sorted function

List Comprehension
List Comprehension provides a concise way of creating lists.

newlist = [expression for item in iterable if condition == True]


Advantages of List Comprehension

More time-efficient and space-efficient than loops.

file:///C:/Users/disha/Downloads/Day10 - List in python(part-2).html 2/4


9/29/23, 9:51 AM Day10 - List in python(part-2)

Require fewer lines of code.


Transforms iterative statement into a formula.

In [ ]: # Add 1 to 10 numbers to the list

# if we use for loop


L=[]
for i in range(1,11):
L.append(i)

print(L)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In [ ]: # By List Comprehension
L = [i for i in range(1,11)]
print(L)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In [ ]: # Scaler multiplication on vecrtor


c = [2,3,4]
v = -3

L = [v*i for i in c]
print(L)

[-6, -9, -12]

In [ ]: # Add sqaures
L = [2,3,4,5,6]

[i**2 for i in L]

[4, 9, 16, 25, 36]


Out[ ]:

In [ ]: # Print all numbers divisible by 5 in the range of 1 to 50

[i for i in range(1,51) if i%5 == 0]

[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
Out[ ]:

Disadvantages of Python Lists


Slow
Risky usage
eats up more memory

In [ ]: a = [1,2,3]
b = a.copy()

print(a)
print(b)

a.append(4)
print(a)
print(b)

# lists are mutable

file:///C:/Users/disha/Downloads/Day10 - List in python(part-2).html 3/4


9/29/23, 9:51 AM Day10 - List in python(part-2)
[1, 2, 3]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3]

In [ ]:

file:///C:/Users/disha/Downloads/Day10 - List in python(part-2).html 4/4


9/30/23, 12:32 AM Day11 - Tuples In Python

Tuples In Python
A tuple in Python is an immutable, ordered collection of elements. It is similar to a list in that
it can store a variety of data types, including numbers, strings, and other objects, but unlike
lists, tuples cannot be modified once they are created.

This immutability means that you can't add, remove, or change elements within a tuple after
it's been defined.

Characterstics

Ordered
Unchangeble
Allows duplicate

Creating Tuples
In [ ]: # How to create empty tuple
t1 =()
print(t1)

# creating tuple with single item


t2 = ('hello',)
print(t2)
print(type(t2))

# homo
t3 = (1,2,3,4,5)
print(t3)

# hetero
t4 = (1,2.5,True,[1,2,3])
print(t4)

# tuple
t5 = (1,2,3,(4,5))
print(t5)

# using type conversion


t6 = tuple('hello')
print(t6)

()
('hello',)
<class 'tuple'>
(1, 2, 3, 4, 5)
(1, 2.5, True, [1, 2, 3])
(1, 2, 3, (4, 5))
('h', 'e', 'l', 'l', 'o')

Accessing items in Tuples


Indexing
Slicing
file:///C:/Users/disha/Downloads/Day11 - Tuples In Python.html 1/5
9/30/23, 12:32 AM Day11 - Tuples In Python

In [ ]: print(t3)

(1, 2, 3, 4, 5)

In [ ]: # extract 4 from the tuple


print(t3[3])

# extract 3,4,5
print(t3[2:])

4
(3, 4, 5)

In [ ]: print(t5)
t5[-1][0]

(1, 2, 3, (4, 5))


4
Out[ ]:

Editing items in tuple/Deleting in tuple


Tuple are immutable like string it cannot change or Delete

In [ ]: print(t5)
del t5[-1]

(1, 2, 3, (4, 5))


---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
c:\Users\disha\Downloads\Pythoon 100 Days\100_Days_OF_Python\Day11 - Tuples In Pyt
hon.ipynb Cell 10 line 2
<a href='vscode-notebook-cell:/c%3A/Users/disha/Downloads/Pythoon%20100%20Da
ys/100_Days_OF_Python/Day11%20-%20Tuples%20In%20Python.ipynb#X22sZmlsZQ%3D%3D?line
=0'>1</a> print(t5)
----> <a href='vscode-notebook-cell:/c%3A/Users/disha/Downloads/Pythoon%20100%20Da
ys/100_Days_OF_Python/Day11%20-%20Tuples%20In%20Python.ipynb#X22sZmlsZQ%3D%3D?line
=1'>2</a> del t5[-1]

TypeError: 'tuple' object doesn't support item deletion

Operation on Tuples
In [ ]: # + and *
t1 = (1,2,3,4)
t2 = (5,6,7,8)

print(t1 + t2)

# membership
print(1 in t1)

# iteration/loops
for i in t3:
print(i)

file:///C:/Users/disha/Downloads/Day11 - Tuples In Python.html 2/5


9/30/23, 12:32 AM Day11 - Tuples In Python
(1, 2, 3, 4, 5, 6, 7, 8)
True
1
2
3
4
5

Tuple Functions
In [ ]: # len/sum/min/max/sorted
t = (1,2,3,4,5)

print(len(t))

print(sum(t))

print(min(t))

print(max(t))

print(sorted(t))

5
15
1
5
[1, 2, 3, 4, 5]

In [ ]: # count
t = (1,2,3,4,5)

t.count(3)

1
Out[ ]:

In [ ]: # index
t = (4,64567,3454,11,33,55)

t.index(64567)

1
Out[ ]:

Special Syntax
In [ ]: # tuple unpacking
a,b,c = (1,2,3)
print(a,b,c)

1 2 3

In [ ]: a = 1
b = 2
a,b = b,a

print(a,b)

2 1

In [ ]: a,b,*others = (1,2,3,4)
print(a,b)
file:///C:/Users/disha/Downloads/Day11 - Tuples In Python.html 3/5
9/30/23, 12:32 AM Day11 - Tuples In Python
print(others)

1 2
[3, 4]

In [ ]: # zipping tuples
a = (1,2,3,4)
b = (5,6,7,8)

tuple(zip(a,b))

((1, 5), (2, 6), (3, 7), (4, 8))


Out[ ]:

Difference between Lists and Tuples


Lists and tuples are both data structures in Python, but they have several differences in
terms of syntax, mutability, speed, memory usage, built-in functionality, error-proneness,
and usability. Let's compare them in these aspects:

1. Syntax:

Lists are defined using square brackets [ ] , e.g., my_list = [1, 2, 3] .


Tuples are defined using parentheses ( ) , e.g., my_tuple = (1, 2, 3) .
2. Mutability:

Lists are mutable, which means you can change their elements after creation using
methods like append() , insert() , or direct assignment.
Tuples are immutable, which means once created, you cannot change their
elements. You would need to create a new tuple if you want to modify its contents.
3. Speed:

Lists are slightly slower than tuples in terms of performance because they are
mutable. Modifying a list may involve resizing or copying elements, which can
introduce overhead.
Tuples, being immutable, are generally faster for accessing elements because they
are more memory-efficient and do not require resizing or copying.
4. Memory:

Lists consume more memory than tuples due to their mutability. Lists require extra
memory to accommodate potential resizing and other internal bookkeeping.
Tuples are more memory-efficient since they don't have the overhead associated
with mutable data structures.
5. Built-in Functionality:

Both lists and tuples have common operations like indexing, slicing, and iteration.
Lists offer more built-in methods for manipulation, such as append() ,
insert() , remove() , and extend() . Lists are better suited for situations
where you need to add or remove elements frequently.
Tuples have a more limited set of operations due to their immutability but offer
security against accidental modifications.
6. Error-Prone:

file:///C:/Users/disha/Downloads/Day11 - Tuples In Python.html 4/5


9/30/23, 12:32 AM Day11 - Tuples In Python

Lists are more error-prone when it comes to accidental modification, especially in


large codebases, as they can be changed throughout the code.
Tuples are less error-prone since they cannot be modified once created, making
them more predictable.
7. Usability:

Lists are typically used when you need a collection of items that can change over
time. They are suitable for situations where you want to add, remove, or modify
elements.
Tuples are used when you want to create a collection of items that should not
change during the program's execution. They provide safety and immutability.

In summary, the choice between lists and tuples depends on your specific needs. Use lists
when you require mutability and dynamic resizing, and use tuples when you want to ensure
immutability and need a more memory-efficient, error-resistant data structure.

file:///C:/Users/disha/Downloads/Day11 - Tuples In Python.html 5/5


10/2/23, 10:38 AM Day13 - Dictionary in Python

Dictionary In Python
Dictionary in Python is a collection of keys values, used to store data values like a map,
which, unlike other data types which hold only a single value as an element.

In some languages it is known as map or assosiative arrays.

dict = { 'name' : 'xyz' , 'age' : 24 , 'gender' : 'male' }

Characterstics:

Mutable
Indexing has no meaning
keys can't be duplicated
keys can't be mutable items

Create Dictionary
In [ ]: # empty
d = {}
print(d)

#1D
d1 = {'name':'xyz', 'Age':23, 'gender':'male'}
print(d1)

# with mixed keys


d2 = {(2,2,3):1,'hello':'world'}
print(d2)

# 2D dictionary
s = {
'name':'ramesh',
'college':'bit',
'sem':4,
'subjects':{
'dsa':50,
'maths':67,
'english':34
}
}
print(s)

# using sequence and dict function


d4 = dict([('name','xyz'),('age',23),(3,3)])
print(d4)

#mutable items keys


d6 = {'name':'xyz', (1,2,3):2}
print(d6)

file:///C:/Users/disha/Downloads/Day13 - Dictionary in Python.html 1/4


10/2/23, 10:38 AM Day13 - Dictionary in Python
{}
{'name': 'xyz', 'Age': 23, 'gender': 'male'}
{(2, 2, 3): 1, 'hello': 'world'}
{'name': 'ramesh', 'college': 'bit', 'sem': 4, 'subjects': {'dsa': 50, 'maths': 6
7, 'english': 34}}
{'name': 'xyz', 'age': 23, 3: 3}
{'name': 'xyz', (1, 2, 3): 2}

Accessing Items
In [ ]: my_dict = {'name': 'Jack', 'age': 26}
my_dict['name'] # you have to write keys

'Jack'
Out[ ]:

Adding key pair


In [ ]: print(d4)

{'name': 'xyz', 'age': 23, 3: 3}

In [ ]: d4['gender'] = 'male'
print(d4)

d4['weight'] = 70
print(d4)

{'name': 'xyz', 'age': 23, 3: 3, 'gender': 'male'}


{'name': 'xyz', 'age': 23, 3: 3, 'gender': 'male', 'weight': 70}

Remove key-value pair


In [ ]: d = {'name': 'xyz', 'age': 24, 3: 3, 'gender': 'male', 'weight': 72}

# pop
d.pop(3) # it remove three
print(d)

#popitems
d.popitem() # it remove last item in the dictionary
print(d)

# del
del d['name']
print(d)

#clear
d.clear() # it clear dictionary
print(d)

{'name': 'xyz', 'age': 24, 'gender': 'male', 'weight': 72}


{'name': 'xyz', 'age': 24, 'gender': 'male'}
{'age': 24, 'gender': 'male'}
{}

Editing key-value pair


In [ ]: print(s)

file:///C:/Users/disha/Downloads/Day13 - Dictionary in Python.html 2/4


10/2/23, 10:38 AM Day13 - Dictionary in Python
{'name': 'ramesh', 'college': 'bit', 'sem': 4, 'subjects': {'dsa': 50, 'maths': 6
7, 'english': 34}}

In [ ]: s['subjects']['dsa'] = 80
s

{'name': 'ramesh',
Out[ ]:
'college': 'bit',
'sem': 4,
'subjects': {'dsa': 80, 'maths': 67, 'english': 34}}

Dictionary Operations
Membership
Iteration

In [ ]: print(s)

{'name': 'ramesh', 'college': 'bit', 'sem': 4, 'subjects': {'dsa': 80, 'maths': 6


7, 'english': 34}}

In [ ]: # membership
'name' in s

True
Out[ ]:

In [ ]: 'ramesh' in s # it use on it keys not on values

False
Out[ ]:

In [ ]: # ITERATION
for i in s:
print(i,s[i])

name ramesh
college bit
sem 4
subjects {'dsa': 80, 'maths': 67, 'english': 34}

Dictionary Functions
In [ ]: print(s)

{'name': 'ramesh', 'college': 'bit', 'sem': 4, 'subjects': {'dsa': 80, 'maths': 6


7, 'english': 34}}

In [ ]: # len/sorted
print(len(s))

sorted(s)

4
['college', 'name', 'sem', 'subjects']
Out[ ]:

In [ ]: # items/keys/values

print(s.items())

print(s.keys())

file:///C:/Users/disha/Downloads/Day13 - Dictionary in Python.html 3/4


10/2/23, 10:38 AM Day13 - Dictionary in Python

print(s.values())

dict_items([('name', 'ramesh'), ('college', 'bit'), ('sem', 4), ('subjects', {'ds


a': 80, 'maths': 67, 'english': 34})])
dict_keys(['name', 'college', 'sem', 'subjects'])
dict_values(['ramesh', 'bit', 4, {'dsa': 80, 'maths': 67, 'english': 34}])

In [ ]: # update
d1 = {1:2,3:4,4:5}
d2 = {4:7,6:8}

d1.update(d2)
print(d1)

{1: 2, 3: 4, 4: 7, 6: 8}

Dictionary Comprehension
In [ ]: # print 1st 10 numbers and their squares
{i:i**2 for i in range(1,11)}

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}


Out[ ]:

In [ ]: distances = {'delhi':1000,'mumbai':2000,'bangalore':3000}
print(distances.items())

dict_items([('delhi', 1000), ('mumbai', 2000), ('bangalore', 3000)])

In [ ]: # using zip
days = ["Sunday", "Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
temp_C = [30.5,32.6,31.8,33.4,29.8,30.2,29.9]

{i:j for (i,j) in zip(days,temp_C)}

{'Sunday': 30.5,
Out[ ]:
'Monday': 32.6,
'Tuesday': 31.8,
'Wednesday': 33.4,
'Thursday': 29.8,
'Friday': 30.2,
'Saturday': 29.9}

In [ ]: # using if condition
products = {'phone':10,'laptop':0,'charger':32,'tablet':0}

{key:value for (key,value) in products.items() if value>0}

{'phone': 10, 'charger': 32}


Out[ ]:

In [ ]: # Nested Comprehension
# print tables of number from 2 to 4
{i:{j:i*j for j in range(1,11)} for i in range(2,5)}

{2: {1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18, 10: 20},


Out[ ]:
3: {1: 3, 2: 6, 3: 9, 4: 12, 5: 15, 6: 18, 7: 21, 8: 24, 9: 27, 10: 30},
4: {1: 4, 2: 8, 3: 12, 4: 16, 5: 20, 6: 24, 7: 28, 8: 32, 9: 36, 10: 40}}

file:///C:/Users/disha/Downloads/Day13 - Dictionary in Python.html 4/4

You might also like