You are on page 1of 27

Q.1Differentiate between Python and JAVA.

ANS.
Parameter Python Java

Code Python has less lines of code. Java has longer lines of code.

Compare to JAVA, Python has


lower number of Frameworks.
Popular ones are DJango, Java has large number of Frameworks. Popular
Framework Flask. ones are Spring, Hibernate, etc.

Syntax is easy to remember


almost similar to human Syntax is complex as it throws error if you miss
Syntax language. semicolon or curly braces.

Less line no of code, Rapid


Key deployment and dynamic Self memory management, Robust, Platform
Features typing. independent

Python is slower since it uses


interpreter and also determines
Speed the data type at run time. Java is faster in speed as compared to python.

Python’s database access


layers are weaker than Java’s (JDBC)Java Database Connectivity is most
JDBC. This is why it rarely used popular and widely used to connect with
Databases in enterprises. database.

Machine
Learning
Libraries Tensorflow, Pytorch. Weka, Mallet, Deeplearning4j, MOA

Java enjoys more consistent refactoring


Python has always had a support than Python thanks on one hand to its
presence in the agile space and static type system which makes automated
has grown in popularity for refactored more predictable and reliable, and
Practical many reasons, including the on the other to the prevalence of IDEs in Java
Agility rise of the DevOps movement. development .

Q.2 Differentiate between Python and C.


Metrices C Python

C is a general-purpose, procedural computer Python is an interpreted, high-level, general-purpose


Introduction programming language. programming language.

Compiled programs execute faster as Interpreted programs execute slower as compared to


Speed compared to interpreted programs. compiled programs.

It is easier to write a code in Python as the number of


Usage Program syntax is harder than Python. lines is less comparatively.

There is no need to declare the type of variable.


In C, the type of a variable must be declared Variables are untyped in Python. A given variable can be
Declaration of when it is created, and only values of that type stuck on values of different types at different times
variables must be assigned to it. during the program execution

In C, error debugging is difficult as it is a Error debugging is simple. This means it takes only one
compiler dependent language. This means in instruction at a time and compiles and executes
that it takes the entire source code, compiles it simultaneously. Errors are shown instantly and the
Error Debugging and then shows all the errors. execution is stopped, at that instruction.

Function C does not support function renaming


renaming mechanism. This means the same function Supports function renaming mechanism i.e, the same
mechanism cannot be used by two different names. function can be used by two different names.

The syntax of a C program is harder than Syntax of Python programs is easy to learn, write and
Complexity Python. read.

Memory- In C, the Programmer has to do memory Python uses an automatic garbage collector for memory
management management on their own. management.

C is generally used for hardware related


Applications applications. Python is a General-Purpose programming language.

Built-in functions C has a limited number of built-in functions. Python has a large library of built-in functions.

Implementing Implementing data structures requires its Gives ease of implementing data structures with built-in
Data Structures functions to be explicitly implemented insert, append functions.

Pointers Pointers are available in C. No pointers functionality available in Python.

Q.3 Explain various features of Python programming Language


ANS. Python is a dynamic, high-level, free open source, and interpreted programming language. It supports object-oriented
programming as well as procedural-oriented programming. In Python, we don’t need to declare the type of variable because it is a
dynamically typed language. For example, x = 10 Here, x can be anything such as String, int, etc.

Features in Python
There are many features in Python, some of which are discussed below as follows:
1. Free and Open Source
Python language is freely available at the official website and you can download it from the given download link below click on
the Download Python keyword. Download Python Since it is open-source, this means that source code is also available to the public.
So you can download it, use it as well as share it.
2. Easy to code
Python is a high-level programming language. Python is very easy to learn the language as compared to other languages like C, C#,
Javascript, Java, etc. It is very easy to code in the Python language and anybody can learn Python basics in a few hours or days. It is
also a developer-friendly language.

3. Easy to Read

