Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
33 views

Python Material

The document discusses the Python installation process and the two modes of using the Python interpreter. It describes downloading and installing Python, verifying the installation, and setting the path variable. It also explains running Python in interactive and script modes, and when each mode is better to use.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Python Material

The document discusses the Python installation process and the two modes of using the Python interpreter. It describes downloading and installing Python, verifying the installation, and setting the path variable. It also explains running Python in interactive and script modes, and when each mode is better to use.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

1.

Discuss about python installation process/the two modes of using


python interpreter?
Python Installation:
There are many interpreters available freely to run Python scripts like
IDLE (Integrated Development Environment) which is installed when you
install the python software from http://python.org/downloads/
Steps to be followed and remembered:
Step 1: Select Version of Python to Install.
Step 2: Download Python Executable Installer.
Step 3: Run Executable Installer.
Step 4: Verify Python Was Installed On Windows.
Step 5: Verify Pip Was Installed.
Step 6: Add Python Path to Environment Variables (Optional)

There are many interpreters available freely to run Python scripts like
IDLE (Integrated Development Environment) which is installed when
you install the python software from http://python.org/downloads/
Working with Python
Source code you type is translated to byte code, which is then run by
the Python Virtual Machine (PVM). Your code is automatically
compiled, but then it is interpreted.
Source Byte code Runtime

m.py m.pyc PVM

Source code extension is


.py
Byte code extension is .pyc (Compiled
python code)
There are two modes for using the Python interpreter:
• Interactive Mode
• Script Mode

Running Python in interactive mode:

Without passing python script file to the interpreter, directly


execute code to Python prompt. Once you are inside the python
interpreter, then you can start.

>>> print("hello world")

hello world

# Relevant output is displayed on subsequent lines without the


>>> symbol

Running Python in script mode:

Alternatively, programmers can store Python script source


code in a file with the .py extension, and use the interpreter to
execute the contents of the file. To execute the script by the
interpreter, you have to tell the interpreter the name of the file.
For example, if you have a script name MyFile.py and you're
working on Unix, to run the script you have to type:

python MyFile.py

Working with the interactive mode is better when Python


programmers deal with small pieces of code as you can type and
execute them immediately, but when the code is more than 2-4
lines, using the script for coding can help to modify and use the
code in future.
2. What are the features of Python?

Python and its features:

Python is the world's most popular and fastest-growing computer


programming language. It was developed by Guido van Rossum in 1991.

Features of Python:

1. Python is object-oriented structure supports such concepts


as classes, objects, inheritance and polymorphism.
2. Indentation:
Indentation is one of the greatest feature in python.
3. It‟s free and open source software:
Downloading python and installing python is free and easy.
4. Portable Language:
Python runs virtually every major platform used today.
5. Interpreted Language:
Python is processed at runtime by python Interpreter.
6. Interactive Programming Language:
Users can interact with the python interpreter directly for
writing the programs.
7. Straight forward syntax:
The formation of python syntax is simple and straight forward
which also makes it popular.

8. Python is a widely used general-purpose, high level programming


language.

9. Python is a dynamic typed programming language.

10. Python is a cross-platform independent programming language.

11. Python is an extensible and embedded programming language.

12. Python is a powerful and it is easy to learn and use.


3. Discuss about standard data types in Python?

Standard Data Types in Python:


A data type is the classification of the type of values that can be
assigned to variables.
In Python, user no need to declare a variable with explicitly mentioning
the data type, but it‟s still important to understand the different types of
values that can be assigned to variables in Python.
After all the data type of a variable is decided based on the value
assigned.

Python data types are categorized into two as follows:


1. Mutable Data Types: Data types in python
where the value assigned to a variable can be
changed.

Ex:Lists,Dictionary,Sets
2. Immutable Data Types: Data types in python
where the value assigned to a variable cannot be
changed.
Ex:int,float,complex,Boolean,Strings,Tuples

1.int:
int, or integer, is a whole number, positive or negative, without decimals,
of unlimited length.
2.float:
float, or "floating point number" is a number, positive or negative,
containing one or more decimals.
3.Boolean:
Objects of Boolean type may have one of two values, True or False:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
4.Complex:
Complex number is represented by complex class. It is specified as
(real part) + (imaginary part)j.

