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

Python - Preparation Notes

The document provides an introduction to Python programming, covering its history, variable declaration, data types, conditional statements, loops, and functions. It explains the syntax and usage of various programming constructs, including examples for better understanding. Additionally, it includes exercises with solutions to test knowledge of Python concepts.

Uploaded by

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

Python - Preparation Notes

The document provides an introduction to Python programming, covering its history, variable declaration, data types, conditional statements, loops, and functions. It explains the syntax and usage of various programming constructs, including examples for better understanding. Additionally, it includes exercises with solutions to test knowledge of Python concepts.

Uploaded by

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

Python Introduction :

o Python was developed by Guido van Rossum in late 80’s and released globally in 1991 by
Python Software Foundation.
o Python is a programming as well as a scripting language.
o This language has various purposes such as developing, scripting, generation, and software
testing.

Python Variable :
o Variable is a container that store value.
o Variable has the capacity to change its value during program execution
o Once an object is assigned to a variable, it can be referred to by that name.
o Python variable declaration does not require explicit mention of data-type as soon as assigning
value automatically concerned type is assigned to it by interpreter

Rules for Python variables


o A variable name must start with a letter or the underscore character.
o A variable name cannot start with a number.
o A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ ).
o Variable in Python names are case-sensitive (name, Name, and NAME are three
different variables).
o The reserved words(keywords) in Python cannot be used to name the variable in
Python.

Example:

# An integer assignment
age = 45
# A floating point
salary = 1456.8
# A string
name = "John"

print(age)
print(salary)
print(name)

DATA TYPES :
o A Data type indicates which type of value a variable has in a program.
o However a python variables can store data of any data type but it is necessary to identify the
different types of data they contain to avoid errors during execution of program.
o The most common data types used in python are str(string), int(integer) and float (floating-point)

o Numeric – int, float, complex


o Sequence Type – string, list, tuple
o Mapping Type – dict
o Boolean – bool
o Set Type – set, frozenset
o Binary Types – bytes, bytearray, memoryview
Conditional Statements :

o These statements are used to execute certain blocks of code based on specific conditions.
o These statements help to control the flow of a program, making it behave differently in different
situations based on given conditions.
o These statements otherwise called as decision making statements.
o These statement in python classified into
o Simple if
o if…else
o if….elif ladder

Importance of indentation:

o Indentation is significant in Python.


o It is used to define a block of code.
o Without proper indentation, the program will show an error.

Syntax of If Statement:
if condition:
# Statements to execute if
# condition is true

Example :

Age = int(input(“Enter your Age :”))

if Age>=18 :

Print(“Major, and Can Vote.”)


Syntax of Python If-Else:
if condition:
# code to execute if condition is true
else:
# code to execute if condition is false

Example :

Age = int(input(“Enter your Age :”))

if Age>=18 :
“print(“Major, and Can Vote.”)

else:

print(“Minor, and Can’t Vote.”)

Syntax of if…elif:

if condition1:
# code to execute if condition1 is true
elif condition2:
# code to execute if condition2 is true
else:
# code to execute if none of the above conditions are true
Example:

no = int(input(“Enter Any no :”))

if no<0:

print(“Negative Value”)

elif no >0 and no<10:

print(“Single Digit”)

elif no>9 and no<100:


print(“Double Digit”)

elif no>99 and no<999:

print(“Trible Digit”)

else

print(“Greater than Trible Digit”)


Looping Statements :
Type of Loops
There are mainly two types of loops.

1. For Loop

A for loop in Python is used to iterate over a sequence (list, tuple, set, dictionary, and string).

Flowchart:

Fig: Flowchart of a for loop

Syntax: for iterating_var in sequence:

statement(s)

Example:

for x in range (5):

print(x)

The preceding code executes as follows:

The variable x is a placeholder for every iteration.


The loop iterates as many times as the number of elements and prints the elements serially.

2. While Loop

The while loop is used to execute a set of statements as long as a condition is true.

Flowchart:

Fig: While loop flowchart

Syntax: while expression:

statements

Example:

x =0

while x<5:

print(x)

x+=1

The preceding code executes as follows:

We assign the value to variable x as 0.

Until the value of x is less than 5, the loop continues and prints the numbers.

Python Functions:
Python Functions is a block of statements that return the specific task.
The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of
writing the same code again and again for different inputs, we can do the function calls to reuse code
contained in it over and over again.

