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

Python QB ct1

The document discusses various Python concepts like data types, operators, control flow statements, and modules. It provides examples and explanations of numeric, string, list, tuple, and set data types. It also covers identity, membership, logical operators, if-else conditional statements, for loops, functions of operators like floor division, exponentiation, and modulus.

Uploaded by

mbhoomi23
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Python QB ct1

The document discusses various Python concepts like data types, operators, control flow statements, and modules. It provides examples and explanations of numeric, string, list, tuple, and set data types. It also covers identity, membership, logical operators, if-else conditional statements, for loops, functions of operators like floor division, exponentiation, and modulus.

Uploaded by

mbhoomi23
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

ASSIGNMENT 01

1. List features of Python

Easy to code:-
Python is a high level language. Python is very easy to learn the
language as compared to C, C++, Javascript, Java , etc.
It is very easy to code in python as the syntax is comparatively
easy. It is also a developer friendly language.

Object Oriented Language:-


One of the key features of python is Object-Oriented programming.
Python supports OOP and features like classes, objects,
encapsulation, etc.

Free and Open Source:-


Python language is freely available at the official website

Dynamically Typed Language:-


Python is a dynamically typed language. This means that type of
variable is decided at run time not in advance because of this
feature we don’t need to specify the type of variable

2. Determine various data types available in Python with example

Numeric:-
Numeric value can be integer, floating number or even complex
numbers.
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 specified by a
decimal point.
Complex Numbers – Complex number is represented by complex
class. It is specified as (real part) +
(imaginary part)j. For example – 2+3j

In Python, sequence is the ordered collection of similar or different


data types. Sequences allows to store
multiple values in an organized and efficient fashion. There are
several sequence types in Python –

String
In Python, Strings are arrays of bytes representing Unicode
characters. A string is a collection of one
or more characters put in a single quote, double-quote or triple
quote. In python there is no character
data type, a character is a string of length one. It is represented
by str class.

1. List
Lists are just like the arrays, declared in other languages which
is a ordered collection of data. It is very
flexible as the items in a list do not need to be of the same type.

2. Tuple
Just like list, tuple is also an ordered collection of Python
objects. The only difference between tuple and
list is that tuples are immutable i.e. tuples cannot be modified
after it is created. It is represented by tuple
class.

Example:-
my_tuple = (1,2,3,4,5)
my_list = [1,2,3,4,5]
my_set = {"1":"ONE",
"2": "TWO"}
my_int = 10
my_float = 12.12
my_string = "Hello"
print("List",my_list)
print("Tule",my_tuple)
print("Integer",my_int)
print("Float",my_float)
print("String",my_string)
print("set",my_set)
3. Compare Interactive mode and Script mode.

4. Explain Building blocks of python

Variables:-
Variable is a name that is used to refer to memory location.
Python variable is also known as an
identifier and used to hold value.
In Python, we don't need to specify the type of variable because
python is a dynamically typed language.
Variable names can be a group of both the letters and digits,
but they have to begin with a letter or
an underscore.
It is recommended to use lowercase letters for the variable
name. Rahul and rahul both are two
different variables.

KeyWords:-
Python Keywords are special reserved words that convey a
special meaning to the compiler/interpreter.
Each keyword has a special meaning and a specific operation.
These keywords can't be used as a variable.
Comments
Python Comment is an essential tool for the programmers.
Comments are generally used to explain the
code. We can easily understand the code if it has a proper
explanation.

Single line comment:-


# This is the print statement
print("Hello Python")

Multiline comment:-
''' This is a multiline comment It spans multiple lines Python will
ignore these lines when executing
the code '''

Indentation:-
Python indentation refers to
adding white space before a statement to a particular block of
code. In another word, all the statements
with the same space to the right, belong to the same code
block. To indicate a block of code in Python,
you must indent each line of the block by the same whitespace.

Example:-
j=1
while(j<= 5):
print(j)
j=j+1
#this is an indentation
5. Write steps to install python and run the python code:-

1. Download Python:
• Visit the official Python website:
https://www.python.org/downloads/.
• Click on the "Downloads" tab and choose the latest
version of Python for Windows.
• Download the installer (usually a .exe file).
2. Run the Installer:
• Double-click on the downloaded .exe file.
• Check the box that says "Add Python x.x to PATH" during
installation.
• Click "Install Now."
3. Verify Installation:
• Open a command prompt (cmd) and type python --
version or python -V. It should display the installed
Python version.

Running Python Code:


1. Create a Python File:
• Open a text editor (e.g., Notepad, VSCode, Atom).
• Write your Python code in the editor and save it with a
.py extension (e.g., myscript.py).
2. Run Python Code:
• Open a terminal or command prompt.
• Navigate to the directory where your Python file is
saved using the cd command.
• Run the script by typing python myscript.py (replace
"myscript.py" with the actual filename).
ASSIGNEMNT 02

1. List identity operators and explain with example

They are used to check if two values (or variables) are located on
the same part of the memory or not. Two variables that are equal
does not imply that they are identical

is operator:- is operator returns True if both variables refer to


the same object, otherwise, it returns False.

is not operator:- is not operator returns True if both variables


do not refer to the same object, otherwise, it returns False.

Example:-

2. Explain two membership and two logical operators with


appropriate example

Membership operators:-
They are used to test whether a value or variables is found in a
sequence or not.

in operator:-
returns True if the value/variable is found in the sequence
Syntax:- element in sequence
not in operator:-
returns True if the value/variable is not found in the sequence
Syntax:- element not in sequence
Logical Operators

Logical operators are used to manipulate the logic of Boolean


expression

and - Logical AND (all True then only True)


or - Logical OR (Any one True then True)
not - Logical NOT (Inverts)

Exmaple:-
x1 = True
x2 = True
if x1 and x2:
print("Logical And is true")
print("Use of Logical Not",not x1)

3. Write the use of elif keyword in python

The elif statement enables us to check multiple conditions and


execute the specific block of statements depending upon the true
condition among them.

elif Clause short for "else if", provides an alternative condition to


test if the preceding conditions are false.

The optional else clause provides a default action when none of


the preceding conditions are true

Syntax:-
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements

Example:-
score = int(input("Enter your score: "))
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
else:
grade = 'F'
print("Your grade is:", grade)

4. WAP to display output like this 2 4 6 8 10 12 14 16 18

for i in range(2,19,2):
print(i, end=" ")

5. Describe the role of indentation in python


Indentation:-
Python indentation refers to adding white space before a
statement to a particular block of code. In another word, all the
statements with the same space to the right, belong to the same
code block. To indicate a block of code in Python, you must indent
each line of the block by the same whitespace.

Example:-
j=1
while(j<= 5):
print(j)
j=j+1
#this is an indentation
6. Explain use of pass and else keywords with for loops in python

Pass statement:-
● It is generally used as a placeholder for future code i.e. in cases
where you want to implement some part of your code in the future
but you cannot leave the space blank as it will give a compilation
error.
● Sometimes, pass is used when the user does not want any code
to execute.
● Using the pass statement in loops, functions, class definitions,
and if statements, is very useful as empty code blocks are not
allowed in these.

