info edupoly https://edupoly.in Indepth Training on ReactJS, Angular, Javascript, MERN,MEAN,Python,Java,Devops,AWS Sat, 01 Jun 2024 12:00:38 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://edupoly.in/wp-content/uploads/2024/03/edupoly-logo-light-150x150.png info edupoly https://edupoly.in 32 32 Classes https://edupoly.in/full-stack-training-in-hyderabad/classes/ Sat, 25 May 2024 05:17:05 +0000 https://edupoly.in/?p=503

Classes

In Python, classes are a fundamental concept used for object-oriented programming (OOP). Classes are a special data type which provide a way to structure and organize code by grouping data attributes and methods (functions) that operate on that data into a single unit called an “object”.

Let us take a very basic example of a class. 

Output:

<class ‘__main__.Person’>

Here, we are defining a Person class using the class keyword. We have also defined two attributes(firstname and lastname) inside the class. So, this class groups the firstname and lastname data attributes into a single unit which can be later used to create an object. On printing the value of Person, we only get to see that it is a class named Person. We cannot see the attributes present inside the class.

If we try to print the data type of this class, we get the output as ‘type’.

Output:

<class ‘type’>

So, in order to access the attributes, we have to use attribute references. Let us now see how to use attribute references.

Output:

Charles

Babbage

AttributeError: type object ‘Person’ has no attribute ‘age’

From this example, we can say that we can use a dot(.) followed by the reference of the attribute to access the attribute present in a class. Here, Person.age throws an error as there is no ‘age’ attribute in the Person class. 

Person.firstname and Person.lastname are known as attribute references. These attribute values can be modified by assigning new values to them.

Output:

Darwin

Here, we are modifying the lastname attribute by assigning a new value to it. In the output, we can see that the value of the lastname attribute has changed. 

Let us now see how to create an object using a class. Previously, we have seen that the type of a class is a type. This is because creating a new class creates a new type of object, allowing new instances of that type to be made. We can create an object from a class by instantiation. We can instantiate a class just like what we do to call a function as follows:

Here, we can see that we are creating an instance of a class by using Person(). It returns an object of type Person to the variable person1. On printing person1, we can see that it is a Person object stored at some memory location. On checking the type, it denotes that it is of type Person. We can also access the firstname and lastname attributes of the created object as shown above.

Earlier, we had seen that we can modify the attributes of a class by using attribute references. But that can create undesired effects in the created objects. That’s why we should avoid that approach. Rather, we should create objects out of a class and modify attributes of created objects to avoid polluting the main class. This can be done as follows:

Here, we are creating two instances of the Person class to generate two separate objects(person1 and person2). Then, we are modifying the lastname attribute of the person1 object. This does not modify the lastname attribute of the Person object which we can see at the last line.

Until now, we were creating objects by calling the class object(instantiation) with no parameters. 

person1 = Person()

The object created in this way has the attributes values as defined in the class. This means that all object instances created from the same class will have the same attribute values. But in reality, we may need some attributes unique to each class. In that case, we have to proceed with a slightly different approach. For this, we need a special method called __init__(). We need to define our attributes inside the __init__()method.

Here, we can see that the __init__()method is defined inside the class which takes two parameters. The first parameter self points to the current class instance and the second parameter brand is a value to be passed to the class during instantiation. Inside the __init__() method, self.brand is creating a new attribute for the class to which the user-defined value of brand is assigned. Thus, the Car class has two attributes, category and brand. Here, category is an attribute or variable present in the class which will be shared by all instance objects created from this class. Whereas, brand is an attribute or value passed during instantiation which will be unique for all instances. Due to this, category is known as a class variable and brand is known as an instance variable.

While creating an instance, we can see that we are passing the string BMW which is received by the __init__() method and assigned to the brand variable.

In the above example, we can observe the difference between class variable and instance variable. Here, category is a class variable and therefore it is shared by both instance objects. Whereas brand is an instance variable and therefore it is unique for both instances.

We can also have methods(or functions) inside classes which can be called using attribute references. A function residing inside a class is known as a method. For example:

Output:

It is a four-wheeler BMW