For example – 2+3j

Examples:
# Python program to demonstrate numeric
value a = 5
print("Type of a: ",
type(a)) b = 5.0
print("\nType of b: ",
type(b)) c = 2 + 4j
print("\nType of c: ", type(c))

5.String data type

A string is a collection of one or more characters enclosed within a single


quote, double-quote or triple quote.
In python there is no character data type and it is represented by str class.

Example:

String1='Welcome to the World'


print(String1)

6. List data type

List is a collection of mixed data types which is ordered and changeable.


List allows duplicate members.
List is written with square brackets.

Example:
list=[501,"Raju", “1st Year”, "CSE"]
print(list)

7.Tuple data type


Tuple is a collection of mixed data types which is ordered and
unchangeable.
Tuple allows duplicate members.
Tuples are written with rounded brackets.

Example:
tuple=(501,"Raju", “1st Year”, "CSE")
print(tuple)

8.Dictionary data type


A dictionary is a collection of mixed data types which is unordered,
changeable and indexed.
In python dictionaries are written with curly brackets, and they have keys
and values.

Example:
dict={"Name":"Raju","Rollno":501,"Year":"1st Year":,"Branch":"CSE"}
print(dict)

9.Set data type


Set is a collection of mixed data types which are unordered and
unindexed.
Set doesn‟t allow duplicate members.
Sets are written with curly brackets.

Example:
set={501,"Raju", “1st Year”, "CSE"}
print(set)
4. Define a set? Illustrate any 5 functions/methods on set with
examples?

Set data type and its methods in Python:

Set is a collection of mixed data types which are unordered and


unindexed.
Set doesn‟t allow duplicate members.
Sets are written with curly brackets.

Example:
set={501,"Raju", “1st Year”, "CSE"}
print(set)

Set methods in Python:

1.add():
The add() method adds an element to the set.

Syntax:
set.add(element)

Example:
>>> x={"mrcet","college","cse","dept"}
>>>x.add("autonomous")
>>> x
{'mrcet', 'dept', 'autonomous', 'cse', 'college'}

2.remove ():
The remove() method removes the specified element from the set.

Syntax:
set.remove(element)

Example:
>>> x={1, 2, 3, 'a', 'b'}
>>>x.remove(3)
>>> x
{1, 2, 'a', 'b'}

3. length():
The len() method is used to find the number of items or values present in a
set.
Syntax:
len(set)
Example:
>>> z={'mrcet', 'dept', 'autonomous', 'cse', 'college'}
>>>len(z)
5

4.clear:
The clear() method removes all items from the set.
Syntax:
set.clear()
Example:
>>> x={1,2,3,4,5,6,7}
>>>x.clear()
>>> x
set()

5.pop():
The pop() method removes a random item from the set. This method
returns the removed item.
Syntax:
set.pop()
Example:
>>> x={1, 2, 3, 4, 5, 6, 7, 8}
>>>x.pop()
1
>>> x
{2, 3, 4, 5, 6, 7, 8}

5. Define a string? Illustrate any 5 functions/methods on string with


examples?

String data type and its methods in Python:

A string is a collection of one or more characters enclosed within a single


quote, double-quote or triple quote.
In python there is no character data type and it is represented by str class.

Example:

String1='Welcome to the World'


print(String1)

String methods in Python:

1.isalnum():
The isalnum() method returns True if all the characters are alphanumeric,
meaning alphabet letter (a-z) and numbers (0-9), otherwise returns False.
Syntax:
string.isalnum()
Example:
>>> string="123alpha"
>>>string.isalnum()
True
2.isalpha():
The isalpha() method returns True if all the characters are alphabet letters
(a-z), otherwise returns False.
Syntax:
string.isalpha()
Example:
>>> string="nikhil"
>>>string.isalpha()
True

3.isdigit():
The isdigit() method returns True if all the characters are digits, otherwise
returns False.
Syntax:
string.isdigit()
Example:
>>> string="123456789"
>>>string.isdigit()
True

