× About Us How it works Pricing Student Archive Subjects Blog Contact Us

What are arrays in python? 

In general terms, Python array is a collection of elements having same datatype or typecodes. It can hold more than one value with the same name. 

For example: If you want to marks of three students we generally use three variables, but what if the number ranges beyond capacity say 300. 

The answer to this is an array! 

You can easily traverse, append, remove and do all sorts of operations on a similar collection of data.  

As such Python does not support array, it supports lists. We need to import the array module for using arrays. 

Let’s check some terms used in python array. 

  • Element: item stored in an array are called element. 
  • Index: The location of the element in the array is called index. The first element of the python array has an index 0. 

Now, Let’s have a look how array is initialized or declared in  a python program  

from array import * 

nameof thearray = array(datatype, [Initializers]) 

Datatype stands for what type of value the array will hold such as integer, float etc.  

There are mainly 7 types of datatypes or typecodes. 

Datatype  Type/Value  Size 
b  Signed Integer  1 Byte 
B  Unsigned Integer  1 Byte 
c  Character   1 Byte 
i  Signed integer  2 Bytes 
l  Unsigned Integer  2 Bytes 
f  Floating point integer  4 Bytes 
d  Floating point integer  8 Bytes 

 

Let’s create an array and display all the elements in it: 

from array import * 

array_1 = array(‘l’, [100,150,200,250,300]) 

for y in array_1: 

 print(y) 

Here is the output  

100 

150 

200 

250 

300 

Accessing the elements in an Array 

Every array element can be accessed by their corresponding index number.  

For example, in the above array,  

array_1[0] will give you 100. 

 array_1[1] will give you 150. 

array_1[2] will give you 200. 

And so on.  

Insert() 

This function is used to insert elements into the array at a specific location, be it beginning, end or anyway in the middle.  

Syntax  

Array_name.insert(index_intended, value) 

To add an element 125 at 2nd position, we will use the following program. 

from array import * 

array_1 = array(‘l’, [100,150,200,250,300]) 

array_1.insert (1, 175); 

for y in array_1: 

 print(y) 

Here is the output  

100 

175 

150 

200 

250 

300 

Here, the number of elements in an array has also increased by 1. 

remove() function 

To delete a value from the array, you can use the remove() function. After deletion, all the elements would be reorganized again.  

Syntax 

arrayname.remove (element) 

The interpreter will find the value and delete it from the array and shifts the other values up. 

In case, the value is not found, it’ll give an error.    

Search Operation 

By using the built-in index() function/method you can easily find the index of an element. 

Syntax  

array_name.index (element) 

This will return the place or index of the element. If not found, the compiler will give an error.  

Let’s check some other methods that are used to operate on arrays. 

1). append() 

This method is used to add element at the end of the array and increases the length by 1. 

Syntax: 

array_name.append(<new value>)  

2). count() 

This method counts and returns the number of elements having the given value.  

Syntax: 

array_name.count(<element value>)  

3). reverse() 

It reverses the list making the first element last and brings the last element on first place.  

Syntax: 

array_name.reverse() 

4). pop()  

Just like remove() method uses the element value, pop() function uses index to remove an element. 

Syntax: 

array_name.pop(<index>)  

5). len() 

This method/function calculates the length of the array or number of elements in the array. 

Syntax: 

len(array_name)  

 

Read More – Coding and Programing Questions

View More – Useful links for Your Child’s Development 

What are strings in python?

Strings in Python is an immutable collection of characters. It’s like an array of characters that cannot be modified in any case but can only be accessed. 

Here the Unicode characters can be written in single quotes, double quotes and even triple quotes. You can skip a nested quote with the help of a backslash (“\”). 

Here are a few examples of valid string literals in Python: 

# String with double quotes 

print(“Welcome to TEL Gurus!”) 

# String with single quotes 

print (‘Welcome to TEL Gurus!’) 

# String with triple quotes 

print (‘ ‘ ‘Welcome to TEL Gurus!’ ‘ ‘) 

# String with triple double-quotes 

print (” ” “Welcome to TEL Gurus!” ” “) 

Here’s the output screen 

1. # Online Python compiler (interpreter) to run Python online.
2. # Write Python 3 code in this online editor and run it.
3. print(“Welcome to TEL Gurus!”)
4. print(‘Welcome to TEL Gurus!’)
5. print(”’Welcome to TEL Gurus!”’)
6. print(“””Welcome to TEL Gurus!”””)

Assigning string to a variable  

 You can easily assign a string to a variable. This makes the accessing easier and faster. 

You can use ‘+’ to join two strings. This is called string concatenation.  

For example:  

str1 = ‘This is a beautiful place’ 