Benefits of Using Functions


• Increase Code Readability
• Increase Code Reusability

Python Function Declaration


The syntax to declare a function is:

Syntax of Python Function Declaration

Types of Functions in Python

• Built-in library function: These are Standard functions in Python that are available to use.
• User-defined function: We can create our own functions based on our requirements.

Creating a Function in Python

o We can define a function in Python, using the def keyword.


o We can add any type of functionalities and properties to it as we require.
o writing a function in Python is as follows.
o In this way we can create Python function definition by using def keyword.

# A simple Python function


def fun():
print("Welcome to SRM")

Calling a Function in Python

After creating a function in Python we can call it by using the name of the functions Python followed by
parenthesis containing parameters of that particular function.
Below is the example for calling def function Python.
fun()
o/p : Welcome to SRM

Getting into Python Coding :

#Arithmetic Operation based on Given Choice using if elif ladder:


a = int(input("Enter A value :"))
b = int(input("Enter B value :"))
ch = int(input("\n MENU \n 1.Add \n 2.Sub \n 3.Mul \n 4.Div \n Enter ur choice :"))
r=0
if ch==1:
r=a+b
elif ch==2:
r=a-b
elif ch==3:
r=a*b
elif ch==4:
r=a//b
print("Result :",r)

Arithmetic Operation based on Given Choice using match case:

a = int(input("Enter A value :"))


b = int(input("Enter B value :"))
ch = int(input("\n MENU \n 1.Add \n 2.Sub \n 3.Mul \n 4.Div \n Enter ur choice :"))
r=0
match ch:
case 1:
r=a+b
case 2:
r=a-b
case 3:
r=a*b
case 4:
r=a//b
print("Result :",r)

# Tribonacci Series 0 1 1 2 4 7 13 24........n


def findTribo(n): #5
i=1
a=0
b=1
c=1
d=2
while i<=n: # 1<=5 2<=5 3<=5 4<=5 5<=5 6<=5
a=b #a=0 a=1 a=1 a=2 a=3
b=c #b=1 b=1 b=2 b=3 b=5
c=d
print(" ",a) # 0 1 1 2 3
c=a+b+c #c=0+1=>1 c=1+1=>2 c=1+2=>3 c=2+3=>5 c=3+5=>8
i=i+1 #i=2=3=4=5=6
x=int(input("Enter Tibo-series limit :"))
findTibo(x)

# Program to sum even no's and odd no's upto n limit


i=2
oddSum=0
evenSum=0
n=int(input("Enter limit :"))
while i<n:
if i%2==0:
evenSum=evenSum+i
else:
oddSum=oddSum+i
i+=1 #i=i+1
print("Odd Sum :",oddSum)
print("Even Sum :",evenSum)
# To find sum and avg of n given int inputs
n=int(input("Enter no of elements u wish to add : "))
data=0
tot=0
avg=0.0
for i in range(n):
data=int(input("Enter value :"))
tot=tot+data
avg=tot/n
print("Total of entered elements :",tot)
print("Average is :",avg)

# Progrm to find factorial val


def findFact(n):
if n==0 or n==1:
return 1
else:
return n*findDfact(n-1)
n=int(input("Enter value :"))
print(“ Fact value is :",findFact(n))

# Progrm to find double factorial val


def findDfact(n):
if n==0 or n==1:
return 1
else:
return n*findDfact(n-2)
n=int(input("Enter value :"))
print("Double Fact value is :",findDfact(n))

#Program to generate Pell No Series using Recursion.

def pellNo(n):
if n==0:
return 0
elif n==1:
return 1
else:
return (2*pellNo(n-1)+pellNo(n-2))
x=int(input("Enter Pell-Series limit :"))
for i in range(x):
print(pellNo(i),end=" ")

#Program to Generate Lucas no Series:

def Lucas(n):
if n==0:
return 2
elif n==1:
return 1
else:
return (Lucas(n-1)+Lucas(n-2))
x = int(input("Enter upper limit :"))
for i in range(x):
print(Lucas(i),end=" ")

#Progam to illustrate Binary Search

def binSrch(arr, x):


left=0
right=len(arr)-1
while left<=right :
mid = left+(right-left)//2
if arr[mid]==x:
return mid
elif arr[mid]<x:
left=mid+1
else:
right=mid-1
return -1
arr = list(map(int, input("Enter a list of numbers separated by spaces: ").split()))
print("Given array is :",arr)
arr.sort()
print("Sorted array in Ascending :",arr)
x = int(input("Input No to be searched :"))
r=binSrch(arr,x)
if r==-1:
print("Searched value not found in this array")
else:
print("Value found at :",r)

# Linear Search

def LinrSrch(arr, target):


l=len(arr)
for i in range(l):
if arr[i]==target:
return i

return -1
arr = list(map(int,input("Enter space seperated arr :").split()))
x = int(input("Enter no to be Searched :"))
r = LinrSrch(arr,x)
if r==-1:
print("No not found in this array")
else:
print("No found at location :",r)
Exercise (a)

1. What does the abs() function do?

a) Rounds a number to the nearest integer