4.islower():
The islower() method returns True if all the characters are in lower case,
otherwise returns False.
Syntax:
string.islower()
Example:
>>> string="nikhil"
>>>string.islower()
True

5.isnumeric():
The isnumeric() method returns True if all the characters are numeric (0-
9), otherwise returns False.
Syntax:
string.isnumeric()
Example:
>>> string="123456789"
>>>string.isnumeric()
True

6.isspace():
The isspace() method returns True if all the characters in a string are
whitespaces, otherwise returns False.
Syntax:
string.isspace()
Example:
>>> string=" "
>>>string.isspace()
True

7.istitle()
The istitle() method returns True if all words in a text start with a upper
case letter, and the rest of the word are lower case letters, otherwise
returns False.
Syntax:
string.istitle()
Example:
>>> string="Nikhil Is Learning"
>>>string.istitle()
True

8.isupper()
The isupper() method returns True if all the characters are in upper case,
otherwise returns False.
Syntax:
String.isupper()
Example:
>>> string="HELLO"
>>>string.isupper()
True

9.replace()
The replace() method replaces a specified old string with another new
string.
Syntax:
string.replace()
Example:
>>> string="Nikhil Is Learning"
>>>string.replace('Nikhil','Neha')
'Neha Is Learning'

10.split()
The split() method splits a string into a list according to delimiter string.
Syntax:
string.split()
Example:
>>> string="Nikhil Is Learning"
>>>string.split()
['Nikhil', 'Is', 'Learning']

11.count()
The count() method returns the number of times a specified value appears
in the string.
Syntax:
string.count()
Example:
>>> string='Nikhil Is Learning'
>>>string.count('i')
3
12.find()
The find() method searches the string for a specified value and returns the
position of where it was found.
Syntax:
string.find(“string‟)
Example:
>>> string="Nikhil Is Learning"
>>>string.find('k')
2

13.swapcase()
The swapcase() method is used for converting lowercase letters in a string
to uppercase letters and vice versa.
Syntax:
string.swapcase()
Example:
>>> string="HELLO"
>>>string.swapcase()
'hello'

14.startswith()
The startswith() method returns True if the string starts with the specified
value, otherwise returns False.
Syntax:
string.startswith(“string‟)
Example:
>>> string="Nikhil Is Learning"
>>>string.startswith('N')
True

15.endswith()
The endswith() method returns True if the string ends with the specified
value, otherwise returns False.
Syntax:
string.endswith(“string‟)
Example:
>>> string="Nikhil Is Learning"
>>>string.endswith('g')
True

6. Define a list? Illustrate any 5 functions/methods on list with


examples?

List data type and its methods in Python:

List is a collection of mixed data types which is ordered and changeable.


List allows duplicate members.
List is written with square brackets.

Example:
list=[501,"Raju", “1st Year”, "CSE"]
print(list)

List methods in Python:

1.append:
The append() method adds an item to the end of the list.
Syntax:
list.append(item)
Example:
>>> x=[1,5,8,4]
>>>x.append(10)
>>> x
[1, 5, 8, 4, 10]

2.extend:
The extend() method adds the specified list elements to the end of the
current list.
Syntax:
list.extend(newlist)
Example:
>>> x=[1,2,3,4]
>>> y=[3,6,9,1]
>>>x.extend(y)
>>> x
[1, 2, 3, 4, 3, 6, 9, 1]

3.insert:
The insert() method inserts the specified value at the specified position.
Syntax:
list.insert(position,item)
Example:
>>> x=[1,2,4,6,7]
>>>x.insert(2,10)
>>> x
[1, 2, 10, 4, 6, 7]

4.pop:
The pop() method removes the item at the given index from the list and
returns the removed item.
Syntax:
list.pop(index)
Example:
>>> x=[1, 2, 10, 4, 6]
>>>x.pop(2)
10
>>> x
[1, 2, 4, 6]

5.remove:
The remove() method removes the specified item from a given list.
Syntax:
list.remove(element)
Example:
>>> x=[1,33,2,10,4,6]
>>>x.remove(33)
>>> x
[1, 2, 10, 4, 6]

