❌

Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

Python - Indexing and Slicing

By: ABYS
24 July 2024 at 14:59

Indexing & Slicing is an important concept in Python, especially when we use strings.

Indexing :

WKT, string is nothing but a sequence of characters.
So, each character has a position namely index and accessing their position in that particular string is known as indexing.

In Python, we have zero based indexing i.e., the first character of a string has an index(position) of 0 rather than having one, then the second character has an index(position) of 1 and so on.

For example,

>     H E L L O W O R L D
>     0 1 2 3 4 5 6 7 8 9

This is known as positive indexing as we have used only positive numbers to refer the indices.

You may ask that "Then, we have negative indicing too??"
Ofc, but in here we do not have zero as the first position as it ain't a negative number.

Negative indexing allows us to access characters from the end of the string i.e., the last character has an index of -1, the second last character has an index of -2, and so on.

>      H  E  L  L  O  W  O  R  L  D
>    -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
word = "HELLOWORLD"

print(word[0])
print(word[5])

H
W

Similarly,

print(word[-1])
print(word[-6])

D
0

That's it about indexing.

Slicing :

Think of slicing a string like cutting a slice of cake from a whole cake. We can specify where to start cutting (index), where to finish (end index), and even how big each slice should be (step). This way, we can create smaller portions of the cake (or string) exactly how we like them!

In Python, slicing a string lets us grab specific parts of it by specifying where to start and where to end within the string.
So, for instance, if message contains "HELLOWORLD", then message[3:7] gives you "LOWO" because it starts at index 3 ('L') and ends just before index 7 ('D'). This way, we can extract any part of a string we need!

- The basic syntax for slicing is,

string[start:stop]
  • The start index is where the slice begins, and this index is inclusive.
  • The stop index is where the slice ends, but this index is exclusive, meaning the character at this index is not included in the slice.
text = "HappyBirthday"

print(text[0:5])  
print(text[5:13])

Happy
Birthday  

When slicing a string in Python, we can simply omit the start or stop index to slice from the beginning or to the end of the string.
It's as straightforward as that!

- Slicing with a step,

To specify the interval between characters when slicing a string in Python, just add a colon followed by the step value:

string[start:stop:step]

This allows to control how we want to skip through the characters of the string when creating a slice.

message = "HELLOWORLD"
print(message[1::2])    

EORL

message[1::2] starts slicing from index 1 ('E') to the end of the string, with a step of 2.
Therefore, it includes characters at indices 1, 3, 5, and 7, giving us "EORL".

Until, we saw about positive slicing and now let's learn about negative slicing.

- Negative Slicing :

  • A negative step allows you to slice the string in reverse order.
  • Let us slice from the second last character to the third character in reverse order
message = "HELLOWORLD"
print(message[-2:2:-1])

ROWOL

Let's look into certain questions.

#Write a function that takes a string and returns a new string consisting of its first and last character.

word = "Python"
end = word[0]+word[5]
print(end)

Pn

#Write a function that reverses a given string.

word = "Python"
print(word[::-1])

nohtyP

#Given a string, extract and return a substring from the 3rd to the 8th character (inclusive).

text = "MichaelJackson"
print(text[3:9])

haelJa

#Given an email address, extract and return the domain.

email = "hello_world@gmail.com"
domain = email[:-10]
print(domain)

hello_world

#Write a function that returns every third character from a given string.

text = "Programming"
print(text[::3])

Pgmn

#Write a function that skips every second character and then reverses the resulting string.

text1 = "Programming"
print(text1[::-2])

gimroP

#Write a function that extracts and returns characters at even indices from a given string.

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

Pormig

Allright, that's the basic in here.

.....

Python - Functions

By: ABYS
19 July 2024 at 11:24

FUNCTIONS, an awesome topic I learnt today. It's a shortcut for all lazy i.e., smart people who don't wanna waste their time typing inputs for several times.

What Is a Function?

In programming, rather than repeatedly writing the same code , we write a function and use it whenever and whereever it is needed.
It helps to improve modularity, code organization and reusability.

So, now let's see how to create a function.
A function contains,

  • function name - an identifier by which a function is called
  • arguments - contains a list of values passed to the function
  • function body - this is executed each time the function is called function body must be intended
  • return value - ends function call and sends data back to the program
