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

Python Self Notes

Self notes for python initial

Uploaded by

prernadjschool
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)
7 views

Python Self Notes

Self notes for python initial

Uploaded by

prernadjschool
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/ 12

PYTHON - August - 2024 BATCH (MGM)

Python offers a variety of built-in data structures and data types to organize and manipulate
data efficiently. Here's a breakdown of the most common ones with examples:
Data Structures &
Data Types: Data Types
Integers (int): Represents whole numbers, positive or negative, without decimals.

x = 10

Floating-point numbers (float): Represents numbers with decimals.

y = 3.14

Strings (str): Represents a sequence of characters.

name = "Alice"

Booleans (bool): Represents logical values True or False.

is_valid = True

Data Structures:

Lists: Ordered, mutable collection of elements.

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


fruits.append("grape") # Add element
print(fruits[0]) # Access element

Tuples: Ordered, immutable collection of elements.

coordinates = (10, 20)


print(coordinates[1]) # Access element

Sets: Unordered collection of unique elements.

numbers = {1, 2, 3, 2} # Duplicates removed


numbers.add(4) # Add element
print(numbers)

Dictionaries: Unordered collection of key-value pairs.

person = {"name": "Bob", "age": 30}


person["city"] = "New York" # Add key-value pair
print(person["name"]) # Access value

Other Data Structures:

Arrays (using NumPy): Efficient for numerical computations.

Linked lists: Linear data structure where elements are linked together.

Stacks and Queues: Implement specific data access patterns (LIFO and FIFO, respectively).

Trees and Graphs: Represent hierarchical and network relationships.

Choosing the right data structure and type is crucial for efficient programming. It depends on
the specific requirements of your application.
PYTHON - August - 2024 BATCH (MGM)

Single String : print("Hello world2!")

Multiple String : print("Hello,", "John!", "How are you?")

Numeric String : print(1, "plus", 2, "equals", 1+2)

User Input String : name=

input("Give me your name: ")

print("Hello,", name)

Indentation :

Repetition is possible with the for loop

for i in range(3):

print("Hello")

print("Bye!")

Variables and data types

We saw already earlier that assigning a value to a variable is very simple:

a=1

print(a)

Note : Python automatically detected that the type of a must be int (an integer).

a="some text"

type(a)

Program Implementation :

In Python, the single equals (=) and double equals (==) serve different purposes:
PYTHON - August - 2024 BATCH (MGM)
= (Assignment operator):

This operator assigns a value to a variable. For example, x = 5 assigns the value 5 to the
variable x.

== (Equality operator):

This operator compares two values and checks if they are equal. It returns True if the values
are equal, and False otherwise. For example, x == 5 checks if the value of x is equal to 5.

Example :

x = 10 # Assign the value 10 to x

if x == 10: # Check if the value of x is equal to 10

print("x is equal to 10")

else:

print("x is not equal to 10")

* = is used for assigning values, while == is used for comparing values *

strings using the + operator

a="first"

b="second"

print(a+b)

print(" ".join([a, b, b, a]))

Sometimes printing by concatenation from pieces :

print(str(1) + " plus " + str(3) + " is equal to " + str(4)) # slightly better

print(1, "plus", 3, "is equal to", 4)

Multiple ways of strings interpolation :

- Python format strings print("%i plus %i is equal to %i" % (1, 3, 4))

- format method print("{} plus {} is equal to {}".format(1, 3, 4))

- f-string print(f"{1} plus {3} is equal to {4}")

LOOPS :
PYTHON - August - 2024 BATCH (MGM)
i=1

while i*i < 1000:

print("Square of", i, "is", i*i)

i=i+1

print("Finished printing all the squares below 1000.")

s=0

for i in [0,1,2,3,4,5,6,7,8,9]:

s=s+i

print("The sum is", s)

IF - ELSE STATEMENT :

x=input("Give an integer: ")

x=int(x)

if x >= 0:

a=x

else:

a=-x

print("The absolute value of %i is %i" % (x, a))

SPLITS :

days="Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split()

weathers="rainy rainy sunny cloudy rainy sunny sunny".split()

temperatures=[10,12,12,9,9,11,11]

for day, weather, temperature in zip(days,weathers,temperatures):

print(f"On {day} it was {weather} and the temperature was {temperature} degrees celsius.")
PYTHON - August - 2024 BATCH (MGM)
OPERATIONS STRING :

1. Creating Strings

You can create strings using either single quotes (`'`) or double quotes (`"`).

str1 = 'Hello, World!'

str2 = "Python is fun!"

2. Accessing Characters