As you will see, learning Python is quite simple. As was already established, Python’s syntax is really straightforward. The code block
is defined by the indentations rather than by semicolons or brackets.
4. Object-Oriented Language
One of the key features of Python is Object-Oriented programming. Python supports object-oriented language and concepts of
classes, object encapsulation, etc.
5. GUI Programming Support
Graphical User interfaces can be made using a module such as PyQt5, PyQt4, wxPython, or Tk in python. PyQt5 is the most popular
option for creating graphical apps with Python.
6. High-Level Language
Python is a high-level language. When we write programs in Python, we do not need to remember the system architecture, nor do
we need to manage the memory.
7. Extensible feature
Python is an Extensible language. We can write some Python code into C or C++ language and also we can compile that code in
C/C++ language.
8. Easy to Debug
Excellent information for mistake tracing. You will be able to quickly identify and correct the majority of your program’s issues once
you understand how to interpret Python’s error traces. Simply by glancing at the code, you can determine what it is designed to
perform.
9. Python is a Portable language
Python language is also a portable language. For example, if we have Python code for windows and if we want to run this code on
other platforms such as Linux, Unix, and Mac then we do not need to change it, we can run this code on any platform.
10. Python is an Integrated language
Python is also an Integrated language because we can easily integrate Python with other languages like C, C++, etc.
11. Interpreted Language:
Python is an Interpreted Language because Python code is executed line by line at a time. like other languages C, C++, Java, etc.
there is no need to compile Python code this makes it easier to debug our code. The source code of Python is converted into an
immediate form called bytecode.
12. Large Standard Library
Python has a large standard library that provides a rich set of modules and functions so you do not have to write your own code for
every single thing. There are many libraries present in Python such as regular expressions, unit-testing, web browsers, etc.
13. Dynamically Typed Language
Python is a dynamically-typed language. That means the type (for example- int, double, long, etc.) for a variable is decided at run
time not in advance because of this feature we don’t need to specify the type of variable.
14. Frontend and backend development
With a new project py script, you can run and write Python codes in HTML with the help of some simple tags <py-script>, <py-env>,
etc. This will help you do frontend development work in Python like javascript. Backend is the strong forte of Python it’s extensively
used for this work cause of its frameworks like Django and Flask.
15. Allocating Memory Dynamically
In Python, the variable data type does not need to be specified. The memory is automatically allocated to a variable at runtime when
it is given a value. Developers do not need to write int y = 18 if the integer value 15 is set to y. You may just type y=18.

Q.4 Explain if-else of Python with the help of syntax and example
if-else
The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is fal se
it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use
the else statement with if statement to execute a block of code when the condition is false.
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
FlowChart of Python if-else statement

Example 1: Python if-else statement

• Python3

# python program to illustrate If else statement


#!/usr/bin/python

i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")

Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block
The block of code following the else statement is executed as the condition present in the if statement is false after
calling the statement which is not in block(without spaces).

Q.5 Describe if-elif of Python with the help of example.

ANS: The elif Statement


The elif statement allows you to check multiple expressions for TRUE and execute a block of code as
soon as one of the conditions evaluates to TRUE.
Similar to the else, the elif statement is optional. However, unlike else, for which there can be at most
one statement, there can be an arbitrary number of elif statements following an if.

syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)

flow chart

example
num = 3.4
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Q.6 Describe various control statements of Python.
ANS: Control statements in python are used to control the flow of execution of the program based on the specified
conditions.Python supports 3 types of control statements such as,

1) Break 2) Continue 3) Pass


Break in Python

The break statement in Python is used to terminate a loop. This means whenever the interpreter encounters the break keyword, it simply

exits out of the loop. Once it breaks out of the loop, the control shifts to the immediate next statement.

Also, if the break statement is used inside a nested loop, it terminates the innermost loop and the control shifts to the next statement in the

outer loop.

Flowchart of Break Statement in Python

Example of Break Statement in Python

Here is an example of how break in Python can be used to exit out of the loop. Let's say you want to check if a given word contains the

letter A, then how would you do it?

#program to check if letter 'A' is present in the input

a = input ("Enter a word")

for i in a:

if (i == 'A'):

print ("A is found")

break

else:

print ("A not found")

Input: FACE Prep

Output:

A not found

A is found

How is break statement useful in the above example? Our code accesses each character of the string and checks if the character is 'A'.

Whenever it finds character 'A', it breaks out of the loop, hence avoiding the process of checking the remaining letters. So here break helps

avoid unwanted looping.

Continue in Python
Whenever the interpreter encounters a continue statement in Python, it will skip the execution of the rest of the statements in that

loop and proceed with the next iteration. This means it returns the control to the beginning of the loop.Unlike the break statement,

continue statement does not terminate or exit out of the loop.Rather, it continues with the next iteration. Here is the flow of execution when

continue statement is used.

Flowchart of Continue Statement in Python

Example of Continue Statement in Python

Let us see how the same above discussed example can be written using a continue statement. Here is the code.

#program to check if letter 'A' is present in the input

a = input ("Enter a word")

for i in a:

if (i != 'A'):

continue

else:

print ("A is found")

Input: FACE Prep