b) Returns the absolute value of a number
c) Converts a number to a string
d) Returns the square root of a number

2. Which of the following functions is used to get the length of a list, string, or dictionary?

a) len()
b) size()
c) length()
d) count()

3. What is the return type of the input() function?

a) int
b) float
c) str
d) None

4. Which function is used to convert a string to a floating-point number?

a) str()
b) float()
c) int()
d) eval()

5. What is the output of the following code?

min(4, 2, 8, 6)

a) 2
b) 4
c) 6
d) 8

6. Which built-in function is used to iterate over items in an iterable along with their index?

a) map()
b) zip()
c) enumerate()
d) filter()
7. What does the sorted() function return?

a) A sorted copy of the original iterable


b) A modified version of the original iterable
c) The largest element in the iterable
d) The smallest element in the iterable

8. How can you check if all elements in an iterable are true?

a) Using any()
b) Using all()
c) Using filter()
d) Using reduce()

9. What will be the output of the following code?

round(3.456, 2)

a) 3.45
b) 3.46
c) 3.50
d) 4

10. Which of the following functions converts an iterable into a set?

a) list()
b) dict()
c) set()
d) tuple()
Solutions:

1. What does the abs() function do?

Answer: b) Returns the absolute value of a number

2. Which of the following functions is used to get the length of a list, string, or dictionary?

Answer: a) len()

3. What is the return type of the input() function?

Answer: c) str

4. Which function is used to convert a string to a floating-point number?

Answer: b) float()

5. What is the output of the following code?

min(4, 2, 8, 6)

Answer: a) 2

6. Which built-in function is used to iterate over items in an iterable along with their index?

Answer: c) enumerate()

7. What does the sorted() function return?

Answer: a) A sorted copy of the original iterable

8. How can you check if all elements in an iterable are true?

Answer: b) Using all()


9. What will be the output of the following code?

round(3.456, 2)

Answer: b) 3.46

10. Which of the following functions converts an iterable into a set?

Answer: c) set()
Exercise (b)

1. Which keyword is used to define a function in Python?

a) define
b) def
c) func
d) function

2. What will happen if a return statement is not used in a Python function?

a) It will return None by default


b) It will cause an error
c) It will return False
d) It will return an empty string

3. Which of the following is the correct syntax for a function definition?

a) def func_name():
b) function func_name():
c) def func_name:
d) define func_name():

4. Where should the return statement be placed in a function?

a) At the beginning of the function


b) At the end of the function
c) Anywhere in the function
d) It is not mandatory to use a return statement

5. What is the output of the following code?

def add(a, b):


return a + b

print(add(2, 3))

a) 5
b) None
c) (2, 3)
d) Error
6. What is the scope of a variable defined inside a function?

a) Global
b) Local
c) Universal
d) Dynamic

7. Can a function in Python return multiple values?

a) Yes, using a list


b) Yes, using a tuple
c) Yes, using both a list or a tuple
d) No, only one value can be returned

8. What will be the output of the following code?

def func(a, b=2):


return a * b

print(func(3))

a) 3
b) 6
c) Error
d) None

9. Can you call a function before its definition in Python?

a) Yes, functions can be called before they are defined


b) No, functions must be defined before they are called
c) Only if it is a recursive function
d) Only if it has default arguments

10. What will be the output of the following code?

def func(x=[]):
x.append(1)
return x

print(func())
print(func())

a) [1] [1]
b) [1] [1, 1]
c) [] []
d) Error
Solutions:

1. Which keyword is used to define a function in Python?

Answer: b) def

2. What will happen if a return statement is not used in a Python function?

Answer: a) It will return None by default

