0% found this document useful (0 votes)
0 views

python QA.

The document provides an overview of Python, covering its definition, features, and application areas such as web development, data science, and automation. It explains the differences between interactive and script modes, as well as mutable and immutable data types, and discusses Python's input and print methods, function definitions, and error types. Additionally, it highlights concepts like list comprehension and the distinctions between lists and tuples.

Uploaded by

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

python QA.

The document provides an overview of Python, covering its definition, features, and application areas such as web development, data science, and automation. It explains the differences between interactive and script modes, as well as mutable and immutable data types, and discusses Python's input and print methods, function definitions, and error types. Additionally, it highlights concepts like list comprehension and the distinctions between lists and tuples.

Uploaded by

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

Short questions

 What do you mean by python ?


 Python एक और language , 1980 क द क
Guido van Rossum क क र syntax और readability क ए

 क web development, data science, machine learning, artificial


intelligence, automation, और scientific computing कई
 Python एक open source . क एकई . क ए क
क र . क GPL (general public license) क
. क ए version क क official क क .
 What is the different between interactive mode and and script mode?
 Interactive Mode:
 Interactive mode ek aisa mode hai jismein aap Python interpreter ke saath directly
interact kar sakte hain. Is mode mein aap apne code ko line-by-line likh sakte hain aur
immediate feedback pa sakte hain.

 Interactive Mode ke lakshan:
 1. Python Interpreter: Interactive mode mein aap Python interpreter ke saath directly
interact karte hain.
 2. Line-by-Line Execution: Interactive mode mein aapka code line-by-line execute
hota hai.
 3. Immediate Feedback: Interactive mode mein aapko apne code ke liye immediate
feedback milta hai.

 Interactive Mode ka upyog:
 1. Testing: Interactive mode bahut useful hota hai jab aap kisi code ko test karna
chahte hain.
 2. Exploration: Interactive mode mein aap Python ki functionality ko explore kar
sakte hain.
 3. Learning: Interactive mode bahut useful hota hai jab aap Python sikhna chahte
hain.

 Script Mode:
 Script mode ek aisa mode hai jismein aap apne code ko ek file mein likhte hain aur
phir use execute karte hain. Is mode mein aapka code batch mein execute hota hai.

 Script Mode ke lakshan:
 1. Code File: Script mode mein aap apne code ko ek file mein likhte hain.
 2. Batch Execution: Script mode mein aapka code batch mein execute hota hai.
 3. No Immediate Feedback: Script mode mein aapko apne code ke liye immediate
feedback nahin milta hai.

 Script Mode ka upyog:
 1. Large Programs: Script mode bahut useful hota hai jab aap kisi bade program ko
likhna chahte hain.
 2. Reusable Code: Script mode mein aap apne code ko reusable bana sakte hain.
 3. Production Environment: Script mode bahut useful hota hai jab aap apne code ko
production environment mein deploy karna chahte hain.
 How to use input() and print() method in python ?
 Python mein input() aur print() do mahatvapurn methods hain jo user ke saath
interact karne mein madad karte hain.

 Input() Method:
 Input() method ka upyog user se input lena hai. Yah method user ko ek prompt deta
hai aur user ka input string ke roop mein return karta hai.

 Input() Method ka Syntax:

 variable_name = input(prompt)

 Input() Method ka Udaaharan:

 name = input("Please enter your name: ")


 print("Hello, " + name)

 Print() Method:
 Print() method ka upyog user ko output dikhana hai. Yah method apne arguments ko
string ke roop mein convert karta hai aur unhein console par print karta hai.

 Print() Method ka Syntax:



 print(object(s), sep=' ', end='\n', file=sys.stdout, flush=False)

 Print() Method ka Udaaharan:

 print("Hello, World!")
 print("Hello", "World!")
 print("Hello", "World!", sep="-")


 Input() aur Print() Method ka Sanyojan:
 Input() aur print() method ka sanyojan karke hum user se input le sakte hain aur
unhein output de sakte hain.

 Udaaharan:

 name = input("Please enter your name: ")
 age = input("Please enter your age: ")
 print("Hello, " + name + "! You are " + age + " years old.")

 how to define function in python?


 Python mein function ko define karne ke liye def keyword ka upyog kiya jata hai.

 Function ka Syntax:

 def function_name(parameters):
 function_body


 Function ka Udaaharan:

 def greet(name):
 print("Hello, " + name)

 greet("John")


 Function ke Components:
 1. Function Name: Function ka naam jo def keyword ke baad aata hai.
 2. Parameters: Function ke andar jo variables pass kiye jate hain.
 3. Function Body: Function ke andar jo code hota hai.

 Function ke Prakaar:
 1. Simple Function: Ek aam function jo kisi bhi kaam ko karta hai.
 2. Parameterized Function: Ek function jo parameters ko accept karta hai.
 3. Return Function: Ek function jo kuch value return karta hai.
 4. Lambda Function: Ek chhota sa function jo lambda keyword ke saath define hota