Output:

A is found

Pass in Python
Assume we have a loop that is not implemented yet, but needs to implemented in the future. In this case, if you leave the loop
empty, the interpreter will throw an error. To avoid this, you can use the pass statement to construct a block that does nothing i.e
contains no statements. For example,

for i in 'FACE':

if (i == 'A'):

pass
print (i)

Output:

F
A

Q.7 Explain for loop of Python.


ANS: The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a
sequence is called traversal. If we have a section of code that we would like to repeat a certain number of times, we
employ for loops. This is less like the for keyword in other programming languages, and works more like an
iterator method as found in other object-orientated programming languages.
syntax
for element in ele_list :
statements
program_code
flowchart:

Example;
sum = 0
for val in range(1,11):
sum = sum+val
print("value of val is",val)
print("The sum is", sum)

Q.8 Write a note of while loop of Python.

ANS: The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true.
We generally use this loop when we don't know the number of times to iterate beforehand.

Syntax of while Loop in Python

while test_expression:

Body of while

In the while loop, test expression is checked first. The body of the loop is entered only if the test_expression evaluates

to True. After one iteration, the test expression is checked again. This process continues until the

test_expression evaluates to False. In Python, the body of the while loop is determined through indentation. The body

starts with indentation and the first unindented line marks the end. Python interprets any non-zero value

as True. None and 0 are interpreted as False.


Flowchart of while Loop

Example: Python while Loop

# Program to add natural


# numbers up to
# sum = 1+2+3+...+n

# To take input from the user,


# n = int(input("Enter n: "))

n = 10
# initialize sum and counter
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
Run Code

When you run the program, the output will be:

Enter n: 10
The sum is 55

In the above program, the test expression will be True as long as our counter variable i is less than or equal to n (10 in

our program).
Q.9 Write a note on input and output statement in Python

ANS: A program needs to interact with the user to accomplish the desired task; this can be

achieved using Input-Output functions.

Python Input

While programming, we might want to take the input from the user. In Python, we can use
the input() function.

Syntax of input()

input([prompt])

Here, prompt is the string we wish to display on the screen. It is optional.

Example: Python User Input

# using input() to take user input


num = input('Enter a number: ')
print('You Entered:', num)
print('Data type of num:', type(num))
Run Code

Output

Enter a number: 10
You Entered: 10
Data type of num: <class 'str'>

In the above example, we have used the input() function to take input from the user and stored the user input

in the num variable.

It is important to note that the entered value 10 is a string, not a number. So, type(num) returns <class

'str'>.

To convert user input into a number we can use int() or float() functions as:

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

Here, the data type of the user input is converted from string to integer .

Python Output

In Python, we can simply use the print() function to print output.

Syntax of print()
the syntax of the print function accepts 5 parameters

print(object= separator= end= file= flush=)

Here,

• object - value(s) to be printed


• sep (optional) - allows us to separate multiple objects inside print().

• end (optional) - allows us to add add specific values like new line "\n", tab "\t"

• file (optional) - where the values are printed. It's default value is sys.stdout (screen)

• flush (optional) - boolean specifying if the output is flushed or buffered. Default: False

Example 1: Python Print Statement

print('Good Morning!')
print('It is rainy today')
Run Code

Output

Good Morning!
It is rainy today

In the above example, the print() statement only includes the object to be printed. Here, the value for end is

not used. Hence, it takes the default value '\n'.

So we get the output in two different lines.

Example 2: Python print() with end Parameter

# print with end whitespace


print('Good Morning!', end= ' ')
print('It is rainy today')

Output

Good Morning! It is rainy today

Notice that we have included the end= ' ' after the end of the first print() statement.

Hence, we get the output in a single line separated by space.


Q.10 Write a note on concept of nested loop.

ANS:
• In Python programming language there are two types of loops which are for loop and while loop.
• Using these loops we can create nested loops in Python.
• If a loop exists inside the body of another loop, it is termed as Nested Loop. For example, while loop
inside the for loop, for loop inside the for loop, etc. The “inner loop” will be executed one time for
each iteration of the “outer loop”:
• The outer loop can contain any number of the inner loop. There is no limitation on the nesting of loops.
syntax
Outer_loop Expression:
Inner_loop Expression:
Statement inside inner_loop

flowchart
nested loop example
for i in range(1, 5):
# inner loop
for j in range(1, i + 1):
print(j, end="\t ")
print(' ')
Output:

1 2

1 2 3

1 2 3 4

Q.11 How to accept command line arguments in Python program? Explain.