Here, we have created a carDetails method inside the class which prints the car details(category and brand). In this class, both __init__ and carDetails are methods. The only difference is that __init__ is a special method which if present gets called automatically during instantiation. But the carDetails method needs to be called in order to get the desired output. We are calling it using the statement car1.carDetails() where we are accessing the method using attribute reference. It has a parameter self which points to the current object instance. So, we need to access the category and brand attribute values by using self.category and self.brand respectively.

Note that we can use any variable like obj, myobj, thisobj etc. instead of self.

]]>
503
File operations https://edupoly.in/full-stack-training-in-hyderabad/file-operations/ Sat, 25 May 2024 05:15:27 +0000 https://edupoly.in/?p=504

File operations

When dealing with data in daily scenarios, we may often need to store the data. But data stored in variables are temporary and get reset once we close our program. So, we may want to store the data in files. Let us learn to read/write data onto files in this section.

Writing to a file

To write, first we need a file. Create a file in the directory where you are having your python file. Let’s say we have a 1.py file. In the same directory as the file, create another file users.txt.

Now we have to write some data into this users.txt from the 1.py file.

Let us create a function writeToFile which when called should write some string into the users.txt file. In Python, we have a method called open which helps us to open a file in order to read or write data onto files. We can implement the open method as follows:

Here, we are passing two arguments to the open method. The first one is the path of the file on which we want to perform some action. The second argument is the mode of operation. Here, ‘w’ means write mode. The open method here is only opening the file for writing. But it does not perform any write operation on the file. To write data onto the file, we need to use the write method as follows:

Here, we are using the write method to write the text “Charles Babbage” onto the users.txt file. Finally, we are calling the writeToFile function to execute the code. After this code is executed, if we observe the users.txt file, we can see that the string “Charles Babbage” is written onto the file. But remember that in the beginning, we opened the file for writing. Therefore, it is also necessary to close the file after the writing operation is complete. It is unsafe to keep the file open after the desired operations are done. For that, we need to use the close method as follows:

This is how we open a file, write data onto it and safely close it.

Now, let us modify the code to write another piece of text onto the users.txt file as follows:

After running this code, we will observe that the previous text, “Charles Babbage” is replaced by the new text, “Charles Darwin”. But if we want to add(not replace) a new piece of text to the users.txt file, this approach won’t help us. For that, we just need to change the mode of operation. Till now, we were using the ‘w’ mode, which is write mode. But now we need to go with the append(‘a’) mode to add or append new text to the existing text in the file.

Let us modify our code as follows:

We have just replaced ‘w’ with ‘a’ and passed a new string(Hello) to the write method. Please keep in mind that the users.txt file had the text Charles Darwin because of the previous code execution(write  method with w mode). So, now when we run the above code with a(append) mode, the text “Hello” will be appended to the Charles Darwin text as follows in the users.txt file: Charles DarwinHello

This is totally correct as we told Python to append the new text to the old text. If we want all text in the file to be added in a new line, we need to add a new line character(\n) to the text that we are passing. To do this, first edit the users.txt file to remove all the text from it. Then run the following code:

Now, this will append the new text and move to a new line. If we repeat this code again, we get the following text in the users.txt file:

Hello

Hello

Please note that, we are opening the file using the open method, writing the desired text and then safely closing the file using the close method. For every operation, we need to repeat this opening and closing of the file. But Python has a better alternative for this. In Python, there is a with statement which can handle the opening and closing of files on its own. Let us see it in action.

Here, we are using the with statement to open the file in append mode(a). As you can see here, we are not writing separate open and close methods. The with statement opens the file for writing in append mode. Once the write operation is done, it automatically closes the file. This is syntactically less compared to the previous approach.

Reading a file

Let us now see how to read a file in Python. Please note that to write onto a file, we opened the file in write(w) mode. If we don’t specify the mode, the open method opens the file in read(r) mode by default. After opening the file in read mode, we need to use the read method to read the contents of the file. 

Output:

Hello

Hello

Welcome

Here, the read method reads the whole file and returns the whole content of the file as a string. In the above code, we are not passing any argument to the read method. But we can also pass a size argument as below:

Output:

Hel

Here, the argument 3 tells Python up to how many bytes should be read. Here, it reads 3 bytes from the file as shown in the output. Here, it is to be noted that Python has read only up to 3 bytes and it will stay in that position until the file is closed. If we read the file again without closing the file, Python will continue reading from the same position where it left.

Let us consider the following code:

Output:

Hel

lo

Here, Python first reads the file up to 3  bytes and prints the characters. Hence, we get Hel in the output. Then we read 2 bytes again before closing the file. Python starts reading from the last position of the file object. Hence, we get lo in the output. But once we close the file using the close method, the file object’s position is reset and will read the file from the beginning if opened again.

If we want to know the file object’s current position, we can use the tell()method of the file object as follows:

Output:

Hel

3

Here, we can see that after reading 3 bytes, the tell() method is returning us the current position of the file object. If we want to move or change the position of the file object, we can use the seek() method as follows:

Output:

Hel

3

1

This way, we can change the file object’s position and start reading from there as well:

Output:

llo

Let us now see how to read a file using the with statement. Remember that we had a users.txt file. We will open the file and read it as follows:

Output:

Hello

Hello

Welcome

Here, we are using the read method which returns a string containing the contents of the specified file.

]]>
504
Comprehensions https://edupoly.in/full-stack-training-in-hyderabad/comprehensions/ Thu, 23 May 2024 11:38:05 +0000 https://edupoly.in/?p=498

The Importance of Comprehensions in Python


Python’s comprehensions (list, set, and dictionary) are concise, elegant one-liners for creating collections. They offer several key advantages:
Comprehensions often express the desired collection in a more natural way compared to traditional loops.
They condense multiple lines of iterative code into a single, focused expression.
In many cases, comprehensions can be faster than equivalent loop-based solutions, especially for simple operations.
They encourage a functional programming style, where the focus is on transformations rather than explicit iteration mechanics.
List Comprehensions

Without Comprehension (Traditional Loop)

squares = []
for x in range(10):
squares.append(x**2)

print(squares)

# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

With List Comprehension

squares_comp = [x**2 for x in range(10)]
print(squares_comp) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
The list comprehension is more concise, expressing the desired operation (squaring) directly without the need for an explicit loop or append statement.
List comprehensions create new lists by applying an expression to each item in an iterable (like a list, tuple, or range), optionally filtering items based on a condition.

Basic List Comprehensions

Square the numbers from 0 to 9

squares = [x2 for x in range(10)] print(squares)

# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

This comprehension iterates over the numbers produced by range(10) (0 through 9). For each number x, it calculates x2 (x squared) and includes the result in the new list squares.

Convert strings in a list to uppercase

words = [“hello”, “world”, “python”]
uppercase_words = [word.upper() for word in words]
print(uppercase_words)

# Output: [‘HELLO’, ‘WORLD’, ‘PYTHON’]
This comprehension iterates over the strings in the words list. For each word, it calls the upper() method to convert it to uppercase and includes the result in the uppercase_words list.

List Comprehensions with Conditions

Get even numbers from a list

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers)

# Output: [2, 4, 6, 8]
This comprehension iterates through numbers. It includes a number num in the even_numbers list only if the condition num % 2 == 0 (num is divisible by 2) is True.

Select only the strings with length greater than 3

words = [‘cat’, ‘hello’, ‘world’,’to’, ‘python’,’dog’]
long_words = [word for word in words if len(word) > 3]
print(long_words)

# Output: [‘hello’, ‘world’, ‘python’]
This comprehension filters the words list, keeping only those strings word where the length (len(word)) is greater than 3.

Nested List Comprehensions

Create a matrix (list of lists)

matrix = [[row, col] for row in range(3) for col in range(4)]
print(matrix)

Output: [[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1], [1, 2], [1, 3], [2, 0], [2, 1], [2, 2], [2, 3]]

This comprehension has nested loops. The outer loop (for row in range(3)) iterates over the rows, and the inner loop (for col in range(4)) iterates over the columns. For each combination of row and col, it creates a list [row, col] and adds it to the matrix.