def function_name(arguments): # key function name(arguments)
  statement                   # function body
  statement

  return value                # return value

Some examples of how to use functions.

#Write a function greet that takes a name as an argument and prints a greeting message.

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

Hello, ABY!

Here, we can replace return by print too.

#Write a function sum_two that takes two numbers as arguments and returns their sum.

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

result = add(3,7)
print(result)

10

#Write a function is_even that takes a number as an argument and returns True if the number is even, and False if it is odd.

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

num = 5
print(is_even(num))

False

#Write a function find_max that takes two numbers as arguments and returns the larger one.

def find_max(a,b):
    if a > b:
      return a
    else:
      return b

print(find_max(7,9))

9

#Write a function multiplication_table that takes a number n and prints the multiplication table for n from 1 to 10.

def multiplication_table(n):
    for I in range (1,11)
    result = n * i 

print(f"{n} * {i} = {result}")
n = multiplication_table(int(input("Enter a no: ")))

and the result is,

Enter a no: 5 # I've entered 5
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

#Write a function celsius_to_fahrenheit that takes a temperature in Celsius and returns the temperature in Fahrenheit.

This is how we normally do it..

celsius1 = 27
fahrenheit1 = (celsius1 * 9/5) + 32
print(f"{celsius1}Β°C is {fahrenheit1}Β°F")

celsius2 = 37
fahrenheit2 = (celsius2 * 9/5) + 32
print(f"{celsius2}Β°C is {fahrenheit2}Β°F")

celsius3 = 47
fahrenheit3 = (celsius3 * 9/5) + 32
print(f"{celsius3}Β°C is {fahrenheit3}Β°F")

27Β°C is 80.6Β°F
37Β°C is 98.6Β°F
47Β°C is 116.6Β°F

It's cumbersome right??
Soo, what's the shortcut? Ofc using a function.

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

celsius = float(input("Celsius: "))
fahrenheit = celsius_to_fahrenheit(celsius)
print(f"{celsius}Β°C is {fahrenheit}Β°F")

Celsius: 37.5
37.5Β°C is 99.5Β°F

I've used input function to make it more compact...

#Write a function power that takes two arguments, a number and an exponent, and returns the number raised to the given exponent. The exponent should have a default value of 2.

def pow(num,exp = 2):
  return num ** exp


result = pow(5,exp = 2)
print(f"The number {num} raised to power 2 is ",{result})

You can opt to use input fns and variables as well..

By now, it's understandable that for one problem we can use multiple
programs to solve it. It depends which we prefer to use.

.....

Python - Operators and Conditionals

By: ABYS
17 July 2024 at 10:31

In this blog, we'll get to know about operators, conditionals and input() functions.
Let's jump into Operators.

What are Operators ?

Symbols that perform specific mathematical / logical operations in computer.
This is of 3 types namely;

  • Arithmetic operators
  • Comparison operators
  • Logical operators

What are these and what functions they perform ?

Lemme tell something, you guys will be surprised to learn how simple it is...

1.Arithmetic operators

It includes basic mathematics like addition, subtraction, multiplication, division and few more..
We've seen all these in previous blog where we created a calculator.

ok you would be asking what about the remaining two..
yeah, I'll discuss that now.

2.Comparison operators

It compare two values and return either True or False.

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

For ex,

a = 2
b = 4

result = (a > b)
print(result)

False

a = 2
b = 4

result = (a <= b)
print(result)

True

3.Logical operators

Used to combine conditionals (if, else)

  • and - if both the statements are true, Returns True.
  • or - if one of the statements is true, Returns True.
  • not - returns False if the result is true i.e, Reverses the result.
#and
condition_1 = True
condition_2 = True
print(condition_1 and condition_2)

True

condition_1 = True
condition_2 = False
print(condition_1 and condition_2)

False

#or
condition_1 = True
condition_2 = False
print(condition_1 or condition_2)

True

#not
condition_1 = True
print(not condition_1 )

False

With this, Operators done.

Now, What are Conditionals ?

  • It used decide which path to take based on given conditions.
  • The commonly used conditional statements in Py. are if, elif, and else.