hai.

 Function ke Fayde:
 1. Code Reusability: Function ko ek se adhik baar upyog kiya ja sakta hai.
 2. Code Organization: Function ko code ko organize karne mein madad karta hai.
 3. Error Handling: Function ko error handling mein madad karta hai.

 What is the difference between list and tuple?

S.No List Tuple

Tuples are immutable(cannot be


1 Lists are mutable(can be modified).
modified).

2 Iteration over lists is time-consuming. Iterations over tuple is faster

Lists are better for performing


Tuples are more suitable for
3 operations, such as insertion and
accessing elements efficiently.
deletion.

4 Lists consume more memory. Tuples consumes less memory

5 Lists have several built-in methods. Tuples have fewer built-in methods.

Lists are more prone to unexpected Tuples, being immutable are less
6
changes and errors. error prone.

 How we declare tuple in python?


Python mein tuple ko declare karne ke liye parentheses () ka upyog kiya jata hai. Tuple mein
elements ko comma , ke through alag kiya jata hai.

Tuple ko Declare Karne ka Syntax:

tuple_name = (element1, element2, element3, ...)

Udaaharan:
# Empty tuple
my_tuple = ()

# Tuple with one element


my_tuple = (1,)

# Tuple with multiple elements


my_tuple = (1, 2, 3, 4, 5)

# Tuple with different data types


my_tuple = ("apple", 1, 3.14)

Note:
- Tuple mein elements ko immutable rakhna hota hai, jiska matlab hai ki tuple mein
elements ko add, remove aur modify nahin kiya ja sakta hai.
- Tuple mein elements ko indexing ke through access kiya ja sakta hai.
- Tuple mein elements ko slicing ke through access kiya ja sakta hai.
 What do you mean by list comprehension?
List comprehension ek prakaar ka syntax hai jo Python mein list ko create karne ke liye
upyog kiya jata hai. Yah syntax list ko create karne ke liye ek concise aur readable tareeka
pradaan karta hai.

List Comprehension ka Syntax:

new_list = [expression for variable in iterable]

Udaaharan:

numbers = [1, 2, 3, 4, 5]
double_numbers = [x * 2 for x in numbers]
print(double_numbers) # Output: [2, 4, 6, 8, 10]

List Comprehension ke Fayde:


1. Concise Syntax: List comprehension ka syntax bahut hi concise hai, jisse code ko likhna
aur padhna aasan ho jata hai.
2. Readable Code: List comprehension se code ko bahut hi readable banaya ja sakta hai,
jisse code ko samajhna aur maintain karna aasan ho jata hai.
3. Efficient: List comprehension se list ko create karne ke liye efficient tareeka pradaan kiya
jata hai, jisse code ki performance mein sudhar hota hai.

List Comprehension ke Nuksan:


1. Complexity: List comprehension ka syntax thoda complex ho sakta hai, jisse naye
programmers ko samajhna mushkil ho sakta hai.
2. Debugging: List comprehension se create kiye gaye list ko debug karna mushkil ho sakta
hai, jisse code ki errors ko find karna mushkil ho sakta hai.
 Define features of python and also define application area of python?
Python ke Features:
1. Easy to Learn: Python ka syntax bahut hi simple aur easy to learn hai.
2. High-Level Language: Python ek high-level language hai, jiska matlab hai ki yeh language
low-level details ko handle karta hai.
3. Interpreted Language: Python ek interpreted language hai, jiska matlab hai ki yeh
language code ko line-by-line execute karta hai.
4. Object-Oriented: Python ek object-oriented language hai, jiska matlab hai ki yeh
language objects aur classes ko support karta hai.
5. Large Standard Library: Python ki ek large standard library hai jo various tasks ko perform
karne ke liye modules aur functions ko provide karti hai.
6. Cross-Platform: Python ek cross-platform language hai, jiska matlab hai ki yeh language
various operating systems par chal sakta hai.
7. Open-Source: Python ek open-source language hai, jiska matlab hai ki yeh language free
mein available hai aur iske source code ko modify kiya ja sakta hai.