str2 = ‘We are here to help! 

print (str1) 

print (str2) 

print (str1 +’. ‘+ str2) 

Here’s the output  

/////////////////////// image ///////////////////////////////////

Assessing String elements  

The elements of the strings in Python can easily be accessed using an index.  

The first character of the string has an index 0 and followed by 1,2,3.. and so on. 

You can even access the string from the back using index as -1, -2 etc.  

A string element with index [-1] means the last element of the string. 

Let’s understand the same using a string “TELGURUS”. 

  • First, we’ll create a variable that holds this string value. 
  • Next, we can access the characters using index placed in square brackets.  

str1 = “TEL GURUS” 

T  E  L     G  U  R  U  S 
0  1  2  3  4  5  6  7  8 
-9  -8  -7  -6  -5  -4  -3  -2  -1 

 

To access the first element of the string we use,  

str1[0] will give T  

and second element,  

str[1] will give E 

To access the elements from the end, we use negative numbers. 

str1[-1] will give S,  str1[-2] will give U. 

Length of a string  

To get the length can be calculated by using a len() function. 

len(<string name>) will give you a number that states the length of the string. 

Slicing   

 This helps you to slice a string and obtain a substring from it. 

Syntax followed is  

string_name [start_index: end_index] 

Here start_index is included but end_index is not included.  

Let’s apply all the concepts learnt above in a program. 

str1 = ‘TEL GURUS’ 

print (“The First Letter of string is  ” + str1[0]) 

print (“The Second Letter of String is ” + str1[1]) 

print (“The last letter is ” + str1[-1]) 

print (“The brand name is “+ str1[0:3]) 

print (“The length of string is “+ str(len(str1))) 

Here’s the output  

/////////////////////// image ///////////////////////////////////

If you look carefully at the program we have used another function str() in the last line while calculating the length of the string.   

It is done because, the len() function will return a number and on concatenating a string and a number, the interpreter will give an error.   

The number needs to be converted into string so as to make it eligible for concatenation.  

So, here comes str() function that converts any number into a string format.  

Escape sequences  

Generally, you aren’t able to print a string with the quotes within the quotes. For that, there are some escape sequences. 

  • Using a backlash “\” enables the interpreter to take quotes into account. 
  • “\n” is used for new line. 
  • “\t” is used for giving a tab space. 
  • “\b” is used as backspace. 

Read More – Coding and Programing Questions

View More – Useful links for Your Child’s Development 

What is a comment in programming?

Comments in programming means adding human readable descriptions in the source code explaining what the code intends to perform. 

Commenting is very essential part of every computer program as it helps in maintain the code in a better way extending its usability and scalability. 

It also plays a crucial role in debugging as the programmer will know the right place to debug and save a lot of time. 

Maintaining a well-documented code is an ideal quality of the programmer. 

How commenting works? 

Comments are not visible during the run time. A computer programmer can only see the comments in the source file.  

While executing the code, these comments are automatically hidden by the compiler, making only lines of code visible. 

Types of comments 

There are primarily two types of comments: 

  • Inline comments  

Here the comments are placed in line with the code. The comments take just one line or few words. 

Every language has it’s own syntax and symbols for commenting.  

Example1:  

Check the following C program for in line comment 

Int j= 10; // This is a comment in C Program. 

Two forward slashes are used to write a single line or in-line comment in C program. 

Example2: 

# This is comment in Python. 

The above example shows how single line comment is written in python language. 

  •   Nested comments  

If you want to explain what a function is doing or the role of a block of code, we need nested comments. 

As the explanation can be done in one line and we need multiple lines to explain the functionality.   

Here we need to provide beginning and ending of the comment. 

Let’s learn this with an example: 

In C language we start nested comments using ‘/*’ and end by ‘*/’. 

/* This function is used to 
calculate the average of numbers given by the user */ 

There are many languages such as Ada that do not support multiple line comment. You have to go for single line comments and split them in multiple lines using the in-line syntax for each line. 

What is a run-away comment? 

One of the main problem encountered by multi-line comments is that, programmers forget to close them. Look at this example: 

 /* set variables 

      x = 0; 

   /* set maximum size */ 

      max_size = 10; 

If you take a closer look, the line x=0; actually gets eaten up by the comment as the comment is not closed.  

The compiler will never able to find this line. Therefore, x=0 will never get executed. 

This is a kind of programming bug which is very difficult to locate and is known as run-away comment.  

This is the main reason most of the programmer prefer single-line comments or multiple (nested comments). 

Advantages of computer comments 

Computer program help and guide the programmer or the code-reviewer to: 

  • Understand the intent of code 
  • Debugging 
  • Including meta description  
  • Resource inclusion  
  • Insuring scalability of code and sometimes backward compatibility. 
  • Algorithm Description  