ANS: Python Command line arguments are input parameters passed to the script when executing
them. Almost all programming languages provide support for command line arguments.

There are many options to read python command line arguments. The three most common
ones are:
1. Python sys.argv
2. Python getopt module
3. Python argparse module

Python sys module


Python sys module stores the command line arguments into a list, we can access it using
sys.argv. This is very useful and simple way to read command line arguments as String.

Example
import sys
print(type(sys.argv))
print('The command line arguments are:')
for i in sys.argv:
print(i)
To execute the above program in IDLE, go to RUN menu and choose Run..Customized option or
shift+F5 key. It will show a pop up window for command line arguments, enter arguments
separated by comma and proceed.

Python getopt module


Python getopt module is very similar in working as the C getopt() function for parsing
command-line parameters. Python getopt module is useful in parsing command line arguments
where we want user to enter some options too.

import sys
argv = sys.argv[1:]
try:
opts, args = getopt.getopt(argv, 'hm:d', ['help', 'my_file='])
print(opts)
print(args)
except getopt.GetoptError:
# Print a message or do something useful
print('Something went wrong!')
sys.exit(2)

Python argparse module

Python argparse module is the preferred way to parse command line arguments. It provides a
lot of option such as positional arguments, default value for arguments, help message,
specifying data type of argument etc. At the very simplest form, we can use it like below.

import argparse
parser = argparse.ArgumentParser()
parser.parse_args()

Q.12 Write a note on various data types of Python.


ANS: Data Types

1) Numbers: Number stores numeric values. The integer, float, and complex values belong
to a Python Numbers data-type.
• Integers – This value is represented by int class. It contains positive or
negative whole numbers (without fraction or decimal). In Python there is no
limit to how long an integer value can be.
• Float – This value is represented by float class. It is a real number with
floating point representation. It is specified by a decimal point. Optionally, the
character e or E followed by a positive or negative integer may be appended
to specify scientific notation.
• Complex Numbers – Complex number is represented by complex class. It is
specified as (real part) + (imaginary part)j. For example – 2+3j

2) String: The string can be defined as the sequence of characters represented in the quotation
marks. In Python, we can use single, double, or triple quotes to define a string.
3) List: Python Lists are similar to arrays in C. However, the list can contain data of different
types. The items stored in the list are separated with a comma (,) and enclosed within square
brackets [].
4) Tuple: A tuple is similar to the list in many ways. Like lists, tuples also contain the collection
of the items of different data types. The items of the tuple are separated with a comma (,) and
enclosed in parentheses ().
5) Dictionary: Dictionary is an unordered set of a key-value pair of items. The items in the
dictionary are separated with the comma (,) and enclosed in the curly braces {}.
6) Boolean: Boolean type provides two built-in values, True and False. These values are used to
determine the given statement true or false.
7) Set: Python Set is the unordered collection of the data type. It is iterable, mutable(can
modify after creation), and has unique elements. In set, the order of the elements is
undefined; it may return the changed sequence of the element.

Q.13 How to create variables in python? Explain with help of syntax and
example.
ANS: Python Variable is containers which store values. Python is not “statically typed”. We do
not need to declare variables before using them or declare their type.

Rules for creating variables in Python


• A variable name must start with a letter or the underscore character.
• A variable name cannot start with a number.
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ ).
• Variable names are case-sensitive (name, Name and NAME are three different
variables).
• The reserved words(keywords) cannot be used naming the variable.
#Legal variable names:
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
#Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"
Example
# declaring the var
Number = 100
# display
print( Number)

Output:
100

Global and Local Python Variables


Local variables are the ones that are defined and declared inside a function. We can not call
this variable outside the function.
# This function uses global variable s
def f():
s = "Welcome geeks"
print(s)
f()

Output:
Welcome geeks
Global variables are the ones that are defined and declared outside a function, and we need
to use them inside a function.

def f():
print(s)
s = "I love Geeksforgeeks"
f()

Output:
I love Geeksforgeeks

Q.14 Describe datatype conversion(typecasting) in Python.


ANS: Type Casting is the method to convert the variable data type into a certain data type in
order to the operation required to be performed by users.
There can be two types of Type Casting in Python –
• Implicit Type Casting
• Explicit Type Casting
Implicit Type Conversion
In this, methods, Python converts data type into another data type automatically. In this
process, users don’t have to involve in this process.

a = 7
print(type(a))
b = 3.0
print(type(b))
c = a + b
print(c)
print(type(c))
d = a * b
print(d)
print(type(d))