Else statement:-
The else block is placed just after the for or while loop.
It is executed only when the loop is not terminated by break
statement.
Else statement with for loop
For variable in sequence:
Body of for loop
else:
statement
Example of pass and else :-
for i in range(2,19,2):
if i == 4:
pass
print(i)
else:
print("This is the statement after loop is completed and not
terminated by break")
7. Mention the use of //, **, % operator in python

// - Floor Division -
The floor division operator divides on value by second value and
gives their quotient rounded to the next smallest whole number

Example:-
x1 = 11
x2 = 32
print("Floor Division", x2//x1)

** - Exponential
The exponential operator raises on value to power of second value

Example:-
x1 = 10
x2 = 2
print("Exponentioal operator", x1**x2)
% - modulus operator
The modulus operator divides one value by second value and
gives the remainder

Example:-
x1 = 10
x2 = 2
print("Modulus operator", x1%x2)

8. List and explain comparison operator


Operator Name Working
== Equal to Returns true if
both the values
are equal else
false
!= Not equal to Returns true if
both the values
are not equal else
false
> Greater than Returns true if
operand1 is
greater than
operand2 else
false
< Less than Returns true if
operand1 is less
than operand2
else false
>= Greater than equal to Returns true if
operand1 is
greater or equal
to than operand2
else false
<= Less than equal to Returns true if
operand1 is less
than or equal to
operand2 else
false

Example:-

a, b = 10, 20
print(a == b) # since the values 10 and 20 are different, the output
of this print statement is False
print(a != b) # since both the values are not equal, the output of
this print statement is True
print(a > b) # the value 10 is less than 20, hence the output of this
print statement is False
print(a < b) # since the value 10 is less than 20, the output of this
print statement is True
print(a >= b) # Since the value 10 is less than 20, the output of this
print statement is False
print(a <= b) # Since the value 10 is less than 20, the output of this
print statement is True
9. Write a program for else if ladder in python
score = int(input("Enter your score: "))
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
else:
grade = 'F'
print("Your grade is:", grade)

10 . Write a program to find greatest of 4 numbers


num1 = int(input("Enter num1: "))
num2 = int(input("Enter num2: "))
num3 = int(input("Enter num3: "))
num4 = int(input("Enter num4: "))
if num1 > num2 and num1 > num3 and num1 > num4:
greaest = num1
elif num2 > num2 and num2 > num3 and num2 > num4:
greaest = num2
elif num3 > num1 and num3 > num2 and num3 > num4:
greaest = num3
else:
greatest = num4
print("Greatest: ",greatest)

Write a program to display output like.


3
6 9 12
15 18 21 24 27

11.Write a program to find factorial of a number provided by the user.

num = int(input("Enter num: "))


fact = 1
for i in range(1,num+1):
fact = fact * i
print(fact)

12.Write a program to explain the use of pass and break in for loop.

for i in range(1,10):
if i == 7:
break
elif 1 == 2:
pass
else:
print(i)
print("This is after break statement")
13. Give difference between list and tuple.
List Tuple
List is mutable Tuple is immutable
List are enclosed with “[]” Tuple are enclosed with “()”
List consume more memory Tuples consumes less memory
as compared to lists
List better for performing A tuple data type is appropriate
operations such as insertion and for accessing the elements
deletion

14.Explain slicing in list.

List slicing refers to accessing a specific portion or a subset of a list


while the original list remain unaffected

Syntax:-
Slice = <ListName>[startIndex : endIndex : step]

The start index represents the value from where the slicing should be
started or begin. By default value is 0.

The stop index represents the last index up to which the list slicing
will go on. The default value is (length(list)-1)

The step represents the number of steps. It is optional . By default it


is 1
Example:-
my_list = [1,2,3,4,5]
print("Negative stepping",my_list[::-1])
print("Mentioning all three param",my_list[1:5:2])
print("Without specifying step",my_list[1:5])
print("Without specifying start and step",my_list[1::])

15. Write a program to perform following operations on Set

1. Union
2. Intersection
3.Difference
4.symmetric difference

set1 = {1,2,3,4,5,6}
set2 = {1,2,4,5,6,0,9,11,12}

print("Union", set1|set2)
print("Intersection",set1&set2)
print("Difference" ,set1-set2)
print("Symmetric difference", set1^set2)
16.Write a program to create dictionary of students that includes
their Roll no and Name.
i) Add three Students in above dictionary.
ii) Update name='meeta' of Roll n0=3
ii) Delete information of Roll no=2

my_dict = {1:"Bhumika",
2:"Jiya",
3:"Mohit",
4:"Palak"}
print("Before updating roll no. 3", my_dict)
my_dict[3]="meeta"
print("After updating roll no. 3",my_dict)
my_dict.pop(2)
print("After deleting the info of roll no. 2",my_dict)

17. Comapre list and dictionary.


18. Explain mutable and immutable data structure.

Mutable Data Structures:


Definition: Mutable data structures are those whose state (content)
can be changed or modified after the object is created.
Examples: Lists, dictionaries, sets, and most user-defined objects in
Python are mutable.
List:
Definition: A list is an ordered and mutable sequence of elements,
enclosed in square brackets [].
Dictionary:
Definition: A dictionary is an unordered and mutable collection of
key-value pairs, enclosed in
curly braces {}.

Immutable Data Structures:


Definition: Immutable data structures are those whose state cannot
be changed after the object is created.
Examples: Tuples, strings, and numeric types (int, float) in Python are
immutable.
tuple:
Definition: A tuple is an ordered and immutable sequence of
elements, enclosed in parentheses ()
String:
Definition: A string is an ordered and immutable sequence of
characters, enclosed in single or double quotes.

19. Write a program to explain pop,update,values,keys,items,


fromkey, copy,clear methods of dictionary.

my_dict = {1:"Bhumika",
2:"Jiya",
3:"Mohit",
4:"Palak"}
print("Original dict:",my_dict)
my_dict.pop(2)
print("Using pop and removing roll no 2",my_dict)
my_dict[5]=["Naish"]
print("Adding roll no 5",my_dict)
my_dict.update({1:"Bhumika Bhatia"})
print("Updating roll no 1",my_dict)
print("Values of dict", my_dict.values())
print("Keys of dict", my_dict.keys())
print("Items of dict", my_dict.items())
my_dict2 = my_dict.copy()
print("Created a copy of my_dict",my_dict2)
x = {2,3,4}
y = {0}
my_dict = dict.fromkeys(x,y)
print("from keys",my_dict)
print("CLearing the dict",my_dict.clear())

20.Write down the output of following


T=('spam','Spam','SPAM','SaPm')
print(T[3])
print(T[-3])
print(T[1:])
print(list(T))

You might also like