Where to use comments? 

As such, there is no hard and fast rule for comments inclusion. But there are certain places, where commenting is expected and is a must.  

  • Start of any program  

Here the intent of the program is explained such as who wrote the code, when, why, any modifications made etc. 

  • Above every function  

Before every function, it is important to describe what the function is doing and any algorithm the program is following. 

  • In-line comments  

Any line of code which is not usual or is tricky should be properly commented.  

It may happen that something that seems obvious to one person may not be the same for the other person.  

Read More – Coding and Programing Questions

View More – Useful links for Your Child’s Development 

Describe the basic syntax of python

Unlike C/C++ python is an interpreter-based high-level programming language.  

Python is widely popular because:  

  • It is open source and free to use as well as carries a GPL-compatible license.   
  • Here, the instructions are processed line by line.  
  • This language supports all the OOPs concepts as well such as inheritance, modules, classes, objects etc.   
  • The language has incredible exception handling support and amazing memory management.   

Why python is the first choice of programmers, gamers and other professionals of the digital world? 

  • Enhanced readability 
  • It’s open source and a cross-platform language 
  • Modules from other languages can easily be integrated. 
  • It has become an integral part of Data science, AI, machine learning, web development, game development etc. 
  • Staggering support to other languages and modules. 

Python is highly readable language that is read by a parser line by line. The language follows a syntax which is a set of rules that tells how a program or the instructions would be written.     

Let’s discuss the Line structure in Python. 

Line structure  

In a Python code, every instruction is in the form of a line. Each line is terminated by a carriage return of NEWLINE.  

This line can contain spaces, tabs, characters, comment etc. each line is like a statement.   

Here, we will be discussing syntax based on Python3. 

For example: Have a look at the following Python statements. 

print(‘User Id: ‘, 15) 

print(‘First Name: ‘, ‘Harry’) 

print(‘Last Name: ‘, ‘Potter’) 

These are single line statements followed by a carriage feed or newline character. To join multiple lines, you will need “\” or backspace.  

“\” is used to split one statement or instruction. It does not join two different lines (instructions).   

Let’s take some more examples for multiple lines.  

if subject > 10 and \ 

    totalmarks >= 300:  

        print(‘You have created history!’) 

Indentation: 

To define the program blocks, Python uses whitespaces which can either be spaces or tabs. 

Unlike most of the programming languages like C/C++ uses braces {} to define a block, it’s just white spaces for Python code.  

Though indentation is not fixed, every statement within the block must be indented in a same manner.  

Indentation Rules 

  • All the instructions in a block use same indentation levels (same whitespace or same tab spacing). 
  • Generally four white spaces are used to denote indentation from the previous block. 
  • One block can have further inner levels by giving suitable indentation.  
  • To start a block you should use a colon (:)  and then hit Enter.  

Comments in Python 

In Python, comments always begin with #. Here “#” is not a set of literals that are used in python programming.  

Whatever is written after # till the end of line, python interpreter ignores it.   

Python Identifiers 

An identifier in python means any name that is used to identify a function, variable, object, class etc.  

It starts with letter a-z or A-Z or can start with “_” (underscore). The name can then followed by numbers or other letters. 

No punctuation characters such as $, @ and % are allowed within the identifiers.  

The identifiers are case sensitive. “school” and “School” are two different identifiers.  

Have a look at some naming conventions in Python identifiers: 

  • All identifiers except class names start with lowercase letters. 
  • Identifier named using a one underscore means that it is a private identifier. 
  • A name starting with two underscores means additionally strong private identifier. 
  • Any identifier name ending with two underscores means it’s a language defined name.  

 

Read More – Coding and Programing Questions

View More – Useful links for Your Child’s Development 

Difference between coding and programming.

We often hear about the terms “coding” and “programming” and consider that both are the same. But in reality, these are entirely two different worlds. Read this thoroughly and get all the information concerning it.

Book Your 60-minutes Free Trial class NOW!

What is coding?

Coding refers to the act of translating a code from a general human language to a machine-understandable language. Being a coder, you need to write code using different programming languages, including C programming, Java, Python, and many more.

With the knowledge of these languages, you will be able to endow the computer system with the information and instruction to make it execute a program. It involves the code writing for creating a software program.

What is Programming?

The term programming refers to a process of developing an executable program that is implemented devoid of any errors. A programmer’s job is to analyze a problem and provide solutions corresponding to it.

A programmer follows the following steps to generate an error-free outcome.

  • Plans the application
  • Designs it
  • Tests the features
  • Deploys it
  • And Maintain it after it is finished.

Key Differences between Coding and Programming