Set Comprehensions

Without Comprehension (Traditional Loop)

unique_chars = set()
for char in “hello world”:
unique_chars.add(char)

print(unique_chars)

# Output: {‘l’, ‘d’, ‘o’, ‘e’, ‘r’, ‘w’, ‘h’}

With Set Comprehension

unique_chars_comp = {char for char in “hello world”}
print(unique_chars_comp)

# Output: {‘l’, ‘d’, ‘o’, ‘e’, ‘r’, ‘w’, ‘h’}
The set comprehension eliminates the need for the separate set() initialization and the add() method within the loop.
Set comprehensions are similar to list comprehensions, but they create sets (unordered collections with unique elements).

Get unique letters from a string

text = “hello world”
unique_letters = {char for char in text}
print(unique_letters)

# Output: {‘l’, ‘d’, ‘o’, ‘e’, ‘r’, ‘w’, ‘h’}
This comprehension iterates over each char in the string text. Since it’s a set comprehension, duplicates are automatically eliminated, resulting in a set containing only the unique letters.
You can use conditions and nested for loops within set comprehensions just like with list comprehensions.

Dictionary Comprehensions

Without Comprehension (Traditional Loop)

squares_dict = {}
for num in range(1, 6):
squares_dict[num] = num ** 2

print(squares_dict)

# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

With Dictionary Comprehension

squares_dict_comp = {num: num ** 2 for num in range(1, 6)}
print(squares_dict_comp)

# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
In the traditional loop approach, an empty dictionary squares_dict is initialized, and a for loop iterates through numbers from 1 to 5. Within the loop, the square of each number is calculated (num ** 2) and assigned as the value for the key num in the dictionary. In contrast, the dictionary comprehension achieves the same result in a single line by directly expressing the transformation: it iterates through the numbers and concisely inserts the key-value pairs (num: num** 2) into the new dictionary squares_dict_comp.
Dictionary comprehensions create dictionaries by mapping keys to values based on an expression.

Square the keys and values

numbers = {1: 1, 2: 4, 3: 9}
squared_dict = {k2: v2 for k, v in numbers.items()}
print(squared_dict)

# Output: {1: 1, 4: 16, 9: 81}
This comprehension iterates over the key-value pairs (k, v) in the numbers dictionary. For each pair, it squares both the key and the value and creates a new key-value pair in the squared_dict.

Create a dictionary from two lists

keys = [“a”, “b”, “c”]
values = [1, 2, 3]
my_dict = {k: v for k, v in zip(keys, values)}
print(my_dict)

# Output: {‘a’: 1, ‘b’: 2, ‘c’: 3}
The zip function pairs up the elements from the keys and values lists. The comprehension then creates a dictionary where each key from keys is mapped to its corresponding value from values.

Combining Conditions and Nested Loops

Map words to their lengths, only for words longer than 3 characters

word_lengths = {word: len(word) for word in words if len(word) > 3}
print(word_lengths)

# Output: {‘hello’: 5, ‘world’: 5, ‘python’: 6}
This comprehension iterates over each word in the words list. If a word’s length is greater than 3, the word is used as the key, and its length (len(word)) is used as the value in the resulting word_lengths dictionary.

]]>
498
loops https://edupoly.in/full-stack-training-in-hyderabad/loops/ Wed, 22 May 2024 07:55:24 +0000 https://edupoly.in/?p=423

Whenever we want to repeat some operation, we need loops. There are different types of looping techniques in Python. Firstly, let us go through the while loop. while loop runs or executes a piece of code repeatedly if a certain condition(or expression) evaluates to True. The execution will stop when the given condition(or expression) evaluates to False. The syntax of while is as follows:

while expression:

statement

Note that, just like if statements, indentation is necessary in while statements as well.

Let us see an example,

Here, initially the value of x is True. So, the expression x in line number 2 is satisfied. So, the “hi” in line number 3 will be printed. In the last line of the loop(line number 4), the value of x is set to False. After this, the loop tries to execute lines 3 and 4 again. But as the value of x is False, the expression fails at line number 2. At this point the loop stops. So, we get only one “hi” printed in the output. So, this piece of code is actually not repeating any operation. Let us take a more relevant example to understand loops.