Python ke Application Areas:


1. Web Development: Python ka upyog web development ke liye kiya ja sakta hai, jaise ki
Django aur Flask frameworks.
2. Data Science: Python ka upyog data science ke liye kiya ja sakta hai, jaise ki NumPy,
pandas aur scikit-learn libraries.
3. Machine Learning: Python ka upyog machine learning ke liye kiya ja sakta hai, jaise ki
TensorFlow aur Keras libraries.
4. Automation: Python ka upyog automation ke liye kiya ja sakta hai, jaise ki automating
tasks aur workflows.
5. Scientific Computing: Python ka upyog scientific computing ke liye kiya ja sakta hai, jaise
ki simulating complex systems aur analyzing data.
6. Game Development: Python ka upyog game development ke liye kiya ja sakta hai, jaise ki
Pygame aur Panda3D libraries.
7. Education: Python ka upyog education ke liye kiya ja sakta hai, jaise ki teaching
programming concepts aur principles.
 What do you understand by the terms l-value and r-value?
L-value aur R-value do prakaar ke values hain jo programming mein upyog kiye jate hain.

L-Value:
L-value ek aisa value hota hai jo memory mein ek specific location ko represent karta hai.
Yah value ek variable, array, structure, ya class ka member ho sakta hai. L-value ko assign
karna sambhav hai, jiska matlab hai ki ismein ek naya value assign kiya ja sakta hai.

R-Value:
R-value ek aisa value hota hai jo kisi bhi expression ki evaluation ke baad prapt hota hai.
Yah value ek constant, literal, ya ek expression ka result ho sakta hai. R-value ko assign
nahin kiya ja sakta hai, jiska matlab hai ki ismein ek naya value assign nahin kiya ja sakta hai.

Udaaharan:

x = 5 // x ek L-value hai, 5 ek R-value hai


y = x // y ek L-value hai, x ka value ek R-value hai

Antar:
1. Assignability: L-value ko assign kiya ja sakta hai, jabki R-value ko assign nahin kiya ja sakta
hai.
2. Memory Location: L-value ek specific memory location ko represent karta hai, jabki R-
value ek value ko represent karta hai jo memory mein nahin hota hai.
3. Usage: L-value ko variables, arrays, structures, aur classes mein upyog kiya jata hai, jabki
R-value ko expressions, constants, aur literals mein upyog kiya jata hai.
 What is difference between mutable and immutable data types?
Mutable Data Types:
Mutable data types woh hote hain jinke values ko badalaya ja sakta hai. Yah data types ek
baar create hone ke baad apne values ko modify kar sakte hain.

Udaaharan:
1. List: List ek mutable data type hai jismein elements ko add, remove aur modify kiya ja
sakta hai.
2. Dictionary: Dictionary ek mutable data type hai jismein key-value pairs ko add, remove
aur modify kiya ja sakta hai.
3. Set: Set ek mutable data type hai jismein elements ko add aur remove kiya ja sakta hai.

Immutable Data Types:


Immutable data types woh hote hain jinke values ko badalaya nahin ja sakta hai. Yah data
types ek baar create hone ke baad apne values ko modify nahin kar sakte hain.

Udaaharan:
1. Integer: Integer ek immutable data type hai jiska value badalaya nahin ja sakta hai.
2. Float: Float ek immutable data type hai jiska value badalaya nahin ja sakta hai.
3. String: String ek immutable data type hai jiska value badalaya nahin ja sakta hai.
4. Tuple: Tuple ek immutable data type hai jiska value badalaya nahin ja sakta hai.

Antar:
1. Modifiability: Mutable data types ko modify kiya ja sakta hai, jabki immutable data types
ko modify nahin kiya ja sakta hai.
2. Memory Allocation: Mutable data types ke liye memory allocation dynamic hota hai,
jabki immutable data types ke liye memory allocation static hota hai.
3. Thread Safety: Immutable data types thread-safe hote hain, jabki mutable data types
thread-safe nahin hote hain.
 What are the different types of errors in a python program?
1. Syntax Errors:
Syntax errors woh errors hote hain jo Python interpreter ko code ko parse karne mein rok
dete hain. Yah errors tab hoti hain jab code mein syntax ki galati hoti hai.

Udaaharan:

print("Hello World" # Syntax error: missing closing parenthesis

2. Runtime Errors:
Runtime errors woh errors hote hain jo code ko execute karte samay hoti hain. Yah errors
tab hoti hain jab code mein logical galati hoti hai ya jab code mein koi unexpected situation
aati hai.

Udaaharan:

x = 5 / 0 # Runtime error: division by zero


3. Semantic Errors:
Semantic errors woh errors hote hain jo code ko execute karte samay nahin dikhai deti
hain, lekin code ka output galat hota hai. Yah errors tab hoti hain jab code mein logical
galati hoti hai ya jab code mein koi unexpected situation aati hai.

Udaaharan:

x=5
y=x*2
print(y) # Output: 10, lekin yadi hum x ko 10 kar dete hain, to output 20 hona chahiye

4. Logical Errors:
Logical errors woh errors hote hain jo code ko execute karte samay nahin dikhai deti hain,
lekin code ka output galat hota hai. Yah errors tab hoti hain jab code mein logical galati hoti
hai.

Udaaharan:

x=5
if x > 10:
print("x is greater than 10")
else:
print("x is less than or equal to 10") # Output: x is less than or equal to 10, lekin yadi hum
x ko 15 kar dete hain, to output "x is greater than 10" hona chahiye

5. Exception Errors:
Exception errors woh errors hote hain jo code ko execute karte samay aati hain aur jo code
ko rok deti hain. Yah errors tab hoti hain jab code mein koi unexpected situation aati hai.

Udaaharan:
try:
x=5/0
except ZeroDivisionError:
print("Cannot divide by zero")

unit 1
 A) how many types data types using in python?
Python mein kai prakaar ke data types hote hain:

1. Numeric Data Types:


1. Integers (int): Purnaank hote hain, jaise ki 1, 2, 3, etc.
2. Floating Point Numbers (float): Decimal numbers hote hain, jaise ki 3.14, -0.5, etc.
3. Complex Numbers (complex): Jatil numbers hote hain, jaise ki 3 + 4j, -2 - 3j, etc.

2. Sequence Data Types:


1. Strings (str): Text hote hain, jaise ki "Hello, World!", 'Hello, World!', etc.
2. Lists (list): Ordered collections hote hain, jaise ki [1, 2, 3], ["a", "b", "c"], etc.
3. Tuples (tuple): Ordered, immutable collections hote hain, jaise ki (1, 2, 3), ("a", "b",
"c"), etc.

3. Mapping Data Type:


1. Dictionaries (dict): Unordered collections hote hain, jaise ki {"name": "John", "age":
30}, etc.

4. Set Data Types:


1. Sets (set): Unordered, mutable collections hote hain, jaise ki {1, 2, 3}, {"a", "b",
"c"}, etc.
2. Frozensets (frozenset): Unordered, immutable collections hote hain, jaise ki
frozenset({1, 2, 3}), frozenset({"a", "b", "c"}), etc.

5. Boolean Data Type:


1. Boolean (bool): True ya False hote hain.

6. Binary Data Types:


1. Bytes (bytes): Binary data hote hain, jaise ki b"Hello, World!", etc.
2. Bytearray (bytearray): Mutable binary data hote hain, jaise ki bytearray(b"Hello,
World!"), etc.
3. Memoryview (memoryview): Buffer protocol ko support karte hain, jaise ki
memoryview(b"Hello, World!"), etc.

7. None Data Type:


1. None (NoneType): None hote hain, jo kisi bhi value ko represent nahin karte hain.
 B) define python variable declaration naming rules?
Python mein variable declaration ke liye kuch naming rules hote hain:
Variable Naming Rules:
1. Variable naam alphabets, digits, aur underscore (_) se bana hota hai: Variable
naam mein sirf alphabets, digits, aur underscore (_) ka upyog kiya ja sakta hai.
2. Variable naam alphabet ya underscore (_) se shuru hota hai: Variable naam ka
pehla character alphabet ya underscore (_) hona chahiye.
3. Variable naam mein koi space nahin hota hai: Variable naam mein koi space nahin
hota hai.
4. Variable naam case-sensitive hota hai: Variable naam case-sensitive hota hai, jiska
matlab hai ki 'x' aur 'X' do alag-alag variables hote hain.
5. Variable naam mein koi reserved keyword nahin hota hai: Variable naam mein koi
reserved keyword nahin hota hai, jaise ki 'if', 'else', 'for', 'while', etc.

Reserved Keywords:
Python mein kuch reserved keywords hote hain jo variable naam ke roop mein nahin
use kiye ja sakte hain:

1. and
2. as
3. assert
4. break
5. class
6. continue
7. def
8. del
9. elif
10. else
11. except
12. finally
13. for
14. from
15. global
16. if
17. import
18. in
19. is
20. lambda
21. nonlocal
22. not
23. or
24. pass
25. raise
26. return
27. try
28. while
29. with
30. yield

