❌

Normal view

There are new articles available, click to refresh the page.
Before yesterdaykavin suresh

Python Dictionary

6 August 2024 at 09:49

Annachi Kadai

In Tamil Nadu there was shop called Annachi Kadai. The owner of the shop is Pandiyan. Now we learn Python using this case study.

Morning:

In the early morning the goods for shop will come. Then Pandiyan will take a note on the goods.

One day the goods came to his shop and he take a note on it. They are:-

inventory = {
    "apples": 20,
    "bananas": 30,
    "carrots": 15,
    "milk": 10
}

He want to check the list.

print(inventory)
 {
    'apples': 20,
    'bananas': 30,
    'carrots': 15,
    'milk': 10
}

Noon:

As the time going the delivery also increases. So he add more inventories.

inventory["bread"] = 25
inventory["eggs"] = 50

Then he want to check the list

print("Updated Inventory:", inventory)

Updated Inventory: {'apples': 20, 'bananas': 30, 'carrots': 15, 'milk': 10, 'bread': 25, 'eggs': 50}

Afternoon:

Then in the afternoon the quantities of the goods is going less. So he buyed some goods and he want that to add it on the list.

inventory["apples"] += 10 
inventory["milk"] += 5

Then he want to check the list

print("Inventory after Restocking:", inventory)

Inventory after Restocking: {'apples': 30, 'bananas': 30, 'carrots': 15, 'milk': 15, 'bread': 25, 'eggs': 50}

Evening:

In evening many of goods have sold. So he want to remove it from the list.

del inventory["carrots"]

then he want to check the list.

print("Inventory after Removal:", inventory)

Inventory after Removal: {'apples': 30, 'bananas': 30, 'milk': 15, 'bread': 25, 'eggs': 50}

Night:

Before closing the shop. He wants to check the inventory is the inventories are correct.

is_bananas_in_stock = "bananas" in inventory
is_oranges_in_stock = "oranges" in inventory
print(f"Are bananas in stock? {is_bananas_in_stock}")
print(f"Are oranges in stock? {is_oranges_in_stock}")

 Are bananas in stock? True
 Are oranges in stock? False

This things only we learnt in the python class.
Thank You

Python List

5 August 2024 at 13:21

Empty List

In python it means that a list which is empty.

packages=[]
''

List

List means there are many things which are there in the list.
eg:
list
123
235
574
665

List in Python

eg:

packages=["fruits","vegetables","notebooks"]

Accessing Single List

eg:

packages=["fruits","vegetables","notebooks"]
item=packages[1]

'fruits'

Append() Method

eg:

packages=["fruits","vegetables","notebooks"]
packages.append("pencils")

packages=["fruits","vegetables","notebooks","pencils"]

Remove() method

eg:

packages=["fruits","vegetables","notebooks","pencils"]
packages.remove("fruits")

packages=["vegetables","notebooks","pencils"]

Pop() Method

eg:

packages=["vegetables","notebooks","pencils"]
last_package=packages.pop

packages=["vegetables","notebooks"]

Finding Position by using Index() Method

eg:

packages=["vegetables","notebooks"]
position=packages.index("vegetables")

'1'

Sort() Method

It used to use the list in alphabetical order.
eg:

packages=["fruits","vegetables","notebooks","pencils"]
packages.sort()

["fruits","notebooks","pencils","vegetables"]

This things and all I learn in my class.
Thank You.
S. Kavin

Indexing and slicing

27 July 2024 at 02:48

Hi everybody
I am Kavin
I going to write a blog which I learnt in my python class.

Indexing

Indexing is nothing but a position. Indexing refers to accessing individual elements of a sequence, such as a string.

In Python, strings are sequences of characters, and each character in a string has a position, known as an index.
eg:

word = K A V I N
       ^ ^ ^ ^ ^
index= 1 2 3 4 5 

Basic Indexing
eg:

name="kavin"
print(name[0])
print(name[1])
print(name[2])
print(name[3])
print(name[4])

'k'
'a'
'v'
'i'
'n'

Negative Indexing
Python also supports negative indexing, which allows you to access characters from the end of the string.
eg:

name="kavin"
print(name[-1])
print(name[-2])
print(name[-3])
print(name[-4])
print(name[-5])