Output:

hi

hi

hi

In this example, the value of x is initialized with 1 in line number 1. Then the condition is checked in line number 2 whether the value of x is less than 4 or not. The condition is satisfied and the loop proceeds to the execution of lines 3 and 4. It prints “hi” and increments the value of x. As the value of x is now 2, it again satisfies the condition and proceeds to line number 3 and 4. This will continue for values of x up to 3 because the express says x<4. After it prints “hi” for the third time, the value of x will be incremented and the value becomes 4 but the condition fails at this point and the loop stops. So, we get “hi” printed three times in the console. This is how the while loop works. 

Please note that if we don’t increment the value of x in line number 4, the code will go into an infinite loop as the value of x remains 1 and the condition is always satisfied.

The while loop also helps us to loop(or iterate) through sequence data types as well. For example, to loop through

string:

Output:

E

d

u

p

o

l

y

In the same way, the len() function can also be used with lists. So, lists can also be looped in a similar way:

Output:

1

5

2

7

3

9

But Python also provides us with a for loop to iterate or loop through sequences. It is easier to read and understand. For example,

Output:

E

d

u

p

o

l

y

Output:

1

4

2

6

3

7

These are the different basic looping techniques in Python. We will learn about more advanced looping techniques later on.

The range() function

The range function returns an object which can be iterated(an iterable). Let’s take a simple example:

range(5) returns an iterable object which when iterated gives us 0 to 4(excluding 5).

Let us combine this with a for loop to see the appropriate output.

Output:

0

1

2

3

4

Here, we can see that it prints 0 to 4 but not including 5. It starts from 0 by default.

We can also specify the starting point and ending point by passing two arguments to the range() function.

Output:

1

2

3

4

Here, 1 is the starting point and 4 is the ending point(not including 5).

We can also specify a step as a third argument to specify a different increment step. Let’s see it through an example:

Output:

1

3

5

7

9

We can also run a loop in the reverse direction if we use a negative step. This will decrement each value instead of incrementing it.

Output:

5

4

3

2

1

Here, the starting point is 5 and the ending point is 1(excluding 0) with a step -1. 

-1 means it will run in a negative direction by decrementing each value by 1.

Similarly, if we put -2 as a step, it will decrement each value by 2 at a time.

Output:

10

8

6

4

2

Interview Questions

Q. What is the primary purpose of a while loop in Python?

Ans. The primary purpose of a while loop is to repeatedly execute a block of code as long as a specified condition evaluates to True. The loop will terminate when the condition becomes False.

Q. Explain the syntax of a while loop and the role of indentation.

Ans. The syntax of a while loop is:

while expression:

    statement

expression: This is a condition that is evaluated before each iteration of the loop. If it’s True, the loop continues. If it’s False, the loop stops.

statement: This is the code block that is executed repeatedly as long as the expression is True.

Indentation: The statement block must be indented (typically four spaces) to indicate that it belongs to the loop. Proper indentation is crucial for Python to understand the structure of your code.

Coding Problems

Q. Write a Python program using a while loop to print numbers from 1 to 10.

Ans.

number = 1

while number <= 10:

    print(number)

    number += 1

Q. Write a Python program that calculates the sum of numbers from 1 to a given limit using a while loop.

Ans

limit = int(input(“Enter the limit: “))

number = 1

sum = 0

while number <= limit:

    sum += number

    number += 1

print(“Sum of numbers from 1 to”, limit, “is:”, sum)

Q. Write a Python program to calculate the factorial of a number using a while loop.

Ans.

num = int(input(“Enter a number: “))

factorial = 1

i = 1

while i <= num:

    factorial *= i

    i += 1

print(“Factorial of”, num, “is:”, factorial)

Q. Write a Python program that takes a number as input and prints its reverse using a while loop.

Ans

num = int(input(“Enter a number: “))

reversed_num = 0

while num > 0:

    digit = num % 10  

    reversed_num = (reversed_num * 10) + digit 

    num //= 10       