3. Which of the following is the correct syntax for a function definition?

Answer: a) def func_name():

4. Where should the return statement be placed in a function?

Answer: c) Anywhere in the function

5. What is the output of the following code?

def add(a, b):


return a + b

print(add(2, 3))
Answer: a) 5

6. What is the scope of a variable defined inside a function?

Answer: b) Local

7. Can a function in Python return multiple values?

Answer: c) Yes, using both a list or a tuple


8. What will be the output of the following code?

def func(a, b=2):


return a * b

print(func(3))

Answer: b) 6

9. Can you call a function before its definition in Python?

Answer: b) No, functions must be defined before they are called

10. What will be the output of the following code?

def func(x=[]):
x.append(1)
return x

print(func())
print(func())

Answer: b) [1] [1, 1]


(The default argument x=[] is mutable, so it retains changes between function calls.)
Exercise ( c )

1. Which of the following is the correct syntax for an if statement in Python?

a) if (condition):
b) if condition:
c) if condition then:
d) if: condition

2. What is the output of the following code?

x = 10
if x > 5:
print("Greater")
else:
print("Smaller")

a) Greater
b) Smaller
c) None
d) Error

3. How do you write an if-else statement in Python?

a) if condition: else:
b) if (condition) {} else {}
c)

if condition:
# do something
else:
# do something else

d) None of the above

4. What will be the output of the following code?

x=5
if x > 5:
print("A")
elif x == 5:
print("B")
else:
print("C")

a) A
b) B
c) C
d) Error
5. What is the purpose of the elif keyword in Python?

a) It is the same as else


b) It allows testing multiple conditions in a single if statement
c) It is used to end an if-else block
d) It allows looping within the if statement

6. What is the output of the following code?

x = 10
y = 20
if x < y and x > 5:
print("Yes")
else:
print("No")

a) Yes
b) No
c) Error
d) None

7. What is the output of the following code?

x = 15
if x % 2 == 0:
print("Even")
else:
print("Odd")

a) Even
b) Odd
c) Error
d) None

8. Which of the following correctly checks for both conditions being true?

a) if condition1 & condition2:


b) if condition1 and condition2:
c) if condition1 || condition2:
d) if condition1 or condition2:

9. What will be the output of the following code?

x=5
if x > 10:
print("A")
else:
print("B")
if x < 3:
print("C")

a) A
b) B
c) B C
d) Error

10. What will be the output of the following code?

x=7
if x > 10:
print("Greater")
elif x == 7:
print("Equal")
else:
print("Smaller")

a) Greater
b) Equal
c) Smaller
d) None

Solutions :

1. Which of the following is the correct syntax for an if statement in Python?

Answer: b) if condition:

2. What is the output of the following code?

x = 10
if x > 5:
print("Greater")
else:
print("Smaller")

Answer: a) Greater
3. How do you write an if-else statement in Python?

Answer: c)

if condition:
# do something
else:
# do something else

4. What will be the output of the following code?

x=5
if x > 5:
print("A")
elif x == 5:
print("B")
else:
print("C")

Answer: b) B

5. What is the purpose of the elif keyword in Python?

Answer: b) It allows testing multiple conditions in a single if statement

6. What is the output of the following code?

x = 10
y = 20
if x < y and x > 5:
print("Yes")
else:
print("No")

Answer: a) Yes

7. What is the output of the following code?

x = 15
if x % 2 == 0:
print("Even")
else:
print("Odd")

Answer: b) Odd
8. Which of the following correctly checks for both conditions being true?

Answer: b) if condition1 and condition2:

9. What will be the output of the following code?

x=5
if x > 10:
print("A")
else:
print("B")
if x < 3:
print("C")

Answer: b) B

10. What will be the output of the following code?

x=7
if x > 10:
print("Greater")
elif x == 7:
print("Equal")
else:
print("Smaller")

Answer: b) Equal
Exercise (d)

1. What is the correct syntax for a for loop in Python?

a) for i to 10:
b) for i in range(10):
c) foreach i in range(10):
d) loop i in range(10):

2. What is the output of the following code?

for i in range(3):
print(i)

a) 0 1 2
b) 1 2 3
c) 0 1 2 3
d) Error

3. Which of the following keywords is used to stop the execution of a loop?

a) stop
b) exit
c) break
d) terminate

4. What is the purpose of the continue statement in a loop?