6.reverse:
The reverse() method reverses the elements of the list.
Syntax:
list.reverse()
Example:
>>> x=[1,2,3,4,5,6,7]
>>>x.reverse()
>>> x
[7, 6, 5, 4, 3, 2, 1]

7.sort:
The sort() method sorts the elements of a given list in ascending order.
Syntax:
list.sort()
Example:
>>> x=[10,1,5,3,8,7]
>>>x.sort()
>>> x
[1, 3, 5, 7, 8, 10]
8.clear:
The clear() method removes all items from the list.
Syntax:
list.clear()
Example:
>>> x=[1,2,3,4,5,6,7]
>>>x.clear()
>>> x
[]
9. length():
The len() method is used to find the number of items or values present in a
list.
Syntax:
len(list)
Example:
>>> x=[1,2,3,4,5]
>>> len(x)
5
7. Define a tuple? Illustrate any 3 functions/methods on tuple with
examples?

Tuple data type and its methods in Python:

Tuple is a collection of mixed data types which is ordered and


unchangeable.
Tuple allows duplicate members.
Tuples are written with rounded brackets.

Example:
tuple=(501,"Raju", “1st Year”, "CSE")
print(tuple)

Tuple methods in Python:

1.count():
The count() method returns the number of times a specified value appears
in the tuple.
Syntax:
tuple.count(value)
Example:
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>>x.count(2)
4
2.index():
The index() method searches the tuple for a specified value and returns the
position of where it was found.
Syntax:
tuple.index(value)

Example:
>>> x=(1,2,3,4,5,6)
>>>x.index(2)
1
3. length():
The len() method is used to find the number of items or values present in a
tuple.
Syntax:
len(tuple)
Example:
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> len(x)
12
8. Define a dictionary? Illustrate any 5 functions on lists with
examples?

Dictionary data type and its methods in Python:

A dictionary is a collection of mixed data types which is unordered,


changeable and indexed.
In python dictionaries are written with curly brackets, and they have keys
and values.

Example:
dict={"Name":"Raju","Rollno":501,"Year":"1st Year":,"Branch":"CSE"}
print(dict)

Dictionary methods in Python:

1.update():
The update() method inserts the specified items to the dictionary.

Syntax:
dictionary.update({“keyname”:”value”})
Example:
>>> dict={"brand":"mrcet","model":"college","year":2004}
>>> dict.update({"cse":"dileep"})
>>> dict
{'brand': 'mrcet', 'model': 'college', 'year': 2004, 'cse': 'dileep'}

2.pop():
The pop() method removes the specified item from the dictionary.

Syntax:
dictionary.pop(keyname)
Example:
>>> dict={"brand":"mrcet","model":"college","year":2004}
>>> dict.pop("model"))
college
>>> dict
{'brand': 'mrcet', 'year': 2005}

3.items():

Returns all the items present in the dictionary. Each item will be inside
a tuple as a key-value pair.

Syntax:
dictionary.items()
Example:
dict={"brand":"mrcet","model":"college","year":2004}
>>> dict.items()
dict_items([('brand', 'mrcet'), ('model', 'college'), ('year', 2004)])
4.keys():
Returns the list of all keys present in the dictionary.

Syntax:
dictionary.keys()
Example:
>>> dict={"brand":"mrcet","model":"college","year":2004}
>>> dict.keys()
dict_keys(['brand', 'model', 'year'])
5.values():
Returns the list of all values present in the dictionary
Syntax:
dictionary.values()
Example:
>>> dict={"brand":"mrcet","model":"college","year":2004}
>>> dict.values()
dict_values(['mrcet', 'college', 2004])

6.Length():
The len() method is used to find the number of items present in a
dictionary.
Syntax:
len(dictionary)
Example:
>>>x={1: 1, 2: 4, 3: 9, 4: 16}
>>> len(x)
>>> 4

7.clear():
The clear() method removes all the elements from a dictionary.
Syntax:
dictionary.clear()
Example:
>>> dict={"brand":"mrcet","model":"college","year":2004}
>>> dict.clear()
>>> dict
{}
8.get():
The get() method returns the value of the item with the specified key.
Syntax:
dictionary.get(“keyname”)
Example:
>>> dict={"brand":"mrcet","model":"college","year":2004}
>>> dict.get("model")
'college'