print(“Reversed number:”, reversed_num)

Q. Write a Python program to print the Fibonacci series up to a given number using a while loop.

Ans

limit = int(input(“Enter the limit: “))

a, b = 0, 1

count = 0

while count < limit:

    print(a, end=’ ‘)

    a, b = b, a + b

    count += 1 

Code snippet based problems

Q. In the provided code snippet:

x = 1

while x < 4:

    print(“hi”)

    x += 1

  1. Explain how the loop works and why it outputs “hi” three times.
  2. What would happen if you removed the line x += 1 from the code?

Ans.

  1. x is initialized to 1.
  2. The while loop checks if x is less than 4. Since it’s True, the loop starts.
  3. Inside the loop:
    1. “hi” is printed to the console.
    2. x is incremented by 1 (x += 1), so x becomes 2.
  4. The loop checks the condition again. Since x (now 2) is still less than 4, the loop continues.
  5. Steps 3 and 4 repeat until x becomes 4. At this point, the condition x < 4 is False, and the loop terminates.
  6. The output is “hi” printed three times because the loop iterates three times before the condition becomes False.

 If you remove the line x += 1, the value of x would remain 1 throughout the loop. The condition x < 4 would always be True, causing the loop to run indefinitely (an infinite loop).

Q. What is the issue with this code, and how would you fix it?

x = 5

while x > 0:

    print(“Hello”)

Ans. This code results in an infinite loop because the value of x never changes within the loop. To fix it, you need to decrement x in each iteration:

x = 5

while x > 0:

    print(“Hello”)

    x -= 1  # Decrement x

Q. What is the output of this code, and how can it be corrected to print the correct count?

count = 1

while count < 5:

    print(“Counting:”, count + 1)

    count += 1

Ans. The output will be:

Counting: 2 

Counting: 3 

Counting: 4 

Counting: 5

The code is printing count + 1 instead of count. To correct it:

count = 1

while count < 5:

    print(“Counting:”, count)  # Print count directly

    count += 1

]]>
423
Adding an Image to a Web Page https://edupoly.in/full-stack-training-in-hyderabad/adding-an-image-to-a-web-page/ Tue, 28 May 2024 12:25:15 +0000 https://edupoly.in/?p=700

Adding an Image to a Web Page

When an image is ready for the web, you need to use the correct markup to add it to your page, but you also need to know where to store your image.

Image location

You can store images for your website in several places. Image storage works best if it uses relative URLs stored somewhere on the website with your other HTML files. You can store images in the same root as your HTML files, which gets confusing if you have a lot of files, or you can create a graphics or images directory in the root file for your website.

Relative links connect resources from the same website. You use absolute links between resources on two different websites. 

Here are three compelling reasons to store images on your own site:

  • Control: When images reside on your site, you have complete control over them. You know your images aren’t going to disappear or change, and you can work to optimize them.
  • Speed: If you link to images on another site, you never know when that site may go down or respond unbelievably slowly. Linking to images on someone else’s site also causes the other site’s owner to pay for bandwidth required to display it on your pages — on another site!
  • Copyright: If you show images from another site on your pages, you may violate copyright laws. If you must do this, obtain permission from the copyright holder to store and display images on your website.

Using the <img> element

The image (<img>) element is an empty element (sometimes called a singleton tag) that enables you to specify the place on the page where you want your image to go.

An empty element uses only one tag, with neither a distinct opening nor a distinct closing tag.

The following markup places an image named leaf.jpg, which is saved in the same directory as the HTML file, between two paragraphs:

The output is displayed as follows in the browser:

A web browser replaces the img element with the image file provided as the value for the src attribute. The src attribute is like the href attribute that you use with an anchor (<a>) element. The src attribute specifies the location for the image you want to display on your page. The preceding example points to an image file in the same folder as the HTML file referencing it.

]]>
700
The role of images in a webpage https://edupoly.in/full-stack-training-in-hyderabad/the-role-of-images-in-a-webpage/ Tue, 28 May 2024 12:20:36 +0000 https://edupoly.in/?p=696

The role of images in a webpage