Lemme explain it using a realtime scenario,
I'm planning to go out and I wanna select my clothes. So, I've three options tracks, dress or I'm not going.

if tracks_available:
wear tracts
elif dress_aviable:
wear dress
else:
sit at home

The same we're gonna do it by coding.
Let's compare two numbers;

a = 25
b = 25
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")

So, each condition is checked by steps, as according to line 5 and 6
the result will be as following..

a is equal to b

Get User Input using input()

It is to get input from the user.
We always get input in string type i.e, text format, so if we need a number we've to convert it.

Here's a basic usage of this function:

name = input("What is your name? ")
print("Hello, " + name + "!")
print("Have a nice day.")

It asks the user for their name and then prints as given.
But, that's not the case for numbers as we've discussed earlier while creating calculator.

For numbers we ought to convert the input from string to an integer or float..

age = input("Enter your age: ")
age = int(age)
print("You are " + str(age) + " years old.")

or,

age = int(input("Enter your age: "))
print("You are " + str(age) + " years old.")

Let us now look into a question which comprises it all.

Create a program that asks the user to enter a number and then prints whether the number is positive, negative, or zero.

num = float(input("Enter a number: "))
if num > 0 :
   result = "positive"
elif num < 0 :
   result = "negative"
else :
   result = 0
print(f"The number is {result}.")

This program

  • Asks the user to enter a number.
  • Converts the input to a float (as it could be applicable for decimals too)
  • Check if the number is positive, negative, or zero, and prints the result.

Okay, with this in our mind try to make a grading system.

Grading system
A - 100 to 90
B - 90 to 80
C - 80 to 70
D - 70 to 60
E - 60 to 45
FAIL - 45 to 0

Lets create a program that takes a numerical grade as input and prints the corresponding letter grade (A, B, C, D, or F). Total Marks is 100.

mark = float(input("Enter your mark : "))

if mark >= 91 and mark <= 100:
    print("Grade A")
elif mark >= 81 and mark < 91:
    print("Grade B")
elif mark >= 71 and mark < 81:
    print("Grade C")
elif mark >= 61 and mark < 71:
    print("Grade D")
elif mark >= 45 and mark < 61:
    print("Grade E")
elif mark < 45:
    print("Fail")
else:
    print("Mark not valid")

Try it out yourself...

Let's make a Calculator using Py.

By: ABYS
16 July 2024 at 14:48

Before we actually make a calculator, let's first see some basic mathematical expressions...

1. Add

num1 = 2
num2 = 3
print(num1+num2) 

5

2. Subtract

num1 = 7
num2 = 5
print(num1-num2)

2

3. Multiply

num1 = 5
num2 = 5
print(num1*num2)

25

4. Divide

num1 = 100
num2 = 5
print(num1/num2)

20

5. Modulus (nothing but remainder)

quotient = 5//2
remainder = 5 % 2
print(quotient , "," ,remainder)

2 , 1

6.Exponentiate (powers)

For ex; a power b in python written as a**b

num1 = 3
num2 = 3
print(num1**num2)

27

Input Datatype and Typecasting

# Addition

num1 = int(input("Enter Number 1 : "))
num2 = int(input("Enter Number 2 : "))

result = num1+num2
print("Result is : ", result)

Enter Number 1 : 1
Enter Number 2 : 4
Result is :  5

Here it appears as steps but I'm unable to present it.
You can just do it and see.

# to make it possible in decimals too we use float

num1 = float(input("Enter Number 1 : "))
num2 = float(input("Enter Number 2 : "))

result = num1+num2
print("Result is : ", result) 

Enter Number 1 : 1.5
Enter Number 2 : 2.5
Result is :  4.0

Similarly, we do for other operations.

Now, with this knowledge we gonna create a simple calculator by using the following code;

print("Simple Calculator")
print("Select Operation : ")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Modulus")
print("6. Exponentiate")

choice = input("Enter choice (1/2/3/4/5/6) : ")
num1 = float(input("Enter first  Number : "))
num2 = float(input("Enter second Number : "))

if choice == "1" :
   result = num1 + num2
   print(result)
elif choice == "2" :
   result = num1 - num2
   print(result)
elif choice == "3" :
   result = num1 * num2
   print(result)