Udaaharan:

# Sahi variable naam


x=5
y = 10

# Galat variable naam


1x = 5 # SyntaxError: invalid syntax
x y = 10 # SyntaxError: invalid syntax
if = 5 # SyntaxError: invalid syntax
or
 a) What do you mean by blocks in python ?
Python mein blocks ek group hote hain jo statements ko ek saath mein group karte
hain. Yah blocks indentation ke through define kiye jate hain.

Blocks ke Prakaar:
1. Conditional Blocks: Conditional blocks ka upyog if-else statements mein kiya jata
hai.
2. Loop Blocks: Loop blocks ka upyog for aur while loops mein kiya jata hai.
3. Function Blocks: Function blocks ka upyog functions mein kiya jata hai.
4. Class Blocks: Class blocks ka upyog classes mein kiya jata hai.

Blocks ke Liye Indentation:


Python mein blocks ko indentation ke through define kiya jata hai. Indentation ka
matlab hai ki block ke andar ke statements ko kuch spaces ya tabs se indent kiya jata
hai.

Udaaharan:

if x > 5:
print("x is greater than 5")
y=x*2
print("y is", y)

Is udaaharan mein, if statement ke andar ke do statements ko indentation ke through


block mein define kiya gaya hai.

Blocks ke Fayde:
1. Code ko Organize Karta Hai: Blocks code ko organize karte hain aur isse padhne aur
samajhne mein aasan banate hain.
2. Code ko Reusable Banata Hai: Blocks code ko reusable banate hain, jisse hum ek hi
block ko alag-alag jagah par use kar sakte hain.
3. Code ko Debug Karne Mein Madad Karta Hai: Blocks code ko debug karne mein
madad karte hain, jisse hum blocks ke andar ke errors ko aasan se find aur fix kar
sakte hain.
 b) How many types of operators in python?
Python mein kai prakaar ke operators hote hain:

1. Arithmetic Operators:
Arithmetic operators ka upyog mathematical operations ke liye kiya jata hai.

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

2. Comparison Operators:
Comparison operators ka upyog do values ko compare karne ke liye kiya jata hai.

- == (Equal)
- != (Not Equal)
- > (Greater Than)
- < (Less Than)
- >= (Greater Than or Equal)
- <= (Less Than or Equal)
3. Logical Operators:
Logical operators ka upyog conditional statements mein kiya jata hai.

- and (Logical And)


- or (Logical Or)
- not (Logical Not)

4. Assignment Operators:
Assignment operators ka upyog variables ko assign karne ke liye kiya jata hai.

- = (Assignment)
- += (Addition Assignment)
- -= (Subtraction Assignment)
- *= (Multiplication Assignment)
- /= (Division Assignment)
- **= (Exponentiation Assignment)
- //= (Floor Division Assignment)
- %= (Modulus Assignment)

5. Bitwise Operators:
Bitwise operators ka upyog binary numbers ke saath kiya jata hai.

- & (Bitwise And)


- | (Bitwise Or)
- ^ (Bitwise Xor)
- ~ (Bitwise Not)
- << (Left Shift)
- >> (Right Shift)

6. Membership Operators:
Membership operators ka upyog check karne ke liye kiya jata hai ki ek value kisi
sequence mein hai ya nahin.

- in (Membership)
- not in (Non-Membership)

7. Identity Operators:
Identity operators ka upyog check karne ke liye kiya jata hai ki do values ek hi object
ko represent karte hain ya nahin.
- is (Identity)
- is not (Non-Identity)

unit 2

 a) Define the use of pass, continue, break and else with suitable
example?
Pass, continue, break, aur else statements ka upyog loop aur conditional statements
mein kiya jata hai.

Pass Statement:
Pass statement ka upyog ek empty block ya ek function mein kiya jata hai jab hum
kuch bhi nahin karna chahte hain.

Udaaharan:

for i in range(5):
if i == 3:
pass
print(i)

Output:

0
1
2
3
4

Continue Statement:
Continue statement ka upyog loop mein kiya jata hai jab hum ek iteration ko skip
karna chahte hain aur agle iteration par jaana chahte hain.

Udaaharan:
for i in range(5):
if i == 3:
continue
print(i)

Output:

0
1
2
4

Break Statement:
Break statement ka upyog loop mein kiya jata hai jab hum loop ko puri tarah se exit
karna chahte hain.

Udaaharan:

for i in range(5):
if i == 3:
break
print(i)

Output:

0
1
2

Else Statement:
Else statement ka upyog loop ke saath kiya jata hai jab hum loop ke baad ek block ko
execute karna chahte hain jab loop puri tarah se execute ho gaya ho.

Udaaharan:
for i in range(5):
print(i)
else:
print("Loop puri tarah se execute ho gaya")

Output:

0
1
2
3
4
Loop puri tarah se execute ho gaya

Udaaharan 2:
Else statement ka upyog loop ke saath kiya jata hai jab hum loop ko break kar dete
hain aur else block ko execute nahin karna chahte hain.

for i in range(5):
if i == 3:
break
print(i)
else:
print("Loop puri tarah se execute ho gaya")

Output:

0
1
2
 B) How to use range function using for loop with suitable example?
Range function ka upyog for loop ke saath kiya jata hai taaki hum ek sequence ke
sabhi elements par iterate kar sakein.

Range Function ka Syntax:


range(start, stop, step)

Parameters:
- start: Sequence ki starting value.
- stop: Sequence ki ending value.
- step: Sequence mein increment ya decrement ki value.

Udaaharan:
Udaaharan 1:
Ek simple range function ka upyog karke 1 se 5 tak ke numbers print karna.

for i in range(1, 6):


print(i)

Output:

1
2
3
4
5

Udaaharan 2:
Ek range function ka upyog karke 2 se 10 tak ke numbers print karna, lekin 2 ke step
se.

for i in range(2, 11, 2):


print(i)

Output:

2
4
6
8
10

Udaaharan 3:
Ek range function ka upyog karke 10 se 1 tak ke numbers print karna, lekin -1 ke step
se (reverse order).

for i in range(10, 0, -1):


print(i)

Output:

10
9
8
7
6
5
4
3
2
1
or
 a) How to use if,elif and else for decision macking with suitable example?
if condition

The if condition is considered the simplest of the three and makes a decision based on whether
the condition is true or not. If the condition is true, it prints out the indented expression. If the
condition is false, it skips printing the indented expression.

if condition:

expression

POWERED BY
Example of if
Suppose you have a variable z, equal to 4. If the value is 'even', you will print z is 'even'. You will use
modulo operator 2, which will return 0 if z is 'even'. As soon as you run the below code, Python will check if
the condition holds. If True, the corresponding code will be executed.

z=4

if z % 2 == 0: # True

print("z is even")

POWERED BY

z is even

POWERED BY

Example of multiple lines inside if statement


It is perfectly fine to have more lines inside the if statement, as shown in the below example. The script will
return two lines when you run it. If the condition is not passed, the expression is not executed.

z=4

if z % 2 == 0:

print("checking" + str(z))

print("z is even")

POWERED BY

checking 4

z is even

POWERED BY

Example of a False if statement


Let's change the value of z to be odd. You will notice that the code will not print anything since the
condition will not be passed, i.e., False.

z=5

if z % 2 == 0: # False

print("checking " + str(z))


print("z is even")

POWERED BY

POWERED BY

if-else condition

The if-else condition adds an additional step in the decision-making process compared to the
simple if statement. The beginning of an if-else statement operates similar to a simple if statement;
however, if the condition is false, instead of printing nothing, the indented expression under else will be
printed.

if condition:

expression

else:

expression

POWERED BY

Example of if-else
Continuing our previous example, what if you want to print 'z is odd' when the if condition is false? In this
case, you can simply add another condition, which is the else condition. If you run it with z equal to 5, the
condition is not true, so the expression for the else statement gets printed out.

z=5

if z % 2 == 0:

print("z is even")

else:

print("z is odd")

POWERED BY

z is odd

POWERED BY

if-elif-else condition

The most complex of these conditions is the if-elif-else condition. When you run into a situation where
you have several conditions, you can place as many elif conditions as necessary between the if condition
and the else condition.
if condition:

expression

elif condition:

expression

else:

expression

POWERED BY

Example one of if-elif-else condition


Below is an example of where you want different printouts for numbers that are divisible by 2 and 3.

Here, since z equals 3, the first condition is False, so it goes over to the next condition. The next condition
does hold True. Hence, the corresponding print statement is executed.

z=3

if z % 2 == 0:

print("z is divisible by 2")

elif z % 3 == 0:

print("z is divisible by 3")

else:

print("z is neither divisible by 2 nor by 3")

POWERED BY

z is divisible by 3

POWERED BY

Example two of if-elif-else condition