You can access individual characters in a string using indexing (indices start at 0).

text = "Python"

print(text[0]) # Output: P

print(text[5]) # Output: n

3. Slicing Strings

You can extract a portion of a string using slicing.

text = "Hello, World!"

print(text[0:5]) # Output: Hello

print(text[7:12]) # Output: World

4. String Length

Use `len()` to get the length of a string.

text = "Hello"

print(len(text)) # Output: 5

5. Concatenation

You can concatenate strings using the `+` operator.

str1 = "Hello"

str2 = "World"

result = str1 + " " + str2

print(result) # Output: Hello World


PYTHON - August - 2024 BATCH (MGM)
6. Repetition

Use the `*` operator to repeat strings.

str1 = "Python! "

print(str1 * 3) # Output: Python! Python! Python!

7. Uppercase and Lowercase

Convert strings to uppercase or lowercase using `upper()` and `lower()` methods.

text = "Hello, World!"

print(text.upper()) # Output: HELLO, WORLD!

print(text.lower()) # Output: hello, world!

8. Strip Whitespace

Remove leading and trailing whitespace using `strip()`, `lstrip()`, and `rstrip()`.

text = " Python "

print(text.strip()) # Output: Python

print(text.lstrip()) # Output: Python

print(text.rstrip()) # Output: Python

9. Replacing Substrings

Use `replace()` to replace occurrences of a substring with another substring.

text = "Hello, World!"

new_text = text.replace("World", "Python")

print(new_text) # Output: Hello, Python!

10. Splitting Strings

Use `split()` to split a string into a list based on a delimiter.

text = "Python is fun"

words = text.split()

print(words) # Output: ['Python', 'is', 'fun']


PYTHON - August - 2024 BATCH (MGM)

11. Split using a specific delimiter

text = "apple,orange,banana"

fruits = text.split(",")

print(fruits) # Output: ['apple', 'orange', 'banana']

12. Joining Strings

Use `join()` to concatenate a list of strings into a single string.

words = ['Python', 'is', 'fun']

sentence = ' '.join(words)

print(sentence) # Output: Python is fun

13. Checking String Content

Use methods like `isdigit()`, `isalpha()`, and `isspace()` to check the content of strings.

text = "123"

print(text.isdigit()) # Output: True

text = "abc"

print(text.isalpha()) # Output: True

text = " "

print(text.isspace()) # Output: True

14. Formatting Strings

Use formatted string literals (f-strings) or the `format()` method for formatting.

name = "Alice"

age = 30

# Using f-strings

print(f"My name is {name} and I am {age} years old.")


PYTHON - August - 2024 BATCH (MGM)
# Using format() method

print("My name is {} and I am {} years old.".format(name, age))

These are some of the fundamental string operations you'll use often in Python.

23 - 08 - 2024

* Code for Random password generator *

If statement and its related statements.

Code :

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")

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

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


* The else keyword catches anything which isn't caught by the preceding conditions.
* The elif keyword in way of saying "if the previous conditions were not true, then try this
condition".

Two primitive loop commands: while loops, for loops


PYTHON - August - 2024 BATCH (MGM)
With the while loop we can execute a set of statements as long as a condition is true.
The while loop requires relevant variables to be ready, in this example we need to define an
indexing variable, i, which we set to 1.

i=1

while i < 6:

print(i)

i += 1

The break Statement: With the break statement we can stop the loop even if the while
condition is true

i=1

while i < 6:

print(i)

if (i == 3):

break

i += 1

The Continue Statement: With the continue statement we can stop the current iteration,
and continue with the next

i=0

while i < 6:

i += 1

if i == 3:

continue

print(i)

The Else Statement: With the else statement we can run a block of code once when the
condition no longer is true

i=1

while i < 6:

print(i)

i += 1

else:

print("i is no longer less than 6")

FOR LOOPS
PYTHON - August - 2024 BATCH (MGM)
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.

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

Even strings are iterable objects, they contain a sequence of characters

Code :

for x in "grapes":

print(x)

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

Code :

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

for x in fruits:

print(x)

if x == "cherry":

break

The Continue Statement :

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

Range Function : o 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.

Code :

for x in range(20):

print(x)

for x in range(2, 6):

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
PYTHON - August - 2024 BATCH (MGM)
for x in range(6):

print(x)

else:

print("Finally finished!")

Nested Loop :

A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each
iteration of the "outer loop"

adj = ["red", "big", "tasty"]

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

for x in adj:

for y in fruits:

print(x, y)

DICTIONARY
PYTHON - August - 2024 BATCH (MGM)

You might also like