elif choice == "4" :
   result = num1 / num2
   print(result)
elif choice == "5" :
   result = num1 % num2
   print(result)
elif choice == "6" :
   result = num1 ** num2
   print(result)
else :
   print("option not available")

So, that's what I learned under this topic.
You can use the same code above and chk whether it works for you too..

Platforms I use to try these codes :

  • W3 Schools Tryit Editor
  • Google Colaboratory
  • Visual Studio Code

.....

Python - Fundamentals

By: ABYS
16 July 2024 at 14:00

In here, I'm gonna tell you how to use variables in python. We shall see how to name a variable and assign values to them.

How to name a Variable ?

Firstly a variable is nothing but a reference to an object or value throughout the program. They act as reference to a memory where the value is stored.

There are certain rules to name them.

  • Must begin with a letter (a-z, A-Z) or an underscore (_).
  • After the first character, letters, digits (0-9), or underscores can be followed.
  • Variable names are case-sensitive. For ex, myName and myname are entirely different variables.
  • Should not use Python reserved words as variable names For ex: class, def, for, while.

So, in python the operator = is used for assigning values to variables.

# Assigning integer value
age = 18
print(age)

18

# Assigning string value
name = "Arif"
print(name)

Arif

# Assigning float value (float means decimal value)
height = 2.5
print(height)

2.5

# Assigning boolean value (rfrs to true/false)
is_student = True
print(is_student)

True

Varible Types

Python is a typed lang, we needn't declare the type of a variable when assigning a value to it. The type is inferred by its own.

name = "Abys"
print(name)
print(type(name))

Abys
<class 'str'>

or we can also define the type by,

name = "Abys"
type(name)

str

age = 18
type(age)

int

That's the basic.

I've been asked to complete some questions on my own, lemme discuss those with you guys.
It's much easier to learn right...?

1. Create a variable named name and assign your name to it. Then print the value of the variable.

name = "Abys"
print(name)
print(type(name))

Abys
<class 'str'>

2. Create a variable age and assign your age to it. Later, reassign the variable with a new value and print the new value.

age=17
print("Present age:",age)
age= 18
print(age)

Present age: 17
18

and here if we want the type;

print(type(age))
<class 'int'>

3. Assign the values 5, 10, and 15 to three variables a, b, and c in a single line. Print their values.

a,b,c = 5,10,15
print(a,b,c)

5 10 15

if we wanna add them we get,

print(a+b+c)

30

4. Swap the values of two variables x and y without using a third variable. Print their values before and after swapping.

x,y = 5,25
print(x,y)
print(x-y)
x,y = 25,5
print(x,y)
print(x-y)

5 25
-20
25 5
20

they've asked just to print the swapped values, it's me who did extra stuffs.

Before the next qn we ought to know what is constants...

What are Constants ?

In Python, constants are those values that are not meant to change. By convention, they are typically written in capital letters with underscores separating the words.
However, in python constants can also be changed.

5. Define constants PI with appropriate values and print them.

PI=3.14159
print(f"{PI:.3f}")

3.142

6. Write a program that calculates the area of a circle using the constant PI and a variable radius. Print the area.

PI=3.14
radius=7
r=radius
area=PI*r**2 # r**2 refers to r pow 2
print("Area of circle is",area)

Area of circle is 153.86

7. Define constants for the length and width of a rectangle. Calculate and print the area.

L,B = 5,15
area = L*B
print("Area of rect is ",area)

Area of rect is  75

These were the qns I worked on. Hope it is clear.
Sorry, if I'm ain't clear enough.., as I've just started blogging I may make mistakes.
Definitely will improve myself.
Thank you, All...

My First Blog _Python

By: ABYS
16 July 2024 at 08:39

Hi All,

This is my very first blog. I'm a Biomath student who has zero knowledge about computer related stuffs.
Later, I was convinced to study a programming language yet confused with how,where and what to start...?

And finally decided to learn python, as people around me implied that it's easy to start with... So, now I'm learning python from an online platform., which teaches me so fine...

I thought of blogging it all, cause people like me will get to know that python isn't overly challenging rather as simple as English grammar.

We can learn python just by using "Google Colaboratory", yet I would let u know how to install python later.

So, join with me...
Let's start to learn PYTHON