Output:
<class 'int'>
<class 'float'>
10.0
<class 'float'>
21.0
<class 'float'>

Explicit Type Casting


In this method, Python need user involvement to convert the variable data type into certain
data type in order to the operation required.
Mainly in type casting can be done with these data type function:
• Int() : Int() function take float or string as an argument and return int type object.
• float() : float() function take int or string as an argument and return float type
object.
• str() : str() function take float or int as an argument and return string type object.

some example of type casting:

Type Casting int to float:


Here, we are casting integer object to float object with float() function.
n = float(a)
print(n)
print(type(n))

Output:
5.0
<class 'float'>
Type Casting float to int:
Here, we are casting float data type into integer data type with int() function.
n = int(a)
print(n)
print(type(n))

Output:
5
<class 'int'>
Type casting int to string:
Here, we are casting int data type into string data type with str() function.
n = str(a)
print(n)
print(type(n))

Output:
5
<class 'str'>
Type Casting string to int:
Here, we are casting string data type into integer data type with int() function.
a = "5"
n = int(a)
print(n)
print(type(n))

Output:
5
<class 'int'>
Type Casting String to float:
Here, we are casting string data type into float data type with float() function.
a = "5.9"
n = float(a)
print(n)
print(type(n))

Output:
5.9
<class 'float'>

Q.15 Explain execution process of Python program.


ANS:

a = 10
b = 10
print("Sum ", (a+b))

Output:
Sum 20
Suppose the above python program is saved as first.py. Here first is the name and .py is the
extension. The execution of the Python program involves 2 Steps:
• Compilation
• Interpreter
Compilation
The program is converted into byte code. Byte code is a fixed set of instructions that represent
arithmetic, comparison, memory operations, etc. It can run on any operating system and hardware.
The byte code instructions are created in the .pyc file. The .pyc file is not explicitly created as
Python handles it internally.
The .pyc file is not explicitly created as Python handles it internally but it can be viewed with the
following command:

-m and py_compile represent module and module name respectively. This module is responsible to
generate .pyc file. The compiler creates a directory named __pycache__ where it stores the
first.cpython-38.pyc file.

Interpreter
The next step involves converting the byte code (.pyc file) into machine code. This step is
necessary as the computer can understand only machine code (binary code). Python Virtual
Machine (PVM) first understands the operating system and processor in the computer and then
converts it into machine code. Further, these machine code instructions are executed by processor
and the results are displayed.

Execution of Python Program

However, the interpreter inside the PVM translates the program line by line thereby consuming a lot
of time. To overcome this, a compiler known as Just In Time (JIT) is added to PVM. JIT compiler
improves the execution speed of the Python program. This compiler is not used in all Python
environments like CPython which is standard Python software.
To execute the first.cpython-38.pyc we can use the following command:

To view the byte code of the file – first.py we can type the following command as :

The dis command is known as “disassembler” that displays the byte code in an understandable
format. The code represents 5 columns:
1. Line Number
2. offset position of byte code
3. name of byte code instruction
4. instruction’s argument
5. constants or names (in brackets)

Q.16 Differentiate between break and continue statement.


ANS:

BASIS FOR
BREAK CONTINUE
COMPARISON

Task It terminates the execution of remaining It terminates only the current iteration of the

iteration of the loop. loop.

Control after 'break' resumes the control of the 'continue' resumes the control of the program to

break/continue program to the end of loop enclosing that the next iteration of that loop enclosing

'break'. 'continue'.
BASIS FOR
BREAK CONTINUE
COMPARISON

Causes It causes early termination of loop. It causes early execution of the next iteration.

Continuation 'break' stops the continuation of loop. 'continue' do not stops the continuation of loop,

it only stops the current iteration.

Other uses 'break' can be used with 'switch', 'label'. 'continue' can not be executed with 'switch' and

'labels'.

Q.17 How else statement works with the for loop in python? Explain with an example.
ANS: In most of the programming languages (C/C++, Java, etc), the use of else statement
has been restricted with the if conditional statements. But Python also allows us to use the
else condition with for loops.

The else block just after for/while is executed only when the loop is NOT terminated by a
break statement.
Else block is executed

or i in range(1, 4):
print(i)
else: # Executed because no break in for
print("No Break")

Output :
1
2
3
No Break
Else block is NOT executed

for i in range(1, 4):


print(i)
break
else: # Not executed as there is a break
print("No Break")

Output :
1