9. Explain different types of operators in python with example


programs?

Operators in Python:

Operators are special symbols that perform specific operations on one or


more operands (values) and then return a result.

Python has seven types of operators that we can use to perform different
operation and produce a result.

1.Arithmetic operator
2.Relational operators
3.Assignment operators
4.Logical operators
5.Membership operators
6.Identity operators
7.Bitwise operators

1.Arithmetic operators:
Arithmetic operators are used to perform different mathematical
operations between the operands.

Python has the following seven arithmetic operators.

+ (Addition)
- (Subtraction)
* (Multiplication)
/ (Division)
// Floor division)
℅ (Modulus)
** (Exponentiation)

2.Relational (Comparison) operators:


Relational operators are also called comparison operators. It performs a
comparison between two values. It returns a boolean True or False
depending upon the result of the comparison.

Python has the following six relational operators.

> (Greater than)


< (Less than)
== (Equal to)
!= (Not equal to)
>= (Greater than or equal to)
<= (Less than or equal to)

3.Assignment operators:
In Python, Assignment operators are used to assigning value to the
variable. Assign operator is denoted by = symbol. For example, name =
"Raju" here, we have assigned the string literal „Raju‟ to a variable name.

Also, there are shorthand assignment operators in Python.


Python has the following assignment operators.

= (Assign)
+= (Add and assign)
-= (Subtract and assign)
*= (Multiply and assign)
/= (Divide and assign)
%= (Modulus and assign)
**= (Exponentiation and assign)
//= (Floor-divide and assign)

4.Logical operators:
Logical operators are useful when checking a condition is true or not.
Python has three logical operators. All logical operator returns a boolean
value True or False depending on the condition in which it is used.

Python has the following three relational operators.


and (Logical and)
or (Logical or)
not (Logical not)

5.Membership operators:
Membership operators are used to check for membership of objects in
sequence, such as string, list, tuple. It checks whether the given value or
variable is present in a given sequence. If present, it will return True
otherwise False.

Python has the following two membership operators.


in
not in

6.Identity operators:
Identity operators are used to check whether the value of two variables are
same or not. If same, it will return True otherwise False.

Python has the following two identity operators.


is
is not.

7.Bitwise Operators:
In Python, bitwise operators are used to performing bitwise operations on
integers. To perform bitwise, we first need to convert integer value to
binary (0 and 1) value.

The bitwise operator operates on values bit by bit, so it‟s called bitwise. It
always returns the result in decimal format.

Python has the following 6 bitwise operators.

& (Bitwise and)


| (Bitwise or)
^ (Bitwise xor)
~ (Bitwise 1‟s complement)
<< (Bitwise left-shift)
>> (Bitwise right-shift)

10. Explain different types of conditional statements in python with


example programs?

Conditional statements in Python:

Conditional statements are used to execute either a single statement or a


group of statements based on the condition.

There are 3 types of conditional statements in python.


1.if statement
2.if else statement
3.elif statement

1.if statement:
if statement flowchart:
In conditional statements, The if statement is the simplest form.
It takes a condition and evaluates to either True or False.

If the condition is True, then the True block of code will be executed, and
if the condition is False, then the block of code is skipped, and the
controller moves to the next line.

Syntax of the if statement


if(condition):
statement 1
statement 2
statement n

Example
a=int(input('Enter any no'))
if(a>25):
print('Given no is greater than 25')

2.if else statement:


if else statement flowchart:
The if else statement checks the condition and executes the „if‟ block of
code when the condition is True, and if the condition is False, it will
execute the else block of code.

Syntax of the if else statement


if(condition):
statement 1
else:
statement 2

Example
n=int(input('Enter any no'))
if(n%2==0):
print('given no is even')
else:
print('given no is odd')

3. if-elif-else statement/Chained multiple if statement:


if elif else statement flowchart:
In Python, the if-elif-else condition statement has an elif keyword used to
chain multiple conditions one after another. The if-elif-else is useful when
you need to check multiple conditions.

