× 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 

Difference between AND, OR Operators

Amongst all operators, AND and OR are two widely used logical operators in any programming language.  

AND, OR operators fall under logical operators set and are known as Logical AND denoted by && and Logical OR denoted by ||. 

Let’s first discuss the Logical OR.  

Logical OR 

Logical OR is a Boolean operator and is denoted by double pipe symbols (||). 

Certain test conditions are input to this operator and the result obtained is also Boolean i.e. either TRUE or FALSE. 

This operator requires a minimum of two operands to process. 

The general conventions followed for all logical operator is that any non zero number is considered as TRUE (1).  

Incase the expression does not has number, it is converted into its corresponding ASCII value and then used for evaluation.  

A Logical OR returns TRUE (1) when atleast one or more operands are TRUE. It will return FALSE (0) only when all the operands are FALSE  or zero. 

Syntax of Logical OR:  

Operand 1 || Operand 2 

Truth Table for Logical OR 

Operand 1  Operand 2  Operand1 || Operand2 
TRUE   TRUE  TRUE 
TRUE  FALSE  TRUE 
FALSE   TRUE  TRUE 
FALSE  FALSE  FALSE 

 

Let’s check a C program to demonstrate the Logical OR that prints a number if it’s either greater than 4 or less than 10 

// C program to demonstrate example of  

// Logical OR (||) operator  

#include <stdio.h> 

int main() 

{ 

    int num = 3; 

    //printing if number less than 10 or greater than 4 

if ( (num < 10) || (num > 4)) 

       printf(“%d”, num); 

else  

     printf(“No Match Found”);  

    return 0; 

} 

Here, check the test condition  

(num < 10) || (num > 4) 

When num=3, the first condition is TRUE but the second condition is FALSE. 

By looking at the TRUTH table, you can easily deduce that ‘if will return TRUE or 1 and the number will be printed on console. 

Logical AND  

Logical AND is denoted by && and just like OR, it works on Boolean operands and values. 

Logical AND returns TRUE or 1 only when all the operands are TRUE or non zero. 

If any one of the operands is zero, it will be FALSE. It is just like multiplication, one zero and the entire thing will be zero or FALSE. 

  Syntax of Logical AND:  

Operand 1 && Operand 2 

Truth Table for Logical AND 

Operand 1  Operand 2  Operand1 && Operand2 
TRUE   TRUE  TRUE 
TRUE  FALSE  FALSE 
FALSE   TRUE  FALSE 
FALSE  FALSE  FALSE 

 

Let’s check a C program to demonstrate the Logical AND that prints a number if it’s greater than 4 and less than 10 

// C program to demonstrate example of  

// Logical OR (||) operator  

#include <stdio.h> 

int main() 

{ 

    int num = 3; 

    //printing if number less than 10 or greater than 4 

if ( (num < 10) && (num > 4)) 

      printf(“%d”, num); 

else  

      printf(“No Match Found”);  

    return 0; 

} 

We are taking the same program used in Logical OR, for better understanding. 

Here the test condition is 

(num < 10) && (num > 4) 

When num is replaced by 3, the first statement is TRUE while the second is FALSE. This makes the entire expression turn FALSE making the control of program to shift to “else” part in the program. 

No Match found” will be printed on console. 

Now, Let’s draw the basic difference between the two operators: 

  OR  AND 
Symbol  || (two pipes)  && (Two Ampersands) 
Working   Returns TRUE when any of the operand is TRUE.  Returns TRUE only when all the operands are TRUE. 
Similarity   Works like arithmetic Addition  Works like arithmetic Multiplication 

 

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 

What is statement in Programming?

Statement in a programming means any line of code that instructs the compiler to perform a specific task. 

A computer program is a set of such statements. There can be multiple types of statements in a program code that controls the input and output of the actions that a program is designed for.   

What is the role of a statement in a program? 

It’s the computer program that tells the computer to perform or to take action. A statement can be a set of symbols, numbers or pneumonics used in a program. 

For example: 

int   x; 

This is a simple declaration statement from C language which declares an integer variable named ‘x’. 

Types of programming statements  

A program consists of various types of statements.  

While assignment and declaration statements help a variable understand its data type and assign its value, flow control statements direct the sequence of the execution of the program.  

Every programming language has its own format and syntax that is to be followed by the programmer while writing the code.  

There are essentially seven types of programming statements. Let’s have a look. 

  1. Declaration statements  
  2. Labeled statements  
  3. Expression statements  
  4. Selection statements 
  5. Iteration statements  
  6. Compound statements  
  7. Jump statements 

Now, let’s discuss them in detail.   

1). Declaration statements 

As mentioned in the above example, a declaration statement is used to introduce a variable or an identifier into the program or module. 

2). Labeled statements  

These statements usually contain a label and are used to direct the flow of execution in a program.  

Considering the C/C++ language, labels are used for redirecting the control to “switch” and “goto” statements. It can be a case label or a default label in a switch statement. 

In C/C++ it is must to use a colon(:) after a label to define it. 

For a switch statement, it is written as: 

case label_expr : statement  

This means that control of the program will reach this point if the label or the expression of the switch gets matched with that of the program. 

You need to give a default label, which will make the thing run in case nothing matches with the labels of the switch statement.  

3). Expression statements  

With perspective to C/C++, any statement which is followed by a semicolon (;) is termed as an expression.  

Example: The input/output commands such as printf and scanf statements are a typical example of expression statements.  

4). Selection statements  

These statements help to make a decision using “if” clause. 

In C/CPP there are three types of selection statements: 

1. IF Statement  

Syntax: 

if (expression) 

         statement_1; 

Here, if the expression is true then, program control executes statement_1 else leaves. 

2. IF-ELSE Statement  

Syntax: 

if (expression) 

          statement_1; 

else  

         statement_2; 

Here, if the expression is true then statement_1 gets executed else the program control shifts to statement_2. 

3. Nested IF-ELSE Statement  

Syntax: 

if (expression_1) 

          {  if(expression_2)    statement_1; } 

else  

         statement_3; 

Here, multiple if-else statements are used to decide the flow of control. 

Apart from that switch statements also come under this category where the selection is made using the case statements. 

5). Iteration statements  

Iteration statements include the ones which require running the same code again and again till a fixed number of times.  

In C/C++ there are three type of iteration statements. 

  • For loop 
  • While loop 
  • Do-while loop 

6). Compound statements  

Compound statement is a group pr block of statements combined together.  

Programs usually need brackets {,} to bind more than one statement. Thereby, forming a compound statement.  

Also, variables that are declared within the braces have a scope limited to that block only.  

7). Jump statements 

To transfer the flow of control unconditionally, some jump statements are used. 

For example: return, goto, continue, break etc.  

While using jump statements every programmer must note that when the control jumps out of a block or loop, may involve destruction that were declared in the local scope.  

 

Read More – Coding and Programing Questions

View More – Useful links for Your Child’s Development 

Tel Guru
Tel Guru

Register For The Demo Class

[footer-form]