In the below example, you define two variables room and area. You then construct if-elif-else and if-
else conditions each for room and area, respectively.

In the first condition, you check if you are looking in the kitchen, elif you are looking in the
bedroom, else you are looking around elsewhere. Depending on the value of the room variable, the satisfied
condition is executed.
Similarly, for the area variable, you write an if and else condition and check whether the area is greater
than 15 or not.

# Define variables

room = "bed"

area = 14.0

# if-elif-else construct for room

if room == "kit":

print("Looking around in the kitchen.")

elif room == "bed":

print("Looking around in the bedroom.")

else:

print("Looking around elsewhere.")

# if-elif-else construct for area

if area > 15:

print("Big place!")

else:

print("Pretty small.")

POWERED BY

When we run the above code, it produces the following result:

Looking around in the bedroom. Pretty small.

 B) How to use while loop in python?


 Python While Loop क क कर C JAVA कर क
क ए कर , क कद ईक
कक True क Loop Execute
 क क क क क ए कर द ई
क क ,क र ए
 while
 while condition / expression :
#do whatever you want.

 or

 while (condition / expression) :
 #do whatever you want.

 क क आ क क ( while(condition) ) र र कई क

 while


 while
 while
 number = 1
table = 5
 while number <= 10 :
 print(number, ' * ', table, ' = ', number *table )
 number = number + 1

 while
 क आ Python Nested While Loop क कर क , While
Loop क दर एक और While Loop.
 while
 x = 1
while x <= 10 :
 y = 1
 print(y, end=' ')
 while y < x :
 y = y+1
 print(y, end=' ')

 print('')
 x = x+1

unit 3

 a) What do you mean by string ? define string operations and methods.?


String ek prakaar ka data type hai jo text ko represent karta hai. Yah ek sequence hai
jo characters ko store karta hai.

String ka Syntax:

string_name = "Hello, World!"

String Operations:
1. Concatenation: Do ya adhik strings ko concatenate kiya ja sakta hai.
2. Repetition: Ek string ko repeat kiya ja sakta hai.
3. Indexing: Ek string ke characters ko index ke through access kiya ja sakta hai.
4. Slicing: Ek string ke characters ko slicing ke through access kiya ja sakta hai.

String Methods:
1. lower(): Ek string ko lowercase mein convert karta hai.
2. upper(): Ek string ko uppercase mein convert karta hai.
3. title(): Ek string ko title case mein convert karta hai.
4. strip(): Ek string ke starting aur ending whitespace ko remove karta hai.
5. split(): Ek string ko ek separator ke basis par split karta hai.
6. join(): Ek list ke strings ko ek separator ke basis par join karta hai.
7. find(): Ek string mein ek substring ki index ki jaanch karta hai.
8. replace(): Ek string mein ek substring ko replace karta hai.
9. count(): Ek string mein ek substring ki frequency ki jaanch karta hai.

Udaaharan:

my_string = "Hello, World!"

# Concatenation
print(my_string + " How are you?") # Output: Hello, World! How are you?

# Repetition
print(my_string * 2) # Output: Hello, World!Hello, World!

# Indexing
print(my_string[0]) # Output: H

# Slicing
print(my_string[0:5]) # Output: Hello

# lower()
print(my_string.lower()) # Output: hello, world!

# upper()
print(my_string.upper()) # Output: HELLO, WORLD!

# title()
print(my_string.title()) # Output: Hello, World!

# strip()
print(my_string.strip()) # Output: Hello, World!

# split()
print(my_string.split(",")) # Output: ['Hello', ' World!']

# join()
print(",".join(["Hello", "World!"])) # Output: Hello,World!

# find()
print(my_string.find("World")) # Output: 7

# replace()
print(my_string.replace("World", "Universe")) # Output: Hello, Universe!

# count()
print(my_string.count("l")) # Output: 3
 B) Define dictionary? Explain all the functions of dictionary?
Dictionary ek prakaar ka data structure hai jo key-value pairs ko store karta hai.
Yah ek mutable data structure hai, jiska matlab hai ki ismein elements ko add,
remove aur modify kiya ja sakta hai.

Dictionary ka Syntax:

dict_name = {key1: value1, key2: value2, ...}

Dictionary ke Functions:
1. keys(): Dictionary ke sabhi keys ko return karta hai.
2. values(): Dictionary ke sabhi values ko return karta hai.
3. items(): Dictionary ke sabhi key-value pairs ko return karta hai.
4. get(): Dictionary se ek key ka value ko return karta hai.
5. pop(): Dictionary se ek key-value pair ko remove aur return karta hai.
6. popitem(): Dictionary se ek random key-value pair ko remove aur return karta
hai.
7. update(): Dictionary ko update karta hai.
8. clear(): Dictionary ko clear karta hai.
9. copy(): Dictionary ka ek copy banata hai.
10. fromkeys(): Ek dictionary banata hai jismein keys aur values hote hain.

