Python Tutorial https://edupoly.in Indepth Training on ReactJS, Angular, Javascript, MERN,MEAN,Python,Java,Devops,AWS Sat, 01 Jun 2024 15:02:39 +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 Python Tutorial 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
Python Installation https://edupoly.in/full-stack-training-in-hyderabad/python-installation/ Tue, 21 May 2024 12:45:21 +0000 https://edupoly.in/?p=368

Installation

Visit the official Python download page: https://www.python.org/downloads. Download the appropriate installer based on your system architecture and install it.

Microsoft Store provides a simple alternative for installing Python on Windows. Look for the Python app published by the Python Software Foundation. The latest stable version is generally recommended.

Click on the desired version and then click “Get” to download and install.

Verify Python Installation

Open Command Prompt

Type python –version and press Enter.

If successful, it displays the installed Python version.

Install an IDE or code editor

There are lots of code editors or IDE for Python like PyCharm, Visual Studio Code, Sublime Text, Eclipse, Jupyter, Spyder etc.

Visit one of their official websites and download the latest stable version.

For example, to install Microsoft Visual Studio Code, visit https://code.visualstudio.com/ and download the latest release for your operating system.

After downloading is complete, run the installer to install Microsoft Visual Studio Code in your system.

Start Coding in Python

Create a new directory

Open the directory.

In the address bar, type cmd and press Enter.

In the terminal, type code . (code<space><dot>)

You will see that the Visual Studio Code application will be opened.

In the left side-panel, click on the new file() icon to create a file. Create a file with .py extension. The .py extension indicates that it is a python file and requires a python interpreter to run this file. In the file, you can now start writing python code.

Write the following lines of code in the file:
print(1+2)

print(“hello”)

Our python file is ready to be run. When you install Python, it actually installs a Python interpreter which is needed to run these files.