Syntax of the if-elif-else statement


if(condition1):
statement1
elif(condition2):
statement2
elif(condition3):
statement3
...
else:
statement
Example
a=int(input('Enter the value of a '))
b=int(input('Enter the value of b '))
c=int(input('Enter the value of c '))
if((a<b) and (a<c)):
print('a is largest')
elif((b>a) and (b>c)):
print('b is largest')
else:
print('c is largest')

11. Explain different types of loops/iterative/repetition statements in


python with example programs?

Loop/Iterative statements in Python:

In Python, iterative statements allow us to execute a block of code


repeatedly as long as the condition is True. We also call it a loop
statements.

Python provides us the following two loop statement to perform some


actions repeatedly.

1.while loop
2.for loop

1.while loop:
It is used when a group of statements are executed repeatedly until the
specified condition is true.
It is also called entry controlled loop.
The minimum number of execution takes place in while loop is 0.
Syntax:
while(condition):
statement 1
statement 2
statement n
Example
i=1
print("The nos from 1 to 10 are ")
while(i<=10):
print(i)
i=i+1

2.for loop:
In Python, the for loop is used to iterate over a sequence such as a list,
string, tuple, other iterable objects such as range.

With the help of for loop, we can iterate over each item present in the
sequence and executes the same set of operations for each item. Using a
for loop in Python we can automate and repeat tasks in an efficient
manner.

Syntax:
for var in range/sequence:
statement 1
statement 2
statement n
Example
for i in range(1,11,1):
print(i)
12. Explain different types of unconditional statements in python
with example programs?

Unconditional/Jump statements in Python:


Unconditional statements:- Normal flow of control can be transferred
from one place to another place in the program. This can be done by
using the following unconditional statements in python.
There are 3 types of Unconditional statements in python.
They are
1. break
2. continue
3. pass

1.break statement: break is an unconditional statement used to terminate


the loops.
When it is used in loops (while,for) control comes out of the loop and
continues with the next statement in the program.
Syntax:-
statement
break

Example:
for i in range(1,6,1):
if(i==4):
break
printf(i)

2.continue statement: continue is an unconditional statement used to


control to be transferred to the beginning of the loop for the next
iteration without executing the remaining statements in the program.
Syntax:-
statement
continue

Example:
for i in range(1,6,1):
if(i==4):
continue
printf(i)

3.pass statement:
The pass statement is a null statement. But the difference between pass
and comment is that comment is ignored by the interpreter whereas pass
is not ignored.
The pass statement is generally used as a placeholder i.e. when the user
does not know what code to write. So user simply places pass at that
line.
pass is just a placeholder for functionality to be added later. Sometimes,
pass is used when the user doesn‟t want any code to execute.
Syntax:
pass
Example:
a=10

b=20

if(a>b):

pass

13. Write about keywords in python?

Keywords in Python:
Keywords are the reserved words in Python.
We cannot use a keyword as variable name, function name or
any other identifier.

They are used to define the syntax and structure of the Python
language.

In Python, keywords are case sensitive.

There are 33 keywords in Python.

All the keywords except True, False and None are in lower
case and they must be written as it is.

The lists of all the keywords are given below.

14. Define a comment and list out different types of


comments with examples?

Python Comments

Comments are very important while writing a program.