a) To stop the loop entirely


b) To skip the rest of the current iteration and move to the next iteration
c) To pause the loop temporarily
d) None of the above

5. What will be the output of the following code?

i=1
while i < 5:
print(i, end=" ")
i += 1

a) 1 2 3 4
b) 1 2 3 4 5
c) Infinite loop
d) Error

6. What is the range of values generated by range(2, 8, 2)?

a) [2, 4, 6, 8]
b) [2, 3, 4, 5, 6, 7]
c) [2, 4, 6]
d) [2, 6, 8]

7. How do you iterate over the keys of a dictionary d?

a) for key in d:
b) for key in d.keys():
c) Both a and b
d) None of the above

8. What is the output of the following code?

for x in "Python":
if x == "h":
break
print(x, end="")

a) Pyt
b) Pyth
c) P
d) Pyt

9. What will be the output of the following code?

for i in range(5):
if i == 3:
continue
print(i, end=" ")

a) 0 1 2 3 4
b) 0 1 2 4
c) 1 2 4
d) 0 1 4

10. What will be the output of the following code?

i=1
while i < 3:
print(i, end=" ")
i += 1
else:
print("Done")

a) 1 2 Done
b) 1 2
c) Done
d) Error
Solutions:

1. What is the correct syntax for a for loop in Python?

Answer: b) for i in range(10):

2. What is the output of the following code?

for i in range(3):
print(i)

Answer: a) 0 1 2

3. Which of the following keywords is used to stop the execution of a loop?

Answer: c) break

4. What is the purpose of the continue statement in a loop?

Answer: b) To skip the rest of the current iteration and move to the next iteration

5. What will be the output of the following code?

i=1
while i < 5:
print(i, end=" ")
i += 1

Answer: a) 1 2 3 4

6. What is the range of values generated by range(2, 8, 2)?

Answer: c) [2, 4, 6]

7. How do you iterate over the keys of a dictionary d?

Answer: c) Both a and b


8. What is the output of the following code?

for x in "Python":
if x == "h":
break
print(x, end="")

Answer: c) P

9. What will be the output of the following code?

for i in range(5):
if i == 3:
continue
print(i, end=" ")

Answer: b) 0 1 2 4

10. What will be the output of the following code?

i=1
while i < 3:
print(i, end=" ")
i += 1
else:
print("Done")

Answer: a) 1 2 Done
Exercise (e)

1. What is the type of the following Python expression: 3.14?

a) int
b) float
c) complex
d) str

2. What will be the output of the following code?

x = 10
y=3
print(x / y)

a) 3.0
b) 3
c) 3.33
d) 3.33...

3. Which of the following is used for floor division in Python?

a) /
b) //
c) %
d) **

4. What is the result of the expression 2 ** 3 in Python?

a) 6
b) 8
c) 9
d) 23

5. Which of the following operators is used for modulus (remainder) in Python?

a) //
b) **
c) %
d) &

6. What will be the output of the following code?

x = "5"
y=3
print(x + str(y))
a) 53
b) 8
c) 5
d) Error

7. What is the data type of True in Python?

a) int
b) bool
c) str
d) float

8. Which of the following data types is immutable in Python?

a) list
b) set
c) tuple
d) dictionary

9. What will be the output of the following code?

x=2
x += 3
print(x)

a) 2
b) 3
c) 5
d) 23

10. Which of the following is the correct way to create a set in Python?

a) x = {1, 2, 3}
b) x = [1, 2, 3]
c) x = (1, 2, 3)
d) x = set(1, 2, 3)
Solutions :

1. What is the type of the following Python expression: 3.14?

Answer: b) float

2. What will be the output of the following code?

x = 10
y=3
print(x / y)

Answer: a) 3.0

3. Which of the following is used for floor division in Python?

Answer: b) //

4. What is the result of the expression 2 ** 3 in Python?

Answer: b) 8

5. Which of the following operators is used for modulus (remainder) in Python?

Answer: c) %

6. What will be the output of the following code?

x = "5"
y=3
print(x + str(y))

Answer: a) 53

7. What is the data type of True in Python?

Answer: b) bool
8. Which of the following data types is immutable in Python?

Answer: c) tuple

9. What will be the output of the following code?

x=2
x += 3
print(x)

Answer: c) 5

10. Which of the following is the correct way to create a set in Python?

Answer: a) x = {1, 2, 3}

You might also like