Web-page designers use images to deliver important information, direct site navigation, and contribute to overall look and feel on a web page. Images in websites may be logos or clickable navigation aids, or they may display content; they can also make a page look prettier or serve to unify or illustrate a page’s theme. A perfect example of the many different ways images can enhance and contribute to web pages is the Edupoly home page at https://edupoly.com, shown below, where the Edupoly logo, photos, and a nice header or navbar appear to good effect. When used well, images are a key element of page design. When used poorly, though, they can make a page unreadable, unintelligible, or frustrating.

]]>
696
Specifying locations in web pages https://edupoly.in/full-stack-training-in-hyderabad/specifying-locations-in-web-pages/ Tue, 28 May 2024 12:05:35 +0000 https://edupoly.in/?p=692

Specifying locations in web pages

Locations within web pages can be marked for direct access by links on:

  • The same page.
  • The same website.

Keep these considerations in mind when adding links to web pages:

  • Several short pages may present information more conveniently for readers than one long page with internal links.
  • Links within large pages work nicely for quick access to directories, tables of contents, and glossaries.
  • Intra document linking works best on your own website, where you can create and control the markup.

When you link to spots on someone else’s website, you’re at its manager’s mercy because that person controls linkable spots. Your links will break if a site designer removes or renames a spot to which you link. 

Naming link locations

To identify and create a location within a page for direct access from other links, use an empty anchor element with the name attribute, like this:

The id attribute also works as an anchor element. It’s often cleaner to use this method depending on your page design approach. (If you use id attributes for CSS, it may be easier to remember and more consistent overall). The anchor element that marks the spot doesn’t affect the appearance of any surrounding content. You can mark spots wherever you need them without worrying about how your pages look (or change) as a result.

Linking within the same page

Links can help users navigate a single web page. Intra document hyperlinks include such familiar features as:

  • Back to Top links.
  • Tables of contents.

An intra document hyperlink, also known as a named document link, uses a URL like this:

The hash sign (#) indicates that you’re pointing to a spot on the same page, not on another page.

The following code shows how two anchor elements combine to link to a spot on the same page. (Documents that use intra document links are usually longer. This document is short so you can easily see how to use the top anchor element)

.https://stackblitz.com/edit/web-platform-qq2xjc?embed=1&file=index.html&hideDevTools=1&hideExplorer=1&hideNavigation=1

We can see how this HTML markup appears in a web browser. If the user clicks the Back to Top link, the browser jumps back to the top spot — marked by <a name=”top”></a>. The text for this example is short, but you can see how it works by resizing your browser window (making it tall and narrow) to display only two or three words per line of text.

Linking within the same website

You can combine intra document and inter document links to send visitors to a spot on a different web page on your site. Thus, to link to a spot named descriptions on a page named home.html on your site, use this markup:

Linking on other websites

If you know that a page on another site has spots marked, you can use an absolute URL to point to a particular spot on that page, like this:

Be sure to check all links regularly to catch and fix the broken ones.

]]>
692
Customizing Links https://edupoly.in/full-stack-training-in-hyderabad/customizing-links/ Tue, 28 May 2024 12:01:02 +0000 https://edupoly.in/?p=688

Customizing Links

You can customize links to:

✓ Open linked documents in new windows

✓ Link to specific locations within a web page of your own

✓ Link to items other than HTML pages, such as

  • Portable Document Format (PDF) files
  • Compressed files
  • Word processing documents

Opening new windows

The web works because you can link pages on your website to pages on other people’s websites by using a simple anchor element. When you link to someone else’s site, though, you send users away from your own site. To keep users on your site, HTML can open the linked page in a new window or in a new tab inside the same browser window. The simple addition of the target attribute to an anchor element opens that link in a new browser window (or tab) instead of opening it in the current window:

When you give a target attribute a _blank value, this tells the browser to do the following:

1. Keep the linking page open in the current window.

2. Open the linked page in a new window or tab.

]]>
688
Exploring link options https://edupoly.in/full-stack-training-in-hyderabad/exploring-link-options/ Tue, 28 May 2024 11:56:27 +0000 https://edupoly.in/?p=684