'n'
'i'
'v'
'a'
'k'

Combining Positive and Negative Indexing
You can mix positive and negative indexing to access different parts of a string.
eg:

word='Indexing'
print(word[0]) 
print(word[-1])  
print(word[2])
print(word[-3]) 

 'I'
 'g'
 'd'
 'i'

Real-World Examples

** Initials of a Name**
eg:

full_name = "Parotta Salna"
initials = full_name[0] + full_name[8]
print(initials) 

PS

Accessing File Extensions
eg:

filename = "document.pdf"
extension = filename[-3:]
print(extension) 

'pdf'

Slicing

Slicing enables you to create a new string by extracting a subset of characters from an existing string.

Basic Slicing
The basic syntax for slicing is:

string[start:stop]

Where:

start is the index where the slice begins (inclusive).
stop is the index where the slice ends (exclusive).

Simple Slicing
eg:

text = "Hello, World!"
print(text[0:5]) 

'Hello'

Omitting Indices

You can omit the start or stop index to slice from the beginning or to the end of the string.
eg:

text = "Python Programming"
print(text[:6])  

'Python'

Slicing with Step

You can include a step to specify the interval between characters in the slice. The syntax is:

string[start:stop:step]

eg:

text = "abcdefghij"
print(text[0:10:2])  

'acegi'

Negative Indices and Step

Negative indices count from the end of the string, and a negative step allows you to slice in reverse order.
eg with Negative Indices:

text = "Python"
print(text[-3:])  

'hon'

eg with reversing a string :

text = "Reverse"
print(text[::-1]) 

'esreveR'

Real-World Examples

1.Extracting File Extensions

filename = "report.pdf"
extension = filename[-3:]
print(extension)  

'pdf'

2.Getting a Substring

quote = "To be or not to be, that is the question."
substring = quote[9:17]
print(substring)  

'not to be'

3.Parsing Dates

date = "20230722"
year = date[:4]
month = date[4:6]
day = date[6:]
print(f"Year: {year}, Month: {month}, Day: {day}")

Year: 2023, Month: 07, Day: 22

Advanced Slicing Techniques

1.Skipping Characters

text = "abcdef"
print(text[::2]) 

'ace'

2.Slicing with Negative Step

text = "abcdefghij"
print(text[::-2])  

'jhfdb'

This the things which I learnt I my class.
Thank you

Functions()

26 July 2024 at 14:11

hi, everybody
I am s. kavin
today we gone a see functions.

Functions

Think of a function as a little helper in your code. It’s like a recipe that you can use over and over again.

Why do need functions

1.Reusability
2.Organization
3.Avoiding Repetition
4.Simplifying Complex Problems
eg:

def celsius_to_fahrenheit(celsius):
    return (celsius * 9/5) + 32

celsius1 = 25
fahrenheit1 = celsius_to_fahrenheit(celsius1)
print(f"{celsius1}Β°C is {fahrenheit1}Β°F")

celsius2 = 30
fahrenheit2 = celsius_to_fahrenheit(celsius2)
print(f"{celsius2}Β°C is {fahrenheit2}Β°F")

celsius3 = 15
fahrenheit3 = celsius_to_fahrenheit(celsius3)
print(f"{celsius3}Β°C is {fahrenheit3}Β°F")

Uses of functions

1. Greet People

def greet(name):
    print(f"Hello, {name}!")

greet("Alice")
greet("Bob")

2. Adding Two Numbers

def add(a, b):
    return a + b

result = add(5, 3)
print(f"The sum is: {result}")

3. Checking if a Number is Even or Odd

def is_even(number):
    return number % 2 == 0

print(is_even(4))  # True
print(is_even(7))  # False

04. Finding the maximum of Three numbers

def max_of_three(a, b, c):
    max = None
    if a > b:
        max = a
    else:
        max = b

    if max > c:
        return max
    else:
        return c

5. Calculating Factorial of a number

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

print(factorial(5))  # 120

6. Calculating Area of a Circle

import math

def area_of_circle(radius):
    return math.pi * radius ** 2

print(area_of_circle(5))  # 78.53981633974483

Operators, Conditionals and Inputs