Terms Coding Programming
Basic Difference It is a part of programming that deals with code writing which machines can translate. It refers to the process of creating a program, which follows some standards and performs a certain task.
Tools It doesn’t require many software tools as it is just a code translation’s act to machine-readable form.

A simple text editor like notepad or WordPad will suffice.

 

It requires performing document analysis and reviews along with coding requires extra tools.

The additional tools include code generators, testing frameworks, compilers, assemblers, modeling algorithms, debuggers, GUI Designers, databases.

 

Skills Being a coder you need to know the syntax details of the programming language. A programmer requires a lot of experience to obtain the skills, create complex data structures.
Definition Coding refers to the translation of a general language to a machine language through an intermediary coding language. Programming refers to the development process of a fully functioning software solution.
Approach required A coder follows a trial and error approach and does not require any previous preparations. A programmer follows a methodical approach that requires attention to detail.
Outcomes Coding generally results in a small part of a simple solution of a project. Programming generally results in a complete ready to use application.

Book Your 60-minutes Free Trial class NOW!

How do Programming and Coding work together?

Now that you have understood the differences between both coding and programming. But do you know that coding and programming also work together to accomplish several tasks? Yes! They work together to perform tasks.

Let us understand it with the help of an example:

Consider that we are creating an application to monitor something like your daily routine. Here is the association between the terms and how it accomplishes the task altogether.

Firstly, the programmer will

  • Plan the application’s structure
  • Write down the application features
  • Design the application
  • And consider thinking of any other features that are required to be included in the application.

Now that the programmer is done with the tasks mentioned above, the coder will take over the process. A coder will transform the ideas into the codes that a machine that is your computer system can understand.

Once the coder is done with the code modules, the programmer will go through them. Do the polishing, debug and check for the errors and perform testing before publishing the final product.

So, this is how these two terms work together to get the desired outcome.

Book Your 60-minutes Free Trial class NOW!

Read More – Python Questions

View More – Useful links for Your Child’s Development 

How do I use “for” loops in Python?

To keep a computer system performing useful work, we need repetition. Repetition is performed by looping back over the same code block again and again.

What is For Loop?

For loop is used to iterate over the sequence of elements that are often used when you have a code, which you want to repeat for “n” number of times. In short, it works like “for all elements in a list, do this.”

A for loop in Python is used for iterations or, say, iterating over the same sequence. It is less like the “for a keyword like used in other programming languages and works more like an iterator method than found in the Object-Oriented Programming languages.

Using a for loop in the Python code, we can execute the set of statements once for each item in a collection, tuple, or list.

For instance,

Print each color in a color list:

Colors = [“Red”, “Yellow”, “Black”, “Blue”]

For x in colors:

Print (x)

Here the “for loop” doesn’t require an indexing variable to put beforehand.

  • Looping through a string

Strings are also iterable objects that contain the characters’ sequence. For instance, let us consider the loop through the letters present in the word “banana.” The looping statement for this will be

For x in “banana”:

Print x

  • Using The Break Statement

By using the break statement, we can stop the ongoing look before it has looped through the entire item set. For instance,

You need to exit the loop when x is “banana”:

Fruits = [“orange”, “apple”, “banana”, “cherry”]

For x in fruits:

Print (x)

If x == “banana”:

Break

This will break the look once it encounters the fruit banana instead of searching for the whole item set.

Taking it another way

Exit the loop when “x” is banana, but this time break comes before the print:

Fruits = [“apple”, “orange”, “banana”, “cherry”]

For x in fruits:

If x == “banana”:

Break

Print (x)

  • Using The Continue statement

Using the continue statement, we can stop the loop’s current iteration and continue with the next one.

For instance,

Fruits = [“apple”, grapes”, banana”, “cherry”]

For x in fruits:

If x == “banana”:

Continue

Print (x)

The for loop is also applicable in the range function.

  • Using the range () function

We can use the range () function to loop through a code set a specified number of times. The range function returns the numbers sequence beginning from 0 by default and then further increments by one till some specified number.

For instance,

Using the range function:

For x in range (6):

Print (x)

Here if you execute the code, the range will move from 0 to 5, not 0 to 6.

  • Using Else in For loop

The use of the else keyword in a for loop indicates that a block of a code needs to be executed when the for loop is finished.

For instance,

Print all the numbers from 0 to 5 and print the message when the loop ends.

For this, we need to perform

For x in range (6):

Print (x)

Else:

Print (“Finally Finished!”)

Now this will iterate from range 0 to 5 and then prints the message “Finally Finished!”

 

Read More – Python Questions

View More – Useful links for Your Child’s Development 

Tel Guru
Tel Guru

Register For The Demo Class

[footer-form]