Udaaharan:

my_dict = {"name": "John", "age": 30, "city": "New York"}

# keys()
print(my_dict.keys()) # Output: dict_keys(['name', 'age', 'city'])

# values()
print(my_dict.values()) # Output: dict_values(['John', 30, 'New York'])

# items()
print(my_dict.items()) # Output: dict_items([('name', 'John'), ('age', 30), ('city', 'New
York')])

# get()
print(my_dict.get("name")) # Output: John
# pop()
print(my_dict.pop("age")) # Output: 30

# popitem()
print(my_dict.popitem()) # Output: ('city', 'New York')

# update()
my_dict.update({"country": "USA"})
print(my_dict) # Output: {'name': 'John', 'city': 'New York', 'country': 'USA'}

# clear()
my_dict.clear()
print(my_dict) # Output: {}

# copy()
my_dict = {"name": "John", "age": 30, "city": "New York"}
my_dict_copy = my_dict.copy()
print(my_dict_copy) # Output: {'name': 'John', 'age': 30, 'city': 'New York'}

# fromkeys()
my_dict = dict.fromkeys(["name", "age", "city"], "Unknown")
print(my_dict) # Output: {'name': 'Unknown', 'age': 'Unknown', 'city': 'Unknown'}
or
 a) Define list operation and methods?
List operations aur methods woh hote hain jo list ke elements ko manipulate karne,
access karne aur modify karne mein madad karte hain.

List Operations:
1. Indexing: List ke elements ko index ke through access kiya ja sakta hai.
2. Slicing: List ke elements ko slicing ke through access kiya ja sakta hai.
3. Concatenation: Do ya adhik lists ko concatenate kiya ja sakta hai.
4. Repetition: List ko repeat kiya ja sakta hai.
5. Membership: List mein element ki membership ki jaanch ki ja sakti hai.
6. Length: List ki length ki jaanch ki ja sakti hai.

List Methods:
1. append(): List mein ek naya element add kiya ja sakta hai.
2. extend(): List mein ek ya adhik elements add kiye ja sakte hain.
3. insert(): List mein ek naya element insert kiya ja sakta hai.
4. remove(): List se ek element remove kiya ja sakta hai.
5. pop(): List se ek element remove aur return kiya ja sakta hai.
6. index(): List mein ek element ki index ki jaanch ki ja sakti hai.
7. count(): List mein ek element ki frequency ki jaanch ki ja sakti hai.
8. sort(): List ke elements ko sort kiya ja sakta hai.
9. reverse(): List ke elements ko reverse kiya ja sakta hai.
10. clear(): List ke sabhi elements remove kiye ja sakte hain.

Udaaharan:

my_list = [1, 2, 3, 4, 5]

# Indexing
print(my_list[0]) # Output: 1

# Append
my_list.append(6)
print(my_list) # Output: [1, 2, 3, 4, 5, 6]

# Sort
my_list.sort()
print(my_list) # Output: [1, 2, 3, 4, 5, 6]

# Reverse
my_list.reverse()
print(my_list) # Output: [6, 5, 4, 3, 2, 1]
 b) How many types of operations we can perform using tuple?
Tuple ke saath kai prakaar ke operations kiye ja sakte hain:

1. Indexing: Tuple ke elements ko index ke through access kiya ja sakta hai.


2. Slicing: Tuple ke elements ko slicing ke through access kiya ja sakta hai.
3. Concatenation: Do ya adhik tuples ko concatenate kiya ja sakta hai.
4. Repetition: Tuple ko repeat kiya ja sakta hai.
5. Membership: Tuple mein element ki membership ki jaanch ki ja sakti hai.
6. Length: Tuple ki length ki jaanch ki ja sakti hai.
7. Max aur Min: Tuple mein maximum aur minimum element ki jaanch ki ja sakti hai.
8. Any aur All: Tuple mein kisi bhi element ki jaanch ki ja sakti hai aur sabhi elements
ki jaanch ki ja sakti hai.
9. Count: Tuple mein kisi element ki frequency ki jaanch ki ja sakti hai.
10. Tuple Methods: Tuple ke liye kai methods available hain, jaise ki index(), count(),
etc

You might also like