26 July 2024 at 13:57

Operators

Operators are symbols that tell the computer to perform specific mathematical or logical operations.

1.Arithmetic Operators

These operators perform basic mathematical operations like addition, subtraction, multiplication, and division.

*Addition (+): Add two numbers.
eg:

>>>print(1+3)

*Subtraction (-): Subtracts one number from another.
eg:

>>>print(1-3)

Multiplication (): Multiplies two numbers.
eg:

>>>print(1*3)

*Division (/): Divides one number by another.
eg:

>>>print(1/3)

*Floor Division (//): Divides one number by another and rounds down to the nearest whole number.
eg:

>>>print(1//3)

*Modulus (%): Returns the remainder when one number is divided by another.
eg:

>>>print(1%3)

Exponentiation (*): Raises one number to the power of another.
eg:

>>>print(1**3)

2.Comparison Operators

These operators compare two values and return either True or False.

*Equal to (==): Checks if two values are equal.

>>>a = 5
>>>b = 3
>>>result = (a == b)  

>>>result is False

*Not equal to (!=): Checks if two values are not equal.

>>>a = 5
>>>b = 3
>>>result = (a != b)  

>>>result is True

*Greater than (>): Checks if one value is greater than another.

>>>a = 5
>>>b = 3
>>>result = (a > b)  

>>>result is True

*Less than (<): Checks if one value is less than another.

>>>a = 5
>>>b = 3
>>>result = (a < b)  

>>>result is False

*Greater than or equal to (>=): Checks if one value is greater than or equal to another.

>>>a = 5
>>>b = 3
>>>result = (a >= b)  

>>>result is True

*Less than or equal to (<=): Checks if one value is less than or equal to another

>>>a = 5
>>>b = 3
>>>result = (a <= b)  
>>>result is False

3.Logical Operators

These operators are used to combine conditional statements.

*and: Returns True if both statements are true.

>>>a = 5
>>>b = 3
>>>result = (a > b and a > 0)  

>>>result is True

*or: Returns True if one of the statements is true.

>>>a = 5
>>>b = 3
>>>result = (a > b or a < 0)  
>>>result is True

*not: Reverses the result, returns False if the result is true.

>>>a = 5
>>>result = not (a > 0)  

>>>result is False

Conditionals

Conditionals are like traffic signals for your code. They help your program decide which path to take based on certain conditions.

1. The if Statement

The if statement checks a condition and executes the code block if the condition is True.
eg:

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

2. The elif Statement

The elif statement is short for β€œelse if”. It checks another condition if the previous if condition was False.
eg:

>>>a = 5
>>>b = 5
>>>if a > b:
    print("a is greater than b")
>>>elif a == b:
    print("a is equal to b")

3. The else Statement

The else statement catches anything that isn’t caught by the preceding conditions.
eg:

>>>a = 3
>>>b = 5
>>>if a > b:
    print("a is greater than b")
>>>elif a == b:
    print("a is equal to b")
>>>else:
    print("a is less than b")

PYTHON-FUNDAMENTALS: CONSTANTS, VARIABLES AND DATA TYPES

26 July 2024 at 13:22

hi,everyody
I am kavin. I am going to write which I learnt I my class.

Variables

A variable in Python is a symbolic name that references or points to an object. Once a variable is assigned a value, it can be used to refer to that value throughout the program. Variables act as containers for storing data values.

How to name a variables

1.Start with a letter or an underscore.
2.Followed by letters, digits, or underscores.
3.Case-sensitive
4.Don't use Python Keywords

Examples of Valid Variable Names:
my_variable
variable1
_hidden_variable
userName

Assigning Values to Variables

In Python, the assignment operator = is used to assign values to variables. The syntax is straightforward: variable_name = value.
eg:

>>>name="kavin"
>>>print(name)

>>>kavin

Multiple Assignments

Python allows you to assign values to multiple variables in a single line. This can make your code more concise and readable.
eg:

>>>a,b,c=1,2,3
>>>print(a,b,c)

Variable Types

Python is a dynamically typed language, which means you don’t need to declare the type of a variable when assigning a value to it. The type is inferred at runtime based on the assigned value.
eg:

>>>my_variable="10"

>>>my_variable is an integer

You can check the type of a variable using the type() function.
eg:

>>>type("hello")

>>><class'str'>

Constants

In Python, constants are variables whose values are not meant to change. By convention, constants are typically written in all uppercase letters with underscores separating words.
eg:

>>>PI=22/7

Data Types

Data types are the different kinds of values that you can store and work with.

1.Numeric Types
*Integer (int): Whole numbers.

>>>value=23

*Float (float): Decimal numbers.

>>>value=23.5

*Complex (complex): Complex numbers.

>>>value=2+3j

2. Text Type

String (str): Sequence of characters.
eg:

>>>message="hello mac"

3. Boolean Type

Boolean (bool): Represents True or False.
eg:

>>>my_project=True

4. None Type

NoneType: Represents the absence of a value
eg:

>>>result=none

5. Sequence Types

*List (list): Ordered, mutable collection
eg:

>>>fruits=[apple,cherry,mango]

*Tuple (tuple): Ordered, immutable collection.
eg:

>>>coordinates(3,4)

*Range (range): Sequence of numbers.
eg:

>>>number=range(1,10)

6. Mapping Type

Dictionary (dict): Unordered, mutable collection of key-value pairs.
eg:

>>>person={"name":"kavin","url":"https://www.kavin.com"}

7.Set Type

Set (set): Unordered collection of unique elements.
Eg:

>>>unique_number={2,3,4}

Frozenset (frozenset): Immutable set.
eg:

>>>frozen_set=frozena([2,3,4])

Checking Data Type

Syntax: type(variable_name)
eg:

>>>name="kavin"
>>>print(type(name))

>>> <class'int'>

this is the things which i learnt in the class of Variables, Constants and Data Types.
Thank You

Print()

26 July 2024 at 02:43

hi, everybody
today I gone to explain which I learnt.

Print() means printing a str, int, flo, etc.

Printing a String
when we want to print a string can use this syntax:
syntax:

print()

eg:

>>>print("hello")
>>>hello

Printing a variables
When we want to print a variables we can use this syntax
eg:

>>>name="hello" 
>>>print(name)

>>> hello

Printing into multiple items
You can print multiple items by separating them with commas.
eg:

>>>age="45"
>>>city="chennai"
>>>name="kavin"
>>>print("Name:",name,"Age:",age,"City:",city")

>>>Name: kavin Age: 45 City: chennai

Formatting with f-strings
An f-string is a way to format strings in Python. You can insert variables directly into the string by prefixing it with an f and using curly braces {} around the variables.
eg:

>>>age="45"
>>>city="chennai"
>>>name="kavin"
>>>print("Name:{name},Age:{age},City:{city}")

>>>Name: kavin Age: 45 City: chennai

Concatenation of strings

We can combine the strings by this.
eg:

>>>main_dish="Parotta"
>>>side_dish="salna"
>>>print(main_dish+""+side_dish+"!")

>>>Parotta salna!

Escape sequencenes
Escape sequences allow you to include special characters in a string. For example, \n adds a new line.
eg:

>>>print("hi\nhello\nfriends")
>>>hi
   hello
   friends

Raw(r) strings
Raw stings are strings which type only which is give in the input.
eg:

>>> print(r"C:users\\name\\tag")
>>> C:users\name\tag

Printing numbers

It used to print numbers.
eg

>>>print(123545)
>>>123545

Printing the results of the expressions
This is used to find the value of a expression.
eg;

>>>print(1+3)
>>>4

Printing lists and dictionaries
We can the entire lists and dictionaries.
eg:

>>>fruits["banana","apple","cherry"]
>>>print(fruits)

>>>['banana','apple','cherry']

using sep and end Parameters
We can use this to separate(sep) and end(end) with this parameters.
eg:

>>>print("hello","world",sep="-",end="!")
>>>hello-world!

Triple Quotes
We can use this for print as a same.
eg:

>>>print("""
hello 
everybody
""")

>>>hello 
   everybody

String Multiplication
This is used to Multipling string.
eg:

>>>print("hello"*3)
>>>hellohellohello

This is learnt in the class of python print() class which is I leant by seeing Parotta Salna python class of Day-2

❌
❌