❌

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 - 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...

❌
❌