PYTHON BASICS

1. Printing a String :

  • To print a text, we use print function - print()

  • Let's begin with "Hello World".

  • By writing certain text within the print function inside double or single quotes, we get :

print("Hello World")

Hello World

2. Similarly, we can Print Variables :

  • Variables are used to store data.
name = "Abys"
print(name)

Abys

  • Here, if we give numbers as values for the variable (ex: age=25) we needn't provide them under double or single quotes as they give the same output but as for texts we should use "" or ''.
age = 25 
print(age)

25

age = "25"
print(age)

25

name = Abys
print(name)

Traceback (most recent call last):
  File "./prog.py", line 4, in <module>
NameError: name 'Abys' is not defined

  • That's the reason for this rule. Hope it's clear.,

3. Printing Multiple Items :

  • We can print multiple items by separating them with commas while python adds space between each item.

  • Formatting strings with f strings is another sub topic where we insert variables directly into the string by prefixing it with an f and using curly braces {} around the variables.

let's see both,

name="Abys"
age=17
city="Madurai"
print("Name:",name , "Age:",age , "City:",city ,end=".")

Name: Abys Age: 17 City: Madurai.


name="Abys"
age=17
city="Madurai"
print(f"Name:{name},Age:{age},City:{city}.")

Name:Abys,Age:17,City:Madurai.

4.Concatenation of Strings :

  • Here, we connect words using + operator.
w1="Sambar"
w2="Vada"
print(w1+" "+w2+"!")

Sambar Vada!

  • Let's also see what is Printing Quotes inside Strings.

  • To print quotes inside a string, we can use either single or double quotes to enclose the string and the other type of quotes inside it.

w1="Sambar"
w2="Vada"
print("I love" , w1+" "+w2+"!")

I love Sambar Vada!

hobby = "Singing"
print("My hobby is" , hobby)

My hobby is Singing

5.Escape Sequences and Raw Strings to Ignore Escape Sequences :

  • Escape sequences allows to include special characters in a string. For example, \n adds a new line.
print("line1\nline2\nline3")

line1
line2
line3

  • r string is used as prefix which treats backslashes as literal characters.
print(r"C:\Users\Name")

C:\Users\Name

6.Printing Results of Mathematical Expressions :

  • We've already seen how to print numbers.
print(26)

26

  • Now, we're going to print certain eqns.
print(5+5)

10

print(3-1)

2

that's how simple it is...

7.Printing Lists and Dictionaries :

  • We can print entire lists and dictionaries.
fruits = ["apple", "banana", "cherry"]
print(fruits)

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

8.Using sep and end Parameters :

  • The sep parameter changes the separator between items.

  • The end parameter changes the ending character.

print("Happy", "Holiday's", sep="-", end="!")

Happy-Holiday's!

  • Let's see how to print the same in adjacent lines, here we use either escape sequences (\n) or Multiline Strings.

  • Triple quotes allow you to print multiline strings easily.

print("""Happy
Holiday's""")

print("Happy\nHoliday's")

both gives same output as :

Happy
Holiday's

9.Combining Strings and Variables :

  • Combining strings and variables by using + for simple cases or formatted strings for more complex scenarios.

  • For simple case:

colour = "purple"
print("The colour of the bag is "+colour)

The colour of the bag is purple

  • For complex case :
temperature=22.5
print("The temperature is", str(temperature),"degree Celsius",end=".")

The temperature is 22.5 degree Celsius.

10.Printing with .format() and Using print for Debugging:

  • Use the .format() method for string formatting.
name="Abys"
age=17
city="Madurai"
print("Name:{}, Age:{}, City:{}".format(name,age,city))

Name:Abys, Age:17, City:Madurai

  • We can use print to debug your code by printing variable values at different points.
def add(a, b):
    print(f"Adding {a} and {b}")
    return a + b

result = add(1, 2)
print("Result:", result)

Adding 1 and 2
Result: 3

That's it.
These were the topics I learned in my 1st class.

At the beginning, I was confused by all the terms but as time went I got used to it just like we first started to learn English.

Try it out yourself... as u begin to get the output., it's next level feeling.
I personally felt this;
"Nammalum Oru Aal Than Pola"...

.....

❌
❌