Comments are basically used to make the code more readable
or to know what is exactly going inside the code. In Python,
we use the hash(#) symbol to start writing a comment.
It extends up to the new line character. Comments are for
programmers for better understanding of a program. Python
Interpreter ignores comment.

Single -line comments

Single-line comments begins with a hash(#) symbol and is useful


in mentioning that the whole line should be considered as a
comment until the end of line.

Example

#This is a comment

#print out Hello

print('Hello')

Multi-line comments

If we have comments that extend multiple lines, we can use


triple quotes, either '''or """. These triple quotes are generally
used for multi-line strings. But they can be used as multi-line
comment as well.

Example

"""This is also a

Perfect example of

multi-line comments"""

15. Write about input and output statements in Python?


Python Input [Reading Input from the Keyboard ]

 To allow flexibility we might want to take the input


from the user.

 input operation: reading data that has been typed on the


keyboard

 In Python, input( ) –input function is used to take input


from the user

The syntax for input() is :

variable = input(prompt)

Example:

>>>name = input('What is your name? ')

where prompt is the string we wish to display on the screen. It


is optional.

Python Output Using print( ) function

We use the print( ) function to output data to the standard


output device (screen).

Example

>>>print('This sentence is output to the screen')

# Output: This sentence is output to the screen

>>>a = 5

>>>print('The value of a is', a)


# Output: The value of a is 5

16. Discuss the various ways of defining variables/identifiers in


python?

Python Variables/Identifiers

A variable is a data name which can be used to store some


data value.

The rules for writing a variable name is same as the rules for
writing identifiers in Python. We don't need to declare a
variable before using it. In Python, we simply assign a value
to a variable and it will exist.

We don't even have to declare the type of the variable. This is


handled internally according to the type of value we assign to
the variable.

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)

Single Variable assignment


We use the assignment operator (=) to assign values to a
variable. Any type of value can be assigned to any valid
variable.

Example

a=5

b = 3.2

c = "Hello“

Note: Every Variable in Python is a Object

Multiple variable Assignment

Python allows you to assign a single value to several

variables simultaneously.

For example :

a = b = c = 10
Here, an integer object is created with the value 10, and all three
variables are assigned to the same memory location. You can also
assign multiple objects to multiple variables.

For example :

a,b,c = 1,2,"mrcet”

Here, two integer objects with values 1 and 2 are assigned to variables
a and b respectively, and one string object with the value "mrcet" is
assigned to the variable c.
17. How are type conversions done in python? Illustrate with
suitable examples?

Data Type conversions:


Converting from one data type value to another data type is
called Type casting.
Casting in python is therefore done using constructor functions:
1.int() - constructs an integer number from an integer literal, a float
literal (by rounding down to the previous whole number), or a string
literal (providing the string represents a whole number).
2.float() - constructs a float number from an integer literal, a float
literal or a string literal (providing the string represents a float or
an integer).
3.str() - constructs a string from a wide variety of data types,
including strings, integer literals and float literals.

1.int():

We can use this function to convert values from other types to


int.

Examples:

x = int(1) # x will be 1

y = int(2.8) # y will be 2

z = int("3") # z will be 3

2.float():
We can use float() function to convert other type values to float type.

Examples:

x = float(1) # x will be 1.0

y = float(2.8) # y will be 2.8

z = float("3") # z will be 3.0

w = float("4.2") # w will be 4.2

3.str():
We can use this method to convert other type values to str type.
Examples:

x = str("s1") # x will be 's1'

y = str(2) # y will be '2'

z = str(3.0) # z will be '3.0'

18. Show an example of how precedence of operators effects an


expression evaluation?
When two operators share an operand, the operator with the higher precedence
goes first.
Example

Programs
1. Program for Prime numbers
n=int(input("Enter any number:"))
for i in range(1,n+1,1):
if (i>1):
for j in range(2,i,1):
if(i%j==0):
break
else:
print(i)

2. Program for Prime numbers using functions


def prime(n):
for i in range(1,n+1,1):
if (i>1):
for j in range(2,i,1):
if (i%j==0):
break
else:
print(i)
n=int(input("Enter any number"))
prime(n)
3. Program for Fibonacci sequence
n=int(input("Enter any number"))
first=0
second=1
print("fibonacci series is")
for i in range(1,n+1,1):
print(first)
nextterm=first+second
first=second
second=nextterm

4. Program for Fibonacci sequence using functions


def fibonacii(n):
first=0
second=1
nextterm=0
for i in range(1,n+1,1):
print(first)
nextterm=first+second
first=second
second=nextterm
n=int(input("Enter any number"))
fibonacii(n)

5. Program to check string is palindrome or not


str=input("Enter any string:")
flag=1
length=len(str)
for i in range(0,length,1):
if (str[i]!=str[length-i-1]):
flag=0
break
if (flag==1):
print("The given string is palindrome")
else:
print("The given string is not a palindrome")

6. Program to check string is palindrome or not using functions


def strpal():
flag=1
length=len(str)
for i in range(0,length,1):
if (str[i]!=str[length-i-1]):
flag=0
break
if (flag==1):
print("The given string is palindrome")
else:
print("The given string is not palindrome")
str=input("Enter any string")
strpal()

7. Program to check number is Armstrong or not


n=int(input("Enter any number"))
temp=n
sum=0
while(n>0):
digit=n%10
sum=sum+(digit*digit*digit)
n=n//10
if(temp==sum):
print("Given no is Armstrong")
else:
print("Given no is not a Armstrong")

8. Program to check number is Armstrong or not


def armstrong():
temp=n
sum=0
while(n!=0):
digit=n%10
sum=sum+(digit*digit*digit)
n=n//10
if(temp==sum):
print("Given no is Armstrong")
else:
print("Given no is not a Armstrong")
n=int(input("Enter any number"))
armstrong()

9. Program for sum of individual digits of a number


n=int(input("Enter any number"))
sum=0
while(n!=0):
digit=n%10
sum=sum+digit
n=n//10
print("The sum of individual digits of a given no is ",sum)
10. Program for sum of individual digits of a number using
functions
def sumdigit():
sum=0
while(n>0):
digit=n%10
sum=sum+digit
n=n//10
print("The sum of individual digits of a given no is ",sum)
n=int(input("Enter any number:"))
sumdigit()

11. Program for reverse of a given number


n=int(input("Enter any value"))
reverse=0
while(n!=0):
digit=n%10
reverse=reverse*10+digit
n=n//10
print("the reverse of a given number is ",reverse)
12. Program for reverse of a given number using functions
def reverse(n):
rev=0
while(n>0):
digit=n%10
rev=rev*10+digit
n=n//10
print("the reverse of a given number is ",rev)
n=int(input("Enter any number"))
reverse(n)

13. Program for stack using list


a=[]
n=int(input("Enter the size of stack"))
print("Enter the elements of the stack")
for i in range(0,n):
ele=input()
a.append(ele)
print("The stack elements are ",a)
for i in range(0,n):
print("The deleted element from the stack is",a.pop())

14. Program for queue using list


a=[]
n=int(input("Enter the size of queue"))
print("Enter the elements of the queue")
for i in range(0,n):
ele=input()
a.append(ele)
print("The queue elements are ",a)
for i in range(0,n):
print("The deleted element from the queue is",a.pop())

15. Program for arithmetic operators


a=int(input("Enter a value:"))
b=int(input("Enter b value:"))
print( a+b)
print( a-b)
print(a*b)
print(a//b)
print(a/b)
print(a%b)
print(a**b)

16. Program for relational operators


x = int(input("Enter x value:"))
y = int(input("Enter y value:"))
print("x > y is:",x>y)
print("x < y is:",x<y)
print("x == y is:",x==y)
print("x != y is:",x!=y)
print("x >= y is:",x>=y)
print("x <= y is:",x<=y)

17. Program for largest number among 3 numbers


a=int(input("Enter a value:"))
b=int(input("Enter b value:"))
c=int(input("Enter c value:"))
if( (a>=b) and (a>=c)):
print("largest:",a)
elif ((b>=a) and (b>=c)):
print("largest:",b)
else:
print("largest:",c)

18. Program for print name of the day of a weak using elif statement
n=int(input("Enter n value:"))
if(n==1):
print("sunday")
elif(n==2):
print("monday")
elif(n==3):
print("tuesday")
elif(n==4):
print("wedensday")
elif(n==5):
print("thursday")
elif(n==6):
print("friday")
elif(n==7):
print("saturday")
else:
print("Enter in the number in range of(1,7):")
19. Program for sum of n natural numbers
n=int(input("Enter any number"))
i=1
sum=0
while(i<=n):
sum=sum+i
i=i+1
print("Sum of n natural numbers is ",sum)

20. Program for factorial of a given number


n=int(input("Enter any number"))
i=1
fact=1
while(i<=n):
fact=fact*i
i=i+1
print("The factorial of a given number is ",fact)

You might also like