Now open a terminal in Visual Studio Code by pressing Ctrl+J or Ctrl+`.

Type the following command in the terminal and press Enter:

python filename.py

Here, filename.py is the name of the file that you want to run. If the filename is myfile.py, then the command should be
python myfile.py.

We should be able to see the output of the Python code in the terminal as follows:
3

hello

Interview Questions:

Q. What is the recommended way to install Python on Windows, and why might someone choose that method?

Ans. The recommended way is to download the installer from the official Python website (python.org) as it ensures you get the latest stable version directly from the source. However, using the Microsoft Store can be a simpler alternative, especially for beginners, as it handles the installation process automatically.

Q. How can you confirm that Python has been successfully installed on your system?

Ans. Open your command prompt (or terminal) and type python –version. If Python is installed correctly, it will display the installed version number.

Q. What’s the purpose of a code editor or IDE (Integrated Development Environment) in the context of Python programming?

Ans. Code editors and IDEs provide a convenient environment for writing, editing, and running Python code. They offer features like syntax highlighting, code completion, debugging tools, and project management, which make development easier and more efficient.

Q. Could you walk me through the steps of creating and running a simple Python program using Visual Studio Code, as described in the article?

Ans. 

  1. Create a new directory for your project.
  2. Open that directory in Visual Studio Code.
  3. Create a new file with a .py extension (e.g., myfile.py).
  4. Write your Python code in this file (e.g., print(“Hello, world!”)).
  5. Open the terminal in Visual Studio Code.
  6. Type python myfile.py and press Enter to run the code.

Q. What does the .py file extension signify, and why is it important for Python code?

Ans. The .py extension indicates that the file contains Python code. It’s important because it helps the operating system and code editors identify the file type and associate it with the Python interpreter for execution.

Q. Explain the role of the Python interpreter in running Python code files.

Ans. The Python interpreter is a program that reads and executes Python code line by line. It translates the human-readable code into instructions that the computer’s hardware can understand and execute.

]]>
368
Numbers https://edupoly.in/full-stack-training-in-hyderabad/numbers/ Tue, 21 May 2024 12:48:21 +0000 https://edupoly.in/?p=369

In Python, there are different types of numbers.

Let’s say,

num = 45

Here, 45 is a number of type integer which means it has no decimal part. This type of number is known as int in Python. In Python, int represents whole numbers of unlimited length, positive or negative.

On the other hand,

price  = 25.99

Here, 25.99 is a floating point  number which can also be called a decimal number.

It contains an integer part as well as a decimal part separated by a decimal. This type of number is known as float in Python. In Python, float represents floating-point numbers with limited precision (around 15 decimal places)

Python also has support for complex numbers. Complex numbers are those numbers which can be represented in the form of x+yj, where j is the imaginary unit and x and y are real numbers. In Python, the imaginary unit can be represented by J or j.

comp = 5+4j

numval = 2+5J

Both these are valid complex numbers in Python.

Interview Questions

Q. What is the difference between an integer and a floating-point number in Python?

Ans.  In Python, an integer (int) is a whole number with no decimal part (e.g., 45). A floating-point number (float) is a number with both an integer and decimal part (e.g., 25.99). Integers have unlimited length, while floats have limited precision (about 15 decimal places).

Q.  What is a complex number in Python, and how is it represented?

Ans. A complex number in Python has both a real and imaginary part, taking the form x + yj, where x and y are real numbers, and j is the imaginary unit (√-1). Complex numbers are represented using either ‘j’ or ‘J’ after the imaginary part (e.g., 5 + 4j or 2 + 5J).

Q. If you wanted to store the number -123456789012345, which data type would you choose and why?

Ans. You would choose the int data type. While this is a large number, Python integers can be of any length, positive or negative, making it suitable for storing large whole numbers.

]]>
369
Data Types in Python https://edupoly.in/full-stack-training-in-hyderabad/data-types-in-python/ Tue, 21 May 2024 12:55:24 +0000 https://edupoly.in/?p=375

Data types

Python offers a variety of data types to store and manipulate different kinds of information. Knowing these types and their specific characteristics is crucial for writing effective and efficient Python code. Here’s a breakdown of the essential data types:

Numeric Types:

  • int (integer): Represents whole numbers of unlimited length, positive or negative. Examples: 10, -723, 0.
  • float (floating-point): Represents floating-point numbers with limited precision (around 15 decimal places). Examples: 3.14159, 9.81, -2.5.
  • complex: Represents complex numbers in the form x + yj, where j is the imaginary unit and x and y are real numbers. Examples: 3 + 2j, 1.5 – 4.7j.

Sequence Types:

  • list: An ordered, mutable collection of items, allowing duplicates. Items can be of different data types. Examples: [1, “hello”, 3.14], [“apple”, “banana”, “apple”].
  • tuple: An ordered, immutable collection of items. Items can be of different data types. Once created, elements cannot be changed. Examples: (1, “hello”, 3.14), (“orange”, “grape”).
  • str (string): Represents sequences of characters (text). Strings are immutable. Examples: “Hello, world!”, “42”, ”.

Mapping Type:

dict (dictionary): An unordered collection of key-value pairs. Keys must be unique and immutable (e.g., strings, numbers, tuples), while values can be of any data type. Examples: {“name”: “Alice”, “age”: 30}, {“fruit”: “banana”, “count”: 2}.

Set Types:

  • set: An unordered collection of unique items. Items can be of any data type, but must be hashable (meaning they can be used as dictionary keys). Examples: {1, 2, 3, 4}, {“apple”, “banana”}.
  • frozenset: An immutable set. Once created, its items cannot be changed. Examples: frozenset({1, 2, 3, 4}), frozenset((“a”, “b”, “c”)).

Boolean Type:

bool: Represents Boolean values: True or False. Used for logical conditions and comparisons. Examples: True, False.

None Type:

None: Represents the absence of a value. Often used as a placeholder or to indicate that a variable has no assigned value. Example: None.

The type() function

The type() function returns the type of the data passed to it.

For example,

type(35)  #int

type(25.45)  #float

type(“hello”)  #str

type(True)  #bool

Interview Questions

Q. Explain the fundamental differences between mutable and immutable data types in Python, providing examples of each. How does the immutability of a data type influence its usage in Python programs?

Ans:

Mutable: Mutable objects can be changed after they are created. Examples include lists, dictionaries, and sets. You can add, remove, or modify elements within them.

Immutable: Immutable objects cannot be changed once created. Examples include numbers (int, float, complex), strings, tuples, and frozensets. Any operation that appears to modify them actually creates a new object.

The immutability of a data type influences its usage. Immutable objects are generally safer to use as keys in dictionaries or elements in sets, as their values won’t change unexpectedly. They can also be used to represent constant values that should not be modified.

Q. Discuss the scenarios where you would choose a list over a tuple, and vice-versa. What factors influence your decision when selecting between a set and a list?

Ans:

List vs. Tuple: Use a list when you need an ordered collection of items that you might need to change (add, remove, modify). Use a tuple when you have an ordered collection of items that should remain constant throughout the program.

Set vs. List: Choose a set when you need a collection of unique items, and order doesn’t matter. Sets are also efficient for membership testing (checking if an item exists in the set). Lists are used when you need to maintain the order of items and allow duplicates.

Q.  Describe the structure and usage of dictionaries in Python. What are the advantages of using dictionaries compared to other data types? Explain the concept of “hashability” and its relevance to dictionary keys?

Ans:

Structure: Dictionaries store data as key-value pairs. Each key is unique and associated with a corresponding value. Keys must be hashable (i.e., immutable), while values can be of any data type.

Advantages: Dictionaries provide fast lookups based on keys, making them efficient for storing and retrieving data by name or identifier. They are also flexible and can hold values of different types.

Hashability: Hashability means an object can be converted into a unique hash value. This hash value is used to determine the object’s position in a hash table, enabling fast dictionary lookups. Immutable objects like strings, numbers, and tuples are naturally hashable.

Q. What is the purpose of the None type? How does it differ from an empty string or a zero value? Provide examples where None would be used effectively?

Ans:

Purpose of None: The None type represents the absence of a value. It’s different from an empty string (“”) or zero (0), which are actual values. None is often used:

  • As a default return value for functions that don’t explicitly return anything.
  • To indicate that a variable has not yet been assigned a meaningful value.
  • As a placeholder for optional function arguments.

Q. Given the variable price = 25.99, what would be the output of type(price) and why?

Ans: The output of type(price) would be <class ‘float’>. This is because the value 25.99 has a decimal point, indicating it’s a floating-point number, which is represented by the float type in Python.

]]>
375
Operators https://edupoly.in/full-stack-training-in-hyderabad/operators/ Tue, 21 May 2024 12:54:18 +0000 https://edupoly.in/?p=374

Python Operators

Python describes a set of operators that can be used to manipulate data values. The operators range from assignment operators and mathematical operators (such as addition and subtraction) to relational operators and equality operators.

Assignment operator

The assignment operator assigns the value of the operand on the right to the operand on the left.

num = 10 # The value of 10 is assigned to variable num

a = 20      # The value of 20 is assigned to variable a

b = a        # The value of variable a is assigned to variable b

Arithmetic operators

Arithmetic operators perform mathematical operations on numeric operands.

The addition(+), subtraction(-) and the multiplication(*) operators work the same way as they do in mathematics.

The difference is with division techniques. There are three types of division in Python.

Firstly,

This is known as classical division. Classical division always returns a floating point number.

To discard the decimal part, we can go with floor division denoted by a double slash(//) as follows:

On the other hand, if you want to find the remainder of a division, then you have to use the % operator  as follows:

Augmented assignment operators

You can combine assignment operators with other operators as a shorthand method of assigning the result of an expression to a variable. For example, the following two examples have the same result:

Similarly,

Comparison operators

Comparison operators test for equality or difference between operands and return a True or False(bool) value. A complete list of the Python comparison operators is given below:

==Equal toa==b
!=Not equal toa!=b
<Less thana<b
<=Less than or equal toa<=b
>Greater thana>b
>=Greater than or equal toa>=b

For example,

Logical operators

Logical operators evaluate a logical expression for truthiness or falseness. There are three logical operators:

  • and
  • or
  • not

When we talk about truthy or falsy values, there are a lot of possibilities. For example,

False is a falsy value

0(and 0.0) is a falsy value

An empty string(”) is a falsy value

An empty list([ ]) is a falsy value

An empty dictionary or set({ }) is a falsy value

An empty tuple(()) is a falsy value

On the contrary,

True is a truthy value

Any number(int or float) other than 0(or 0.0) is a truthy value

Any non-empty string is a truthy value

Any non-empty list is a truthy value

Any non-empty dictionary or set is a truthy value

Any non-empty tuple is a truthy value

and operator

The logical and operator is a binary operator which means that it acts upon two operands. It checks whether both the operands(or values) are truthy or not.

For example,

The and operator returns the value of the first falsy operand encountered when evaluating from left to right, or the value of the last operand if they are all truthy.

or operator

The logical or operator checks whether one of the operands(or values) is truthy or not.

For example,

The or operator returns the value of the first truthy operand encountered when evaluating from left to right, or the value of the last operand if they are all falsy.

Interview Questions

Q. What are the three types of division in Python, and how do they differ?

Ans.

Classical Division (/): Returns a floating-point number, even if the operands are integers. Example: 10 / 3 = 3.3333

Floor Division (//): Returns the quotient as an integer, discarding any remainder. Example: 10 // 3 = 3

Modulo Division (%): Returns the remainder of a division. Example: 10 % 3 = 1

Q. Explain the concept of augmented assignment operators and provide two examples?

Ans. Augmented assignment operators combine an arithmetic operation with assignment. They offer a concise way to update a variable’s value.

Examples:

  • x += 5 is equivalent to x = x + 5
  • y *= 2 is equivalent to y = y * 2

Q. Which operator would you use to check if two variables have the same value? How would you check if they are not equal?

Ans. To check for equality, use the == operator (e.g., a == b).

To check for inequality, use the != operator (e.g., a != b).

Q. What is the difference between the and and or logical operators?

Ans.

and: Returns True only if both operands are truthy. Otherwise, it returns the first falsy value encountered or the last value if all are truthy.

or: Returns True if at least one operand is truthy. Otherwise, it returns the last falsy value encountered or the last value if all are falsy.

Q. Provide examples of falsy values in Python?

Ans

  • False
  • 0 (and 0.0)
  • Empty strings (“”)
  • Empty lists ([])
  • Empty dictionaries ({})
  • Empty sets ({})
  • Empty tuples (())

Coding Problems

Q. Calculate the area of a triangle with base = 10 and height = 8.

Ans

base = 10

height = 8

area = (base * height) / 2

print(area)  # Output: 40.0

Q. Given the variable x = 5, increment its value by 3 using an augmented assignment operator.

Ans

x = 5

x += 3

print(x)  # Output: 8

Q. Given two variables a = 10 and b = 5, calculate their sum, difference, product, and quotient.

Ans

a = 10

b = 5

sum = a + b

difference = a – b

product = a * b

quotient = a / b

print(sum)        # Output: 15

print(difference) # Output: 5

print(product)    # Output: 50

print(quotient)   # Output: 2.0

Q. Determine if 15 is greater than or equal to 10 and store the result (True/False) in a variable named result.

Ans

result = 15 >= 10

print(result)  # Output: True

Q. Given p = True and q = False, evaluate the expression p and q.

Ans

p = True

q = False

result = p and q 

print(result)  # Output: False 

Q. Given the strings str1 = “hello” and str2 = “world”, create a new string by concatenating them and store it in a variable named combined.

Ans

str1 = “hello”

str2 = “world”

combined = str1 + str2

print(combined)  # Output: helloworld

]]>
374
Sequence Data types part 3 – Tuples https://edupoly.in/full-stack-training-in-hyderabad/sequence-data-types-part-3-tuples/ Sat, 01 Jun 2024 14:56:03 +0000 https://edupoly.in/?p=779

Tuples

In Python, tuples are an ordered and immutable sequence of items. This means that once you create a tuple, its values cannot be changed, and the order of items remains fixed. Tuples are incredibly useful when you need to store a collection of related values that should not be modified during your program’s execution.

Creating Tuples

Tuple Literals:

The simplest way to create a tuple is by enclosing a comma-separated sequence of items within parentheses:

my_tuple = (10, 20, ‘apple’, 3.14)

print(my_tuple)   # Output: (10, 20, ‘apple’, 3.14)

my_tuple is a variable assigned a tuple containing integer, string, and float values.

Commas are essential, even when creating a tuple with a single item.

Explicit Typecasting (The tuple() Constructor):

You can create a tuple by passing any iterable (like a list or string) to the tuple() constructor:

numbers = [1, 2, 3, 4]

numbers_tuple = tuple(numbers)

print(numbers_tuple)  # Output: (1, 2, 3, 4)

The tuple() function converts the numbers list into a tuple.

Singleton Tuples:

To create a tuple with just one element, you need to include a trailing comma:

singleton_tuple = (5,) 

print(singleton_tuple)  # Output: (5,)

The comma after 5 is essential to differentiate the tuple from a parenthesized expression.

Indexing and Accessing Elements

Tuples are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on. You can access elements using square brackets:

fruits = (‘apple’, ‘banana’, ‘orange’)

print(fruits[1])   # Output: banana (Positive index)

print(fruits[-2])  # Output: banana (Negative index)

Positive indexing: Starts from 0 (the beginning) of the tuple.

Negative indexing: Starts from -1 (the end) of the tuple.

IndexError: Trying to access an index beyond the tuple’s length results in an IndexError.

Membership Testing

You can use the in and not in operators to check if a value exists within a tuple:

colors = (‘red’, ‘green’, ‘blue’)

print(‘yellow’ in colors)   # Output: False

print(‘green’ not in colors) # Output: False

len() Function

The len() function returns the number of elements in a tuple:

numbers = (1, 2, 3, 4, 5)

print(len(numbers))  # Output: 5

Immutability

Tuples are immutable, meaning their elements cannot be changed once created:

numbers = (1, 2, 3)

numbers[0] = 10   # Raises a TypeError (tuples are immutable)

Tuple Slicing

Slicing allows you to extract a portion of a tuple.

my_tuple = (1, 2, 3, 4, 5, 6)

print(my_tuple[2:5])  # Output: (3, 4, 5) 

The slice notation [start:end] creates a new tuple containing elements from index start up to, but not including, index end.

Concatenation

tuple1 = (1,2,3)

tuple2 = (4,5,6)

print(tuple1+tuple2) # Output: (1, 2, 3, 4, 5, 6)

The + operator concatenates two tuples to create a new tuple.

Nested Tuples

Tuples can contain other tuples:

nested_tuple = (1, 2, (‘a’, ‘b’), 3)

print(nested_tuple[2][1])   # Output: b (accessing ‘b’ in the inner tuple)

Looping Through Tuples

colors = (‘red’, ‘green’, ‘blue’)

for color in colors:

    print(color)

Output: red green blue

The enumerate() Function

The enumerate() function allows you to iterate over a tuple while getting both the index and value of each element:

colors = (‘red’, ‘green’, ‘blue’)

for index, color in enumerate(colors):

    print(f”Index {index}: {color}”)

Tuple Methods

count(x):

The count(x) method returns the number of times the value x appears within the tuple.

numbers = (1, 2, 3, 2, 5, 2)

count_of_two = numbers.count(2) 

print(count_of_two)  # Output: 3

numbers.count(2) is called to find how many times the value 2 appears in the tuple numbers.

The result, 3, is stored in count_of_two and then printed.

index(x):

The index(x) method returns the index (position) of the first occurrence of the value x within the tuple. If the value isn’t found, it raises a ValueError.

fruits = (‘apple’, ‘banana’, ‘orange’, ‘banana’)

banana_index = fruits.index(‘banana’)

print(banana_index)   # Output: 1

fruits.index(‘banana’) is called to find the index of the first ‘banana’ in the tuple.

The index, 1, is stored in banana_index and then printed.

Important Note: Since tuples are ordered, the index() method always returns the index of the leftmost occurrence of the value.

]]>
779
Sequence Data types part 2 – Lists https://edupoly.in/full-stack-training-in-hyderabad/sequence-data-types-part-2-lists/ Sat, 01 Jun 2024 14:38:29 +0000 https://edupoly.in/?p=775

Lists

Lists are a type of data type which can store more than one value(collection of values) at a time. It is denoted by values enclosed within square brackets([ ]).

Output:

<class ‘list’>

Lists can store data of any type. It is not mandatory to store data collections of the same type. That means lists can be homogenous or heterogenous.

Lists support indexing which means we can access each element using numeric indices which start from 0. 

For example,

Output:

1

23

4

5

76

Lists support the len() function

Output:

5

Iterating lists

Lists can be iterated using while loop when combined with the len() function

Output:

1

23

4

5

76

But Python has provided us with a better approach to loop through sequences. The approach is to use a for loop with a range() function.

Output:

1

23

4

5

76

But the for loop in Python can smartly detect a sequence data type and can directly access the elements of a sequence like a list as follows:

Output:

1

23

4

5

76

Accessing or modifying elements using index

We already know that elements of a list can be accessed using index values.

They also support negative indices. An index of -1 points to the last element of a list, -2 points to the second last element and so on.

But Python also allows modifying elements using the index values.

For example,

Here, the number at the first index is replaced with a new number that is 21. This way we can modify the elements of a given list. That’s why lists are said to be mutable which means they can be modified.

Lists also support slicing just like strings.

Output:

[1, 23]

[5]

[23, 4, 5]

[23, 4, 5]

This helps us to slice a list  starting from the first specified index up to the second specified index but not including the second index just like strings.

If we omit the first value, it slices from the first index. And if we omit the last value, it slices up to the last index.

Output:

[1, 23, 4]

[5, 76]

Basic list methods

Let us now see some basic list methods which will help us to modify and manipulate lists

list.append()

Let’s say we have a list as follows:

numbers = [1,23,4,5,76]

If we want to add a  new element to the list, we need to use the append() method as follows:

Output:

[1, 23, 4, 5, 76, 44]

Please note that the append() method always inserts an element to the end of the list. But if we want to insert elements at a particular index, we need to use the insert() method.

list.insert()

The insert method takes two arguments: first, the index at which we want to insert an element and second, the element that we want to insert.

Output:

[1, 23, 99, 4, 5, 76]

Here, the insert() method is inerting the value 99 at index 2 of the numbers list. Hence, upon printing, we get the updated list.

list.pop()

Next, if we want to remove an element from the end, we can use the pop() method as follows:

Output:

[1, 23, 4, 5]

But the pop() method can also help us to remove an element from a particular index. For that, we need to pass the index to the pop() method as follows:

Output:

[1, 23, 5, 76]

Here, the pop() method is accepting index 2 as argument and removing the value at index 2(the value 4) of the list.

list.remove(val)

Let us consider a different scenario where we want to remove a particular element from a given list without knowing the index. In this case, we have to use the remove() method as follows:

Output:

[1, 23, 4, 76]

Here, we are passing the value(not the index) to be removed to the remove() method. As the value 5 was passed, it removed the 5 from the list. If we pass a value which is not present in the list, we get a ValueError as follows:

Output:
ValueError: list.remove(x): x not in list

list.count()

The list.count() method will help us to count the number of occurrences of a particular value in a list. For example,

Interview Questions

Q. What is a list in Python, and how is it represented?

Ans. A list in Python is a versatile data structure that can store a collection of values. These values can be of different data types (homogeneous or heterogeneous). Lists are represented by enclosing the elements within square brackets [].

Q. How do you access elements within a list?

Ans. Elements within a list are accessed using indexing. Each element is associated with a numerical index starting from 0. For example, my_list[2] would access the third element in the list. Lists also support negative indexing, where my_list[-1] refers to the last element.

Q. Explain list mutability and how to modify elements.

Ans. Lists are mutable, meaning their contents can be modified after creation. Elements can be changed using their index: my_list[0] = 10 would replace the first element with the value 10.

Q. Describe two ways to iterate over a list in Python.

Ans. Using a for loop directly: It iterates over each element in the list automatically:

my_list = [23,12,45,76]

for item in my_list:

    print(item)

Using a while loop and len(): This involves using a counter variable and the len() function to determine the list’s length.

i = 0

while i < len(my_list):

    print(my_list[i])

    i += 1 

Q. What is slicing in the context of lists, and how does it work?

Ans. Slicing is a way to extract a portion of a list. It’s done by specifying a start and end index within square brackets, separated by a colon [start:end]. The resulting slice includes elements from the start index up to, but not including, the end index. Omitting the start index starts from the beginning, and omitting the end index goes to the end of the list.

my_list = [1, 23, 4, 5, 76]

print(my_list[1:3])  # Output: [23, 4]

Q. What is the purpose of the len() function when working with lists?

Ans. The len() function returns the number of elements in a list. This is useful for iterating through a list using a while loop or determining the size of a list before performing other operations.

Q. When iterating over a list, what is the advantage of using a for loop over a while loop?

Ans. A for loop is generally preferred for list iteration because it’s more concise, easier to read, and less error-prone. It automatically handles the index and directly accesses each element, whereas a while loop requires manually managing a counter variable.

Q. If you wanted to retrieve a sublist containing the first three elements from a list, how would you achieve this using slicing?

Ans. You can use slicing to retrieve a sublist containing the first three elements. The syntax would be my_list[0:3]. This would return a new list containing the elements at index 0, 1, and 2.

Q. What happens if you try to access an element at an index that doesn’t exist within the list?

Ans. If you try to access an element at an index that is out of range (either negative and too large or positive and exceeding the list’s length), Python will raise an IndexError exception.

Q. Explain the difference between the following two slicing operations: my_list[1:4] and my_list[:4].

Ans

  • my_list[1:4] will return a new list containing the elements starting from index 1 (the second element) up to, but not including, index 4.
  • my_list[:4] will return a new list containing the elements starting from the beginning of the list (index 0) up to, but not including, index 4. Effectively, this returns the first four elements of the list.

Q. How would you add a new element to the end of a list?

Ans. To add a new element to the end of a list, you can use the append() method. For example:

my_list = [1, 2, 3]

my_list.append(4)  

print(my_list)  # Output: [1, 2, 3, 4]

Q. What’s the difference between the append() and insert() methods when working with lists?

Ans

  • append() adds a new element to the end of the list.
  • insert() allows you to add a new element at a specific index within the list. It takes two arguments: the index and the element to insert.

Q. If you wanted to remove the last element from a list, which method would you use?

Ans. To remove the last element, you would use the pop() method without any arguments. This removes and returns the last element.

Q. Explain how to remove a specific element from a list by its value.

Ans. You can use the remove() method to remove the first occurrence of a specific value from a list. For example:

my_list = [1, 2, 3, 2]

my_list.remove(2) 

print(my_list)  # Output: [1, 3, 2] 

Q. How would you determine how many times a particular value appears in a list?

Ans. The count() method returns the number of times a specific value occurs in a list. For example:

my_list = [1, 2, 3, 2]

count_of_two = my_list.count(2)

print(count_of_two)  # Output: 2

Code snippet based questions

Q. Analyze the following code snippet and explain the output:

numbers = [10, 20, 30, 40]

numbers[1] = 25

print(numbers[1])

Ans. The output of this code will be 25. The code first creates a list called numbers and then modifies the element at index 1 (the second element) to have the value 25. Finally, it prints the value at index 1, which is now 25.

my_list = [5, 10, 15, 20]

Q. What will this code snippet print?

print(my_list[-2:]) 

Ans. This will print [15, 20]. The slicing operation [-2:] means to start from the second to last element and go until the end of the list.

Q. Examine the following code and identify any potential errors:

fruits = [‘apple’, ‘banana’, ‘orange’]

fruits.remove(‘grape’)

Ans. This code will raise a ValueError because the remove() method tries to remove the value ‘grape’, which does not exist in the list.

]]>
775