Such type of else is useful only if there is an if condition present inside the loop which
somehow depends on the loop variable.
In the following example, the else statement will only be executed if no element of the array
is even, i.e. if statement has not been executed for any iteration. Therefore for the array [1,
9, 8] the if is executed in the third iteration of the loop and hence the else present after the
for loop is ignored. In the case of array [1, 3, 5] the if is not executed for any iteration and
hence the else after the loop is executed.

def contains_even_number(l):
for ele in l:
if ele % 2 == 0:
print ("list contains an even number")
break
else:
print ("list does not contain an even number")
print ("For List 1:")
contains_even_number([1, 9, 8])
print (" \nFor List 2:")
contains_even_number([1, 3, 5])

Output:
For List 1:
list contains an even number

For List 2:
list does not contain an even number

Q.18 How else statement works with the while loop in python? Explain with an
example.
ANS : In Python, the while statement may have an optional else clause:

while condition:
# code block to run
else:
# else clause code block
Code language: PHP (php)
In this syntax, the condition is checked at the beginning of each iteration. The code block inside
the while statement will execute as long as the condition is True.

When the condition becomes False and the loop runs normally, the else clause will execute. However,
if the loop is terminated prematurely by either a break or return statement, the else clause won’t
execute at all.

The follwing flowchart illustrates the while...else clause:

Example

Print a message once the condition is false:

i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

output

1
2
3
4
5
i is no longer less than 6
Short Answer Question
Q.1 Which the following variables names are valid for the Python program? Justify your
answer. _num , num
ANS: Rules for Python variables:

• A variable name must start with a letter or the underscore character


• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)

Example

#Legal variable names:


myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

#Illegal variable names:


2myvar = "John"
my-var = "John"
my var = "John"

Q.2 What will the last value of i in case of the range(1,8)? Justify your answer.
ANS: The last value will be 7 because range() function gives output up to last number. The range() function returns a
sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a
specified number.

for i in range(1,8):
print(i)

Output

7() function
Note: As you can see in the output, We got six integers starting from 0 to 5. If you
notice, range() didn’t include 6 in its result because it generates numbers up to the stop
number but never includes the stop number in its result.

Q.3 Explain the syntax to create variable in Python program.

ANS: name_of_variablre = value of variable

Q.4 Give any differences between for loop and while loop.

ANS:

Basis of
For Loop While Loop
Comparison

Keyword Uses for keyword Uses while keyword

Used For loop is used when the While loop is used when the
number of iterations is already number of iterations is already
known. Unknown.

absence of The loop runs infinite times in Returns the compile time error in
condition the absence of condition the absence of condition

Nature of Once done, it cannot be In the while loop, it can be


Initialization repeated repeated at every iteration.

Functions To iterate, the range or xrange There is no such function in the


function is used. while loop.

Initialization To be done at the beginning of In the while loop, it is possible to


based on the loop. do this anywhere in the loop body.
iteration

Generator Python's for loop can iterate While loops cannot be directly
Support over generators. iterated on Generators.

Speed The for loop is faster than the While loop is relatively slower as
while loop. compared to for loop.

Q.5 What is an indentation in python Program?


ANS: Indentation refers to the spaces at the beginning of a code line.Where in other
programming languages the indentation in code is for readability only, the indentation in
Python is very important.
1. Python uses indentation to indicate a block of code.

if 5 > 2:
print("Five is greater than two!")

2. Python will give you an error if you skip the indentation:

Example
Syntax Error:

if 5 > 2:
print("Five is greater than two!")

3. The number of spaces is up to you as a programmer, but it has to be at least one.

Example
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")

4. You have to use the same number of spaces in the same block of code, otherwise
Python will give you an error:

Example
Syntax Error:

if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")

Q.6 Why Python is called as dynamically typed language?

ANS: Python is a dynamically typed language. What is dynamic? We don't have to declare the type
of a variable or manage the memory while assigning a value to a variable in Python. Other languages
like C, C++, Java, etc.., there is a strict declaration of variables before assigning values to them. We
have to declare the kind of variable before assigning a value to it in the languages C, C++, Java, etc..,
Python don't have any problem even if we don't declare the type of variable. It states the type of
variable in the runtime of the program. Python also take cares of the memory management which is
crucial in programming. So, Python is a dynamically typed language. Let's see one example.

Example
x = [1, 2, 3]
print(type(x))
x = True
print(type(x))

Output.
<class 'list'>
<class 'bool'>
As you see, we didn't declare the type of variable in the program. Python will automatically recognize
the type of variable with the help of the value in the runtime.

You might also like