Exploring link options

You can link to a variety of online resources:

  • Other HTML pages (either on your website or on another website)
  • Different locations on the same HTML page
  • Resources that aren’t even HTML pages at all, such as e-mail addresses, pictures, and text files or downloads for visitors

Link locations, captions, and destinations exert a huge influence on how site visitors perceive links. The kind of link you create is determined by what you link to and how you formulate your link markup.

Absolute links

An absolute link uses a complete URL to connect browsers to a web page or online resource. Links that use a complete URL to point to a resource are called absolute because they provide a complete, stand-alone path to another web resource. When you link to a page on someone else’s website, the web browser needs every bit of information in the URL to find that page. The browser starts with the domain in the URL and works its way through the path to a specific file. When you link to files on someone else’s site, you must always use absolute URLs in the href attribute of the anchor element. 

Here’s an example:

http://www.website.com/directory/page.html

Relative links

A relative link uses a kind of shorthand to specify a URL for a resource you’re pointing to.

Use the following guidelines with relative links in your HTML pages:

  • Create relative links between resources in the same domain.
  • Because both resources are in the same domain, you may omit domain information from the URL.

A relative URL uses the location of the resource you link from to identify the location of the resource you link to (for example, page.html). If you use relative links on your site, your links still work if you change:

  • Servers.
  • Domain names.

Simple links

You can take advantage of relative URLs when you create a link between pages on the same website. If you want to make a link from http://www.mysite.com/home.html to http://www.mysite.com/about.html, you can use this simplified, relative URL in an anchor element on home.html:

<p>Learn more <a href=”about.html”>about</a> our company.</p>

When a browser sees a link without a domain name, the browser assumes that the link is relative and uses the domain and path from the linking page to find the linked page. The preceding example works only if home.html and about.html are in the same directory, though.

Site links

As your site grows more complex and you organize your files into various folders, you can still use relative links. However, you must provide additional information in the relative URL to help the browser find files that don’t reside in the same directory as the file from which you’re linking. Use ../ (two periods and a slash) before the filename to indicate that the browser should move up one level in the directory structure.

The markup for this directory navigation process looks like this:

<a href=”../docs/home.html>Documentation home</a>

The notation in this anchor element instructs the browser to take these steps:

1. Move up one folder from the folder the linking document is stored in.

2. Find a folder called docs.

3. Inside that folder, find a file called home.html.

When you create a relative link, the location of the file to which you link is always relative to the file from which you link. As you create a relative URL, trace the path a browser takes if it starts on the page you’re linking from to get to the page to which you’re linking. That path defines the URL you need.

]]>
684
Basic links https://edupoly.in/full-stack-training-in-hyderabad/basic-links/ Tue, 28 May 2024 11:50:12 +0000 https://edupoly.in/?p=680

Basic links

To create a link, you need

  • A web address (called a Uniform Resource Locator; URL) for the website or file that’s your link target. This usually starts with http://.
  • Some text in your web page to label or describe the link. Make sure that the text you use says something useful about the resource being linked.
  • An anchor element (<a>) with an href attribute to bring it all together.

The element to create links is called an anchor element because you use it to anchor a URL to some text on your page. When users view your page in a browser, they can click the text to activate the link and visit the page whose URL you specified in that link. You insert the full URL in the href attribute to tell the link where to go.You can think of the structure of a basic link as a cheeseburger (or your preferred vegan substitute). The URL is the patty, the link text is the cheese, and the anchor tags are the buns. Tasty, yes?

For example, if you have a web page that describes HTML standards, you may want to refer web surfers to the World Wide Web Consortium (W3C) — the organization that governs all things related to HTML standards. 

A basic link to the W3C website, www.w3.org, looks like this:https://stackblitz.com/edit/web-platform-ti7mqs?embed=1&file=index.html&hideDevTools=1&hideExplorer=1&hideNavigation=1

You specify the link URL (http://www.w3.org) in the anchor element’s href attribute. The text (World Wide Web Consortium) between the anchor element’s opening and closing tags (<a> and </a>) describes the link.

]]>
680