Module 1 Question Bank
Module 1 Question Bank
1)
What are the different flow control statements supported in Python? Explain all the flow
controlstatements with example code and syntax.
Soluon:
Python provides several flow control statements that allow you to control the execution flow of
your program.These flow control statements allow you to make decisions, iterate over sequences,
and control the executionflow of your Python programs.The main flow control statements in
Python are:
1. if...elif...else statement
: This statement is used for conditional execution. It allows you to perform differentactions based
on different conditions.
Example:
age = 25
else:
In this example, the `if...elif...else` statement checks the value of the `age` variable and prints
acorresponding message based on the condition.
2. for loop:
The `for` loop is used to iterate over a sequence (such as a string, list, or tuple) or other
iterableobjects.
Example:
This code iterates over each element in the `fruits` list and prints them one by one.
3. while loop:
The `while` loop is used to repeatedly execute a block of code as long as a certain condition
istrue.
Example:
count = 0
print(count)
count += 1
This loop prints the value of `count` and increments it by 1 until the condition `count < 5`
becomes false.
4. break statement
: The `break` statement is used to exit a loop prematurely. When encountered, it terminatesthe
current loop and transfers control to the next statement after the loop.
Example:
numbers = [1, 2, 3, 4, 5]
if number == 3:
break
print(number)
In this example, the loop stops executing when the value `3` is encountered, and the control flow
moves tothe next statement after the loop.
5. continue statement
: The `continue` statement is used to skip the rest of the current iteration of a loop andmove to
the next iteration.
Example:
numbers = [1, 2, 3, 4, 5]
if number == 3:
continue
print(number)
In this example, when the value `3` is encountered, the `continue` statement skips the rest of the
currentiteration. The loop continues with the next iteration, printing all the numbers except `3`.
2) Define exception handling. How exceptions are handled in python? Write a program to
solve divideby zero exception.
Soluon:
Exception handling is a mechanism in programming that allows you to handle and respond to
errors orexceptional events that occur during the execution of a program. Exception handling
provides a way togracefully handle error situations and prevent the program from crashing.
In Python, exceptions are handled using the `try` and `except` statements. The `try` block
contains the codethat may potentially raise an exception, while the `except` block specifies the
code to be executed if anexception occurs. The `except` block defines the type of exception it
can handle. If the raised exceptionmatches the specified type, the code inside the `except` block
is executed.
try:
# ...
except ExceptionType:
# ...
Now, let's write a program to solve the divide-by-zero exception using exception handling:
try:
numerator = 10
denominator = 0
print(result)
except ZeroDivisionError:
3) Explain Local and Global Scopes in Python programs. What are local and global
variables? How canyou force a variable in a function to refer to the global variable?
Soluon:
In Python, local and global variables are used to store values within a program. The main
difference betweenthem is their scope, which determines where the variable can be accessed and
modified.
Local Variables:
Local variables are defined within a function or a block of code. They have a local scope, which
means theyare only accessible within the specific function or block where they are defined.
Local variables cannot beaccessed outside of their scope.
def my_function():
x = 10 # Local variable
print(x)
my_function()
# Output: 10
print(x)
# Error: NameError: name 'x' is not defined
In this example, `x` is a local variable defined within the `my_function()` function. It can only be
accessedwithin the function's scope. Attempting to access `x` outside of the function results in a
`NameError` since itis not defined in the global scope.
Global Variables:
Global variables, as the name suggests, are defined outside of any function or block of code.
They have aglobal scope, meaning they can be accessed and modified from anywhere in the
program, including insidefunctions.
x = 10 # Global variable
def my_function():
print(x)
my_function()
# Output: 10
print(x)
# Output: 10
In this example, `x` is a global variable defined outside the function. It can be accessed and
printed both insideand outside the function because of its global scope.
We can force a variable in a function to refer to the global variable using the `global` keyword.
Example:
x = 10 # Global variable
def my_function():
global x
x = 20
print(x)
my_function()
# Output: 20
print(x)
# Output: 20
In this example, the `global` keyword is used to indicate that the variable `x` inside
`my_function()` refers tothe global variable `x`. Therefore, when we modify `x` inside the
function, it affects the global variable itself.
4) Write a program that generates a random number between 1 and
100. The program should prompt theuser to guess the number and
provide feedback if the guess is too high or too low. The game
shouldcontinue until the user correctly guesses the number.
Soluon:
import random
guess = 0
# Connue the game unl the user guesses the correct number
print("Too high!")
print("Too low!")
else:
This program generates a random number between 1 and 100 as the secret
number. It prompts the user to guess thenumber and provides feedback if
the guess is too high or too low. The game connues unl the user correctly
guessesthe number.
Sample Output:
Too high!
Too low!
Too high!
Too low!
Too high!
# Program to print the mulplicaon table of a posi ve integer using a while
loop
while count <= 10:# Iterate while the count is less than or equal to 10
Descripon:This program prompts the user to enter a posi ve integer and
then uses a while loop to print the mulplicaon table ofthat number from 1
to 10. It starts by taking user input and storing it in the `number`
variable.Sample Output:
```
14
21
28
35
42
49
56
63
70
def calculate_factorial(n):
factorial = 1
factorial = factorial * i
return factorial
# Main program
result = calculate_factorial(number)
Descripon:
OUTPUT:
x=5
if x > 10:
count = 0
print(count)
count += 1
The if statement and while loop are both control ow structures in Python
that allow you to control the execuon ofcode based on certain condi ons.
The if statement is suitable for making decisions based on a condion, while
the whileloop is useful for performing iterave tasks as long as a condi on
remains true. Following is the comparison for ifstatement and while loop:
1) Purpose:
if statement:
The if statement is used for condional execuon. It allows you to specify
a condion, and if thecondion evaluates to true, the code block indented
under the if statement is executed.
while loop:
The while loop is used for repeve execuon. It allows you to repeatedly
execute a block of code as longas a speci ed condi on remains true.
Condion:
if statement:
The if statement checks a condion only once. If the condion is true, the
indented code block isexecuted. If the condi on is false, the code block is
skipped.
while loop:
The while loop checks a condion before each itera on. As long as the
condion remains true, the codeblock is executed. If the condi on becomes
false, the loop is exited, and the program connues with the next statement.
Execuon:
if statement:
The code block under the if statement is executed only once, if the
condion is true.
while loop:
The code block under the while loop is executed repeatedly unl the
condion becomes false.
Control Flow:
if statement:
The if statement can be followed by oponal else and elif clauses to provide
addional branching basedon dierent condions.
while loop:
The while loop does not have built-in branching capabilies like else and
elif. However, you can use controlow statements like break and con nue
to control the execuon within the loop.
current_year = date.today().year
return True
else:
return False
# Main program
# Display the result based on the return value of the func on
if is_senior_cizen:
else:
Descripon:
This program prompts the user to enter a person's name and year of birth. It
uses the current year obtained from the`date` module to calculate the
person's age. The `check_senior_cizen` funcon takes the name and year
of birth asinput and determines whether the person is a senior ci zen based
on their age (60 or above).
Output:
Sample 1:
Enter person's name: SanyoEnter year of birth: 1978Sanyo is not a senior citizen.
Sample 2:
9) What are functions? Explain Python function with parameters and return statements.
Soluon:
A function is a block of reusable code that performs a specific task.In Python, functions are
defined using the `def` keyword, followed by the function name, parentheses for parameters (if
any), a colon, and an indented block of code that constitutes the function body.
def greet(name):
return greeting
result = greet("Alice")
print(result)
Output:
Hello, Alice!
In the above example, we define a function called `greet` that takes a single parameter `name`.
To use thefunction, we call it with an argument, in this case, "Alice". The function executes its
code with the providedargument and returns the result. The returned value is then assigned to the
`result` variable. Finally, we printthe value of `result`, which outputs "Hello, Alice!" to the
console.
def update_global_variable():
global eggs
eggs = 'spam'
update_global_variable()
OUTPUT:
def funcon_bacon():
# main program
funcon_bacon()
OUTPUT:
def quiz_example_1():
global variable_1
variable_1 = 10
variable_2 = 20
# main program
variable_1 = 5
variable_2 = 15
quiz_example_1()
print(variable_1)
print(variable_2)
OUTPUT:
b) 10 15
d)
def quiz_example_2():
variable_1 = 5
# main programvariable_1 = 10
quiz_example_2()
OUTPUT:
e)
def quiz_example_3():
global variable_1
variable_1 = 5
def another_funcon():
variable_2 = 10
# main program
variable_1 = 10
variable_2 = 20
quiz_example_3()
another_funcon()
OUTPUT:
f)
def update_list():
global my_list
my_list.append(4)
# main program
my_list = [1, 2, 3]
update_list()
OUTPUT:
def calculate_average(numbers):
total = sum(numbers)# Calculate the sum of the numbers in the list.
average = total / count# Calculate the average by dividing the total by the
count.
# Main program
Descripon:
Soluon:
String concatenation refers to the process of combining two or more strings into a single string.
This can bedone using the `+` operator, which joins the strings together.
first_name = "John"
last_name = "Doe"
print(full_name)
Output:
John Doe
In this example, the variables `first_name` and `last_name` store the strings "John" and "Doe"
respectively.By using the `+` operator, we can concatenate these strings with a space in between,
resulting in the string"John Doe". The `print()` function is then used to display the
concatenated string.
String replication, on the other hand, involves creating a new string by repeating an existing
string a certainnumber of times. This can be achieved using the `*` operator.
message = "Hello!"
repeated_message = message * 3
print(repeated_message)
Output:
Hello!Hello!Hello!
In this example, the variable `message` contains the string "Hello!". By using the `*` operator
and specifyingthe number 3, we replicate the string three times. The resulting string is "Hello!
Hello!Hello!", which is then printed using the `print()` function.
13) What are Comparison and Boolean operators? List all the Comparison and Boolean
operators inPython and explain the use of these operators with suitable examples.
Soluon:
Comparison operators are used to compare two values or expressions and determine the
relationship betweenthem. These operators evaluate to either True or False, indicating whether
the comparison is true or false.
2. `!=` (Not equal to): Checks if two values are not equal.
3. `>` (Greater than): Checks if the left operand is greater than the right operand.
4. `<` (Less than): Checks if the left operand is less than the right operand.
5. `>=` (Greater than or equal to): Checks if the left operand is greater than or equal to the right
operand.
6. `<=` (Less than or equal to): Checks if the left operand is less than or equal to the right
operand.
x=5
y = 10
In this example, we compare the values of `x` and `y` using different comparison operators. Each
comparisonevaluates to either True or False, depending on the relationship between the values.
Boolean operators, also known as logical operators, are used to combine or manipulate Boolean
values (Trueor False). These operators allow you to perform logical operations on the results of
comparison operations.
x=5
y = 10
z=3
These operators are fundamental in controlling the flow of programs, making decisions, and
performinglogical operations in Python.
14) Explain importing of modules into an application in Python with syntax and a
suitableprogramming example.
Soluon:
import module_name
Example:
Let us
write a Python program that generates a random number between 1 and 100. The program
should prompt the user to guess the number and provide feedback if the guess is too high or too
low. The gameshould continue until the user correctly guesses the number.
import random
secret_number = random.randint(1,100)
guess = 0
print("Too high!")
else:
OUTPUT:
def funcon_name(parameters):
# Funcon body
# Code to be executed
# ...
return value
hon Programming
The keyword def is used to indicate the start of a func on de ni on.
•parameters (oponal) are inputs that the funcon can accept. Mulple
parameters are separated by commas.If there are no parameters, empty
parentheses are used.
•The colon (:) marks the end of the funcon header and the start of the
funcon body.
•The funcon body is indented, typically with four spaces, and contains the
code that will be executed when thefunc on is called.
•Within the funcon body, you write the logic and opera ons that the
funcon performs.
For example, let's dene a simple funcon called greet that takes a name
as a parameter and prints a greengmessage:
def greet(name):
greet("Alice")
16) What are try and except statements used for in exception
handling in Python?
Soluon:
In excepon handling, the try and except statements are used to handle
errors in a program. The code that is likely togenerate an error is enclosed
within the try clause. If an error occurs during the execuon of the code
inside the tryclause, the program moves to the start of the statements in the
except clause to handle the error. This helps indetecng errors, handling
them, and allowing the program to connue running without termina ng
abruptly.
Example:
return num1/num2
try:
print(spam(12, 2)) # Normal division, no error
except ZeroDivisionError:
OUTPUT:
6.0
4.0
5.0
# Check if the number is greater than zero and print the appropriate
message
This program takes a number as input from the user and determines whether
it is posive, negave, or zero. It uses an`if-elif-else` condi onal statement
to check the value of the input number. If the number is greater than zero, it
prints amessage stang that the number is posive. If the number is less
than zero, it prints a message stang that the numberis nega ve. If neither
of these condions is true, it means the number is zero, and it prints
a message indicang thatthe number is zero.
Sample Output 1:
Enter a number: 5
Sample Output 2:
18) Name any three different data types in Python and explain each.
Soluon:
In Python, there are several built-in data types. Here are three commonly
used data types:
1) Integer (int):
Integers are used for numeric computaons and represent whole numbers.
The integer data type represents whole numbers without any decimal points.
2) String (str):
Strings are used to store and manipulate textual data, such as words
or sentences.
The string data type represents a sequence of characters enclosed in single
quotes ('') or double quotes ("").
Strings are used to store textual data and can contain leers, numbers,
symbols, and whitespace.
3) Boolean (bool):
Booleans are used for logical operaons and help determine the truth value
of an expression.
The boolean data type represents a logical value that can be either True or
False.
Booleans are oen used in condional statements and logical opera ons to
control the ow of a program.
•Proper indentaon makes the code more organized and easier to maintain,
debug, and collaborate on.
Block Delimiters:
Program Execuon:
A variable is used to store and manipulate data. It holds a value that can be
accessed, modied, or reassignedthroughout the program.
Hence we can say that variable stores data, while a func on performs
acons or computaons.
Python comes with a rich set of built-in funcons that are readily available
for use.Some commonly used built-in funcons in Python include:
1.
print(): Used to display output on the console.
2.
3.
4.
5.
6.
7.
8.
9.
10.
# Define a variable named 'message' and assign a string value to itmessage = "Hello,
world!"# Print the value of the variableprint(message)
In the above example, a variable named 'message' is de ned and assigned
the value "Hello, world!". The equal sign (=)is used to assign the value to the
variable. Then, the value of the 'message' variable is printed using the
'print()'funcon, which will output "Hello, world!" to the console.
Variable names must follow certain naming rules such as star ng with a
leer or underscore and consisng of leers,digits, or underscores.
Variables can hold various types of data, including numbers, strings, lists,
diconaries, and more.
For example,
On the other hand, a number in Python represents numerical values and can
be of dierent types, such as integers(whole numbers), oa ng-point
numbers (decimal numbers), or complex numbers.
my_integer = 42
my_oat = 3.14
my_complex = 2 + 3j
The main dierence between strings and numbers in Python is their
representaon and the operaons that can beperformed on them.
Strings are treated as text and support various string-specic operaons
like concatenaon, slicing,and string methods. Numbers, on the other hand,
are used for mathemacal operaons and support arithme copera ons
such as addion, subtracon, mulplicaon, and division.
my_string = "42"
my_number = 42
x=5
y=3
result = x + y * 2
print(result)
Expressions can also involve other operators, func on calls, and more
complex combinaons of values and variables.They are the building blocks
of any program and are used to perform calculaons, manipulate data, and
make decisionsbased on the evaluated results.
1) Keywords:
Keywords are reserved words in Python that have predened meanings
and cannot be used as variablenames. Examples of keywords include if, for,
while, def, class, import, etc. Keywords dene the structure and ow ofthe
program.
2) Variables:
Variables are used to store and manipulate data. They are named containers
that hold values of dierenttypes, such as integers, strings, lists, etc.
Variables are assigned values using the assignment operator (=) and can
beused in expressions and statements.
3) Operators:
Operators are symbols or special characters that perform specic
operaons on one or more values.Python supports various types of
operators, such as arithmec operators (+, -, *, /), comparison operators (>,
<, ==, !=),assignment operators (=, +=, -=), logical operators (and, or,
not), etc. Operators help in performing calculaons,comparisons, and logical
operaons.
4) Funcons:
Funcons are reusable blocks of code that perform specic tasks. They
take input arguments (if any),perform operaons, and may return a value.
Python provides built-in funcons like print(), len(), input(), etc.Addi onally,
you can dene your own funcons to modularize and organize your code.
SearchSearch
ENCHANGE LANGUAGE
Upload
Read free for 30 days
User Settings
Download now
Jump to Page
You are on page 1of 22
Search inside document
Introduction to
Python Program
ming
BPLCK205B
1
Mrs. Annie
Sujith, CSE, JIT
Module 1
Question
Bank
1)
What are the
different flow
control
statements
supported in
Python? Explain
all the flow
controlstatements
with example
code and syntax.
Soluon:
Python provides
several flow
control statements
that allow you to
control the
execution flow of
your
program.These
flow control
statements allow
you to make
decisions, iterate
over sequences,
and control the
executionflow of
your Python
programs.The
main flow control
statements in
Python are:
1. if...elif...else
statement
: This statement is
used for
conditional
execution. It
allows you to
perform
differentactions
based on different
conditions.
Example:
age = 25
print("You are an
adult.")
else:
print("You are a
senior citizen.")
In this example,
the `if...elif...else`
statement checks
the value of the
`age` variable and
prints
acorresponding
message based on
the condition.
2. for loop:
The `for` loop is
used to iterate
over a sequence
(such as a string,
list, or tuple) or
other
iterableobjects.
Example:
fruits = ["apple",
"banana",
"cherry"]
print(fruit)
This code iterates
over each
element in the
`fruits` list and
prints them one by
one.
3. while loop:
The `while` loop
is used to
repeatedly execute
a block of code as
long as a certain
condition istrue.
Example:
count = 0
print(count)
ADDownload to read ad-free.
00:00
03:41
Introduction to
Python Program
ming
BPLCK205B
Mrs. Annie
Sujith, CSE, JIT
count += 1
4. break
statement
: The `break`
statement is used
to exit a loop
prematurely.
When
encountered, it
terminatesthe
current loop and
transfers control
to the next
statement after the
loop.
Example:
numbers = [1, 2,
3, 4, 5]
for number in
numbers:
if number == 3:
break
print(number)
In this example,
the loop stops
executing when
the value `3` is
encountered, and
the control flow
moves tothe next
statement after the
loop.
5. continue
statement
: The `continue`
statement is used
to skip the rest of
the current
iteration of a loop
andmove to the
next iteration.
Example:
numbers = [1, 2,
3, 4, 5]
for number in
numbers:
if number == 3:
continue
print(number)
In this example,
when the value `3`
is encountered,
the `continue`
statement skips
the rest of the
currentiteration.
The loop
continues with the
next iteration,
printing all the
numbers except
`3`.
2) Define
exception
handling. How
exceptions are
handled in
python? Write a
program to solve
divideby zero
exception.
Soluon:
Exception
handling is a
mechanism in
programming that
allows you to
handle and
respond to errors
orexceptional
events that occur
during the
execution of a
program.
Exception
handling provides
a way togracefully
handle error
situations and
prevent the
program from
crashing.
In Python,
exceptions are
handled using the
`try` and `except`
statements. The
`try` block
contains the
codethat may
potentially raise
an exception,
while the `except`
block specifies the
code to be
executed if
anexception
occurs. The
`except` block
defines the type of
exception it can
handle. If the
raised
exceptionmatches
the specified type,
the code inside the
`except` block is
executed.
# ...
except
ExceptionType:
ADDownload to read ad-free.
Introduction to
Python Program
ming
BPLCK205B
3
Mrs. Annie
Sujith, CSE, JIT
# Code to handle
the exception
# ...
Now, let's write a
program to solve
the divide-by-zero
exception using
exception
handling:
try:
numerator = 10
denominator = 0
result = numerator
/ denominator
print(result)
except
ZeroDivisionError
:
print("Error:
Division by zero
is not allowed.")
In this example,
we attempt to
divide
`numerator` by 0.
Since dividing by
zero is an invalid
operation
andraises a
`ZeroDivisionErro
r`, we handle this
exception in the
`except` block.
Instead of
crashing the
program,the
exception is
caught, and the
error message
"Error: Division
by zero is not
allowed"
is printed.
3) Explain Local
and Global
Scopes in Python
programs. What
are local and
global variables?
How canyou
force a variable
in a function to
refer to the
global variable?
Soluon:
In Python, local
and global
variables are used
to store
values within a
program. The
main difference
betweenthem is
their scope, which
determines where
the variable can
be accessed and
modified.
Local
Variables:
Local variables
are defined within
a function or
a block of code.
They have a local
scope, which
means theyare
only accessible
within the specific
function or block
where they are
defined. Local
variables cannot
beaccessed
outside of their
scope.
Example of a
local variable:
def
my_function():
x = 10 #
Local variable
print(x)
my_function()
# Output: 10
print(x)
# Error:
NameError:
name 'x' is not
defined
In this example,
`x` is a local
variable defined
within the
`my_function()`
function. It can
only be
accessedwithin
the function's
scope. Attempting
to access `x`
outside of the
function results in
a `NameError`
since itis not
defined in the
global scope.
Global
Variables:
Global variables,
as the name
suggests, are
defined outside of
any function or
block of code.
They have aglobal
scope, meaning
they can be
accessed and
modified from
anywhere in the
program,
including
insidefunctions.
Example of a
global variable:
x = 10 #
Global variable
ADDownload to read ad-free.
Introduction to
Python Program
ming
BPLCK205B
Mrs. Annie
Sujith, CSE, JIT
def
my_function():
print(x)
my_function()
# Output: 10
print(x)
# Output: 10
In this example,
`x` is a global
variable defined
outside the
function. It can be
accessed and
printed both
insideand outside
the function
because of its
global scope.
Forcing a
Variable in a
Function to
Refer to the
Global
Variable:
We can force a
variable in a
function to refer
to the global
variable using the
`global` keyword.
Example:
x = 10 #
Global variable
def
my_function():
global x
x = 20
print(x)
my_function()
# Output: 20
print(x)
# Output: 20
In this example,
the `global`
keyword is used
to indicate that the
variable `x` inside
`my_function()`
refers tothe global
variable `x`.
Therefore, when
we modify `x`
inside the
function, it affects
the global variable
itself.
4) Write a
program that
generates a
random
number
between 1
and 100. The
program
should
prompt
theuser to
guess the
number and
provide
feedback if
the guess is
too high or
too low. The
game
shouldcontin
ue until the
user correctly
guesses the
number.
Soluon:
# Program to
guess a random
number
between 1 and
100
import random
# Generate a
random secret
number
secret_number
=
random.randint(
1, 100)
# Inialize the
user's guess
guess = 0
# Connue the
game unl the
user guesses
the correct
number
while guess !
= secret_numbe
r:
BPLCK205B
Mrs. Annie
Sujith, CSE, JIT
# Prompt the
user to guess a
number
guess =
int(input("Guess
a number
between 1 and
100: "))
# Check if the
guess is too
high, too low, or
correct
if guess
> secret_numbe
r:
print("Too
high!")
elif guess
< secret_numbe
r:
print("Too low!")
else:
print("Congratul
aons! You
guessed the
correct
number.")
Descripon:
This program
generates a
random number
between 1
and 100 as the
secret number.
It prompts the
user to
guess thenumb
er and provides
feedback if the
guess is too
high or too low.
The game
connues unl
the user
correctly
guessesthe
number.
Sample Output:
Guess a number
between 1 and
100: 50
Too high!
Guess a number
between 1 and
100: 25
Too low!
Guess a number
between 1 and
100: 35
Too high!
Guess a number
between 1 and
100: 30
Too low!
Guess a number
between 1 and
100: 33
Too high!
Guess a number
between 1 and
100: 32
Congratulaons
! You guessed
the correct
number.
5) Write a
program that
prompts
the user to
enter
a positive
integer and
prints its
multiplication
table from1
to 10 using a
while loop.
Soluon:
# Program to
print the
mulplicaon
table of a
posive integer
using a while
loop
Introduction to
Python Program
ming
BPLCK205B
6
Mrs. Annie
Sujith, CSE, JIT
number =
int(input("Enter
a posive
integer: "))#
Prompt the user
to enter a
posive integer
count = 1#
Inialize the
count variable
to 1
while count <=
10:# Iterate
while the count
is less than or
equal to 10
result = number
* count#
Calculate the
result by
mulplying the
number and
the count
print(result)#
Print the result
count = count +
1# Increment
the count by 1
Descripon:This
program
prompts the
user to enter a
posive integer
and then uses a
while loop
to print the
mulplicaon
table ofthat
number from 1
to 10. It starts
by taking user
input and
storing it in the
`number`
variable.Sample
Output:
```
Enter a posive
integer: 7
7
14
21
28
35
42
49
56
63
70
6) Write a
Python
function
called
"calculate_fac
torial" that
takes a
positive
integer as
input and
returns
thefactorial
of that
number.
Solution:
# Funcon to
calculate the
factorial of a
posive integer
def
calculate_factori
al(n):
factorial = 1
Introduction to
Python Program
ming
BPLCK205B
7
Mrs. Annie
Sujith, CSE, JIT
for i in range(1,
n + 1):
factorial =
factorial * i
return factorial
# Main program
number =
int(input("Enter
a non-negave
number:"))#
prompt the user
to enter a non-
negave
number.
result
= calculate_fact
orial(number)
print("The
factorial
of", number,
"is:", result)
Descripon:
This program
denes a
funcon called
"calculate_facto
rial" that
calculates the
factorial of a
posive integer
using a forloop.
The user is
prompted to
enter a non-
negave
number, and
the factorial of
that number is
calculated and
printedas the
output.
OUTPUT:
Enter a non-
negave
number:10The
factorial of 10
is: 3628800
7) Give one
example each
for if-else
statements
and while
loops.
Compare and
contrast
Python's
if
statement
and
while
loop.
Soluon:
Example of an
if-else
statement:
x=5
if x > 10:
print("x is
greater than
10")
else:
print("x is not
greater than
10")
Example of
while loop:
count = 0
print(count)
count += 1
BPLCK205B
Mrs. Annie
Sujith, CSE, JIT
The if statement
and while loop
are both control
ow structures
in Python that
allow you to
control the
execuon
ofcode based on
certain
condions.
The if statement
is suitable for
making
decisions based
on a condion,
while the
whileloop is
useful for
performing
iterave tasks
as long as a
condion
remains true.
Following is the
comparison for
ifstatement and
while loop:
1) Purpose:
if statement:
The if
statement is
used for
condional
execuon. It
allows you to
specify
a condion, and
if thecondion
evaluates to
true, the
code block
indented under
the if statement
is executed.
while loop:
The while loop
is used for
repeve
execuon. It
allows you to
repeatedly
execute a block
of code as
longas a
specied
condion
remains true.
Condion:
if statement:
The if
statement
checks a
condion only
once. If the
condion is
true, the
indented code
block
isexecuted. If
the condion
is false, the
code block is
skipped.
while loop:
The while loop
checks a
condion
before each
iteraon. As
long as the
condion
remains true,
the codeblock is
executed. If the
condion
becomes false,
the loop
is exited, and
the program
connues with
the
nextstatement.
Execuon:
if statement:
The code block
under the if
statement is
executed only
once, if the
condion is
true.
while loop:
The code block
under the while
loop is executed
repeatedly unl
the condion
becomes false.
Control Flow:
if statement:
The if
statement can
be followed by
oponal else
and elif clauses
to provide
addional
branching
basedon
dierent
condions.
while loop:
The while loop
does not have
built-in
branching
capabilies like
else and elif.
However, you
can use
controlow
statements like
break and
connue to
control the
execuon
within the loop.
8) Develop a
program to
read
the name and
year of birth
of a person.
Display
whether the
person is
asenior
citizen or not.
Soluon:
# Program to
determine if a
person is
a senior cizen
based on their
name and year
of birth
from dateme
import date
def
check_senior_ci
zen(name,
year_of_birth):
# Get the
current year
current_year =
date.today().yea
r
# Calculate the
person's age
age =
current_year -
year_of_birth
# Check if the
age is 60 or
above
BPLCK205B
9
Mrs. Annie
Sujith, CSE, JIT
return True
else:
return False
# Main program
name =
input("Enter
person's name:
")
year_of_birth =
int(input("Enter
year of birth: "))
# Call the
funcon
to check if the
person is
a senior cizen
is_senior_cizen
=
check_senior_ci
zen(name,
year_of_birth)
# Display the
result based on
the return value
of the funcon
if
is_senior_cizen
:
print(name, "is
a senior
cizen.")
else:
print(name, "is
not a senior
cizen.")
Descripon:
This program
prompts the
user to enter a
person's name
and year of
birth. It uses the
current year
obtained from
the`date`
module to
calculate the
person's age.
The
`check_senior_c
izen` funcon
takes the name
and year of
birth asinput
and determines
whether the
person is a
senior cizen
based on their
age (60
or above).
Output:
Sample 1:
Enter person's
name: SanyoEnter
year of birth:
1978Sanyo is not
a senior citizen.
Sample 2:
Enter person's
name: SarojEnter
year of birth:
1960Saroj is a
senior citizen.
9) What are
functions?
Explain Python
function with
parameters and
return
statements.
Soluon:
A function is a
block of reusable
code that
performs a
specific task.In
Python, functions
are defined using
the `def` keyword,
followed by the
function name,
parentheses
for parameters (if
any), a colon, and
an indented block
of code that
constitutes the
function body.
Here's an example
of a Python
function with
parameters and
a return statement:
def greet(name):
ADDownload to read ad-free.
Introduction to
Python Program
ming
BPLCK205B
10
Mrs. Annie
Sujith, CSE, JIT
greeting = "Hello,
" + name + "!"
return greeting
# Calling the
function
result =
greet("Alice")
print(result)
Output:
Hello, Alice!
In the above
example, we
define a function
called `greet` that
takes a single
parameter `name`.
To use
thefunction, we
call it with an
argument, in this
case, "Alice". The
function executes
its code with the
providedargument
and returns the
result. The
returned value is
then assigned to
the `result`
variable. Finally,
we printthe value
of `result`, which
outputs "Hello,
Alice!" to the
console.
Functions with
parameters
allow us to create
more flexible and
reusable code. By
accepting
differentargument
s, the same
function can be
used to perform
similar operations
on various inputs.
The `return`
statement
is used to specify
the value that
should be sent
back from the
function to
the caller.
Itterminates the
function execution
and provides the
output. The
returned value can
be stored in a
variable, usedin
an expression, or
passed as an
argument to
another function.
def update_glob
al_variable():
global eggs
eggs = 'spam'
# main
programeggs =
'bacon'
print("Before
funcon call -
eggs:", eggs)
update_global_v
ariable()
print("Aer
funcon call -
eggs:", eggs)
OUTPUT:
Before
funcon call -
eggs:
baconAer
funcon call -
eggs: spam
b)
BPLCK205B
11
Mrs. Annie
Sujith, CSE, JIT
def
funcon_bacon(
):
eggs =
'bacon'print("Ins
ide the funcon
- eggs:", eggs)
# main program
eggs =
'spam'print("Bef
ore funcon call
- eggs:", eggs)
funcon_bacon(
)
print("Aer
funcon call -
eggs:", eggs)
OUTPUT:
Before
funcon call -
eggs:
spamInside
the funcon -
eggs:
baconAer
funcon call -
eggs: spam
c)
def
quiz_example_
1():
global
variable_1
variable_1 =
10
variable_2 =
20
# main
program
variable_1 = 5
variable_2 =
15
quiz_example_
1()
print(variable_
1)
print(variable_
2)
OUTPUT:
b) 10 15
d)
BPLCK205B
12
Mrs. Annie
Sujith, CSE, JIT
def
quiz_example_
2():
variable_1 = 5
print("Inside
funcon:",
variable_1)
# main
programvariab
le_1 = 10
quiz_example_
2()
print("Outside
funcon:",
variable_1)
OUTPUT:
Inside
funcon:
5Outside
funcon: 10
e)
def
quiz_example_
3():
global
variable_1
variable_1 = 5
def another_fu
ncon():
variable_2 =
10
print("Inside
another
funcon:",
variable_2)
# main
program
variable_1 =
10
variable_2 =
20
quiz_example_
3()
another_func
on()
print("Outside
funcons:",
variable_1)
print("Outside
funcons:",
variable_2)
OUTPUT:
ADDownload to read ad-free.
Introduction to
Python Program
ming
BPLCK205B
13
Mrs. Annie
Sujith, CSE, JIT
Inside another
funcon:
10Outside
funcons:
5Outside
funcons: 20
f)
def
update_list():
global my_list
my_list.append
(4)
# main
program
my_list = [1, 2,
3]
print("Before
funcon call -
my_list:",
my_list)
update_list()
print("Aer
funcon call -
my_list:",
my_list)
OUTPUT:
Before funcon
call - my_list: [1,
2, 3]
Aer funcon
call - my_list: [1,
2, 3, 4]
11) Write a
Python
function
called
"calculate_av
erage" that
takes a list of
numbers as
an input and
returnsthe
average
(mean) of
those
numbers.
Solution:
# This is
a funcon to
calculate the
average of a list
of numbers.
def calculate_av
erage(numbers)
:
total =
sum(numbers)#
Calculate the
sum of the
numbers in
the list.
count
= len(numbers)
# Determine
the count of
numbers in the
list.
average =
total / count#
Calculate the
average by
dividing
the total by the
count.
return average#
Return
the calculated
average.
# Main program
numbers_list =
[2, 4, 6, 8, 10]#
Example list
of numbers
result = calculat
e_average(num
bers_list)#
Call the
calculate_avera
ge funcon
print("The
average is:",
result)# Print
the calculated
average.
Descripon:
The program
denes a
funcon called
"calculate_aver
age" that
calculates the
average of a list
of numbers. It
uses thesum()
funcon to
calculate the
total sum of the
numbers and
the len()
funcon to
determine the
count
of numbers.The
n, it divides the
total by
the count to get
the average.
OUTPUT:
Introduction to
Python Program
ming
BPLCK205B
14
Mrs. Annie
Sujith, CSE, JIT
The average is:
6.0
12) Explain
string
concatenation
and string
replication with
one suitable
example for each.
Soluon:
String
concatenation
refers to the
process of
combining two or
more strings into a
single string. This
can bedone using
the `+` operator,
which joins the
strings together.
Example of string
concatenation:
first_name =
"John"
last_name =
"Doe"
full_name =
first_name + " " +
last_name
print(full_name)
Output:
John Doe
In this example,
the variables
`first_name` and
`last_name` store
the strings "John"
and "Doe"
respectively.By
using the `+`
operator, we can
concatenate
these strings with
a space in
between, resulting
in the string"John
Doe". The
`print()` function
is then used to
display the
concatenated strin
g.
String replication,
on the other hand,
involves creating
a new string by
repeating an
existing string a
certainnumber of
times. This can be
achieved using the
`*` operator.
Example of
string
replication:
message =
"Hello!"
repeated_message
= message * 3
print(repeated_m
essage)
Output:
Hello!Hello!
Hello!
In this example,
the variable
`message`
contains the string
"Hello!". By using
the `*` operator
and specifyingthe
number 3, we
replicate the string
three times. The
resulting string is
"Hello!Hello!
Hello!", which
is then printed
using the `print()`
function.
Comparison
operators are used
to compare two
values or
expressions and
determine the
relationship
betweenthem.
These operators
evaluate to either
True or False,
indicating whether
the comparison is
true or false.
The following are
the comparison
operators in
Python:
3. `>` (Greater
than): Checks if
the left operand is
greater than the
right operand.
ADDownload to read ad-free.
Introduction to
Python Program
ming
BPLCK205B
15
Mrs. Annie
Sujith, CSE, JIT
5. `>=` (Greater
than or equal to):
Checks if the left
operand is greater
than or equal to
the right operand.
6. `<=` (Less than
or equal to):
Checks if the left
operand is less
than or equal to
the right operand.
Example of
comparison
operators:
x=5
y = 10
print(x == y) #
Output: False
print(x != y) #
Output: True
print(x > y) #
Output: False
print(x < y) #
Output: True
print(x >= y) #
Output: False
print(x <= y) #
Output: True
In this example,
we compare the
values of `x` and
`y` using different
comparison
operators. Each
comparisonevalua
tes to either True
or False,
depending on the
relationship
between the
values.
Boolean
operators, also
known as logical
operators, are
used to combine
or manipulate
Boolean values
(Trueor False).
These operators
allow you to
perform logical
operations on the
results of
comparison
operations.
2. `or`: Returns
True if either of
the operands is
True.
3. `not`: Returns
the opposite
Boolean value of
the operand.
Example of
Boolean
operators:
x=5
y = 10
z=3
print(not x < y) #
Output: False
These operators
are fundamental
in controlling the
flow of programs,
making decisions,
and
performinglogical
operations in
Python.
14) Explain
importing of
modules into an
application in
Python with
syntax and a
suitableprogram
ming example.
Soluon:
Importing
modules in
Python
programming
allows us to use
the functionalities
present in external
codelibraries.
Here's an
explanation of
how to import
modules into your
application with
syntax and a
suitable program
ming example:
Syntax for
importing a
module:
import
module_name
ADDownload to read ad-free.
Introduction to
Python Program
ming
BPLCK205B
16
Mrs. Annie
Sujith, CSE, JIT
Example:
Let us
write a Python
program that
generates a
random number
between 1 and
100. The program
should prompt the
user to guess the
number and
provide feedback
if the guess is too
high or too low.
The gameshould
continue until the
user correctly
guesses the
number.
import random
secret_number =
random.randint(1,
100)
guess = 0
while guess !=
secret_number:
guess =
int(input("Guess a
number between 1
and 100: "))
if guess >
secret_number:
print("Too
high!")
print("Too low!")
else:
print("Congratula
tions! You
guessed the
correct number.")
OUTPUT:
15) What is a
function in
Python?
Write the
syntax for
defining a
function.
Solution:
A funcon
in Python is a
reusable block
of code that
performs a
specic task.
It allows you to
break down
your codeinto
smaller,
modular pieces,
making it easier
to read,
understand, and
maintain.
def funcon_na
me(parameters)
:
# Funcon
body
# Code to be
executed
# ...
#
Oponal return
statement
return value
BPLCK205B
17
Mrs. Annie
Sujith, CSE, JIT
•
The keyword
def is used to
indicate the
start of a
funcon
denion.
•
funcon_name
is the name
given to the
funcon. It
should follow
the naming
convenons for
variables.
•
parameters
(oponal)
are inputs that
the
funcon can
accept. Mulple
parameters are
separated by
commas.If there
are
no parameters,
empty
parentheses are
used.
•
The colon (:)
marks the
end of the
funcon header
and the start of
the funcon
body.
•
The funcon
body is
indented,
typically with
four spaces,
and contains
the code that
will be executed
when
thefuncon is
called.
•
Within the
funcon body,
you write the
logic and
operaons that
the funcon
performs.
•
Oponally, a
return
statement can
be used to
specify the
value or values
that the
funcon will
output. If
thereis no
return
statement, the
funcon will
return None by
default.
For example,
let's dene a
simple funcon
called greet
that takes a
name as
a parameter
and prints
a greengmess
age:
def
greet(name):
print("Hello, " +
name + "! How
are you?")
# Calling the
funcon
greet("Alice")
16) What are
try and
except
statements
used for in
exception
handling in
Python?
Soluon:
In excepon
handling, the
try and except
statements are
used to handle
errors in a
program. The
code that is
likely
togenerate an
error is
enclosed within
the try clause. If
an error occurs
during the
execuon of
the code inside
the tryclause,
the program
moves to
the start of the
statements in
the except
clause to handle
the error. This
helps indetecn
g errors,
handling them,
and
allowing the
program to
connue
running without
terminang
abruptly.
In the
given example,
the funcon
`spam()`
is dened to
perform
division.
However, a
ZeroDivisionErr
or can occur
ifthe second
argument is 0.
To handle
this potenal
error, the try-
except block is
used. Inside
the try
block, the
`spam()`funco
n is called
mulple mes
with dierent
arguments. If a
ZeroDivisionErr
or occurs during
the execuon
of`spam()`, the
program jumps
to the except
block, which
prints 'Error:
Invalid
argument.'
Instead of
terminang
theprogram
abruptly, it
connues to
execute the
subsequent
statements.
Example:
def spam(num1,
num2):
return
num1/num2
try:
print(spam(12,
2)) # Normal di
vision, no error
print(spam(48,
12)) # Normal d
ivision, no error
print(spam(12,
0)) # ZeroDivisi
onError occurs
print(spam(5, 1)
) # Normal divis
ion, no error
BPLCK205B
18
Mrs. Annie
Sujith, CSE, JIT
except
ZeroDivisionErr
or:
print('Error:
Invalid
argument.')
In the given
example, the
third call to
`spam(12, 0)`
results in a
ZeroDivisionErr
or, which is
caught by
the except
block.Instead of
terminang the
program, it
executes the
except block
and prints
'Error: Invalid
argument.' This
demonstratesth
e handling
of errors using
try and except
statements in
Python's excep
on handling
mechanism.
OUTPUT:
6.0
4.0
Error: Invalid
argument.
5.0
17) Write a
program that
takes a
number as
input and
determines
whether it is
positive,
negative, or
zero.
Soluon:
# Program to
determine
whether
a number is
posive,
negave, or
zero
number =
oat(input("Ent
er a number:
"))# Input a
number from
the user
# Check if
the number is
greater than
zero and print
the appropriate
message
if number >
0:print("The
number is
posive.")elif
number < 0:#
Check if the
number is less
than zero and
print the
appropriate
message
print("The
number
is negave.")els
e:# If neither
condion is
true, then print
the message
that number is
zero
print("The
number is
zero.")Descrip
on:
This program
takes a number
as input from
the user and
determines
whether it is
posive,
negave, or
zero. It uses
an`if-elif-else`
condional
statement to
check the value
of the input
number. If the
number is
greater than
zero, it prints
amessage
stang that the
number is
posive. If the
number is less
than zero, it
prints a
message
stang that the
numberis
negave. If
neither of these
condions is
true, it means
the number is
zero, and it
prints
a message
indicang
thatthe number
is zero.
Sample Output
1:
Enter a number:
5
The number is
posive.
Sample Output
2:
BPLCK205B
19
Mrs. Annie
Sujith, CSE, JIT
Enter a number:
-3.5
The number
is negave.
In Python, there
are several
built-in data
types. Here are
three commonly
used data
types:
1) Integer
(int):
Integers are
used for
numeric comput
aons and
represent whole
numbers.
The integer
data type
represents
whole numbers
without
any decimal
points.
Examples: -5, 0,
10, 100
Integers can be
posive or
negave and
have no limit on
their size.
2) String (str):
Strings are
used to store
and manipulate
textual data,
such as words
or sentences.
Examples:
"Hello",
'Python',
"12345"
Strings are
used to store
textual data
and can contain
leers,
numbers,
symbols, and
whitespace.
3) Boolean
(bool):
Booleans are
used for logical
operaons and
help determine
the truth value
of an
expression.
The boolean
data
type represents
a logical value
that can
be either True
or False.
Examples: True,
False
Booleans are
oen used in
condional
statements and
logical
operaons to
control the
ow of
a program.
Python is a
dynamically
typed language,
hence we don't
need to
explicitly
declare the data
type of a
variable.
Pythondetermin
es the data type
based on the
value assigned
to the variable.
19) Critique
the
importance
of
indentation
in Python and
how it affects
program
execution.
Soluon:
In
Python, indenta
on is used to
indicate the
grouping and
hierarchy of
statements
within control
structures such
asloops,
condionals,
and funcon
denions.
Indentaon in
Python
is important
because:
Readability
and
Code Organiz
aon:
•
Indentaon
improves the
readability of
the code by
visually
represenng
the logical
structure of the
program.
•
Proper
indentaon
makes the code
more organized
and easier to
maintain,
debug, and
collaborate on.
Block
Delimiters:
•
In many
programming
languages,
curly braces or
keywords are
used to delimit
code blocks.
However,
inPython,
indentaon is
used as a
block delimiter.
•
Blocks of code
with the same
indentaon
level are
considered part
of the same
block, while a
decrease
inindentaon
marks the end
of a block.
Program
Execuon:
•
Indentaon
directly aects
the execuon
of the program.
Incorrect
indentaon can
lead to syntax
errors oralter
the logic of the
code.
Introduction to
Python Program
ming
BPLCK205B
20
Mrs. Annie
Sujith, CSE, JIT
Code Flow
and Control
Structures:
•
Indentaon is
essenal for
control
structures such
as if-else
statements, for
loops,
while loops, and
funcondeni
ons.
•
Proper
indentaon is
necessary to
accurately
dene the
body of
these control
structures.
20) How does
a function
differ from a
variable in
Python?
Name some
built-in
functions in
Python.
Solution:
Dierence
between a
funcon and
a variable:
•
A variable is
used to store
and manipulate
data. It holds
a value that can
be accessed,
modied, or
reassignedthrou
ghout the
program.
•
A funcon, on
the other hand,
is a block of
code that
performs a
specic task or
set of
operaons. It
can takeinputs
(parameters),
perform
acons, and
oponally
return a result.
Hence we can
say that
variable stores
data, while a
funcon
performs
acons or
computaons.
Built-in
funcons in
Python:
Python comes
with a rich set
of built-in
funcons that
are readily
available for
use.Some
commonly used
built-in
funcons in
Python include:
1.
print(): Used to
display output
on the console.
2.
input(): Takes
user input from
the console.
3.
len(): Returns
the length of an
object (e.g.,
string, list).
4.
type(): Returns
the type of an
object.
5.
range():
Generates a
sequence of
numbers.
6.
sum():
Calculates the
sum of
elements in an
iterable.
7.
max(): Returns
the maximum
value from a
sequence.
8.
min(): Returns
the minimum
value from a
sequence.
9.
abs(): Returns
the absolute
value of a
number.
10.
round(): Rounds
a oang-
point number to
a specied
decimal place.
21) Define a
variable in
Python and
give an
example.
Soluon:
In Python, a
variable is a
named
container that
can hold a
value. It allows
you to store and
manipulate data
within
yourprogram.
To dene a
variable
in Python, you
simply choose
a name for the
variable and
assign a value
to it using
theassignment
operator (=).
Here's an
example of
dening a
variable in
Python:
# Define a
variable named
'message' and
assign a string
value to
itmessage =
"Hello, world!"#
Print the value of
the
variableprint(mes
sage)
In the above
example, a
variable named
'message' is
dened and
assigned
the value
"Hello, world!".
The equal sign
(=)is used to
assign the value
to the variable.
Then, the value
of the
'message'
variable
is printed using
the
'print()'funcon,
which will
output "Hello,
world!" to the
console.
Introduction to
Python Program
ming
BPLCK205B
21
Mrs. Annie
Sujith, CSE, JIT
Variable names
must follow
certain naming
rules such as
starng with a
leer
or underscore
and consisng
of leers,digits,
or underscores.
Variables can
hold various
types of data,
including
numbers,
strings, lists,
diconaries,
and more.
22) Explain
the
difference
between a
string and a
number in
Python.
Soluon:
In Python, a
string is a
sequence of
characters
enclosed in
either single
quotes ('') or
double quotes
("").
Strings areused
to represent
textual data
and are treated
as a series
of individual
characters.
They can
contain leers,
numbers,symbo
ls, and
whitespace.
Here's an
example of a
string in Python:
For example,
my_string =
"Hello, World!"
In the above
example,
my_string is
a variable that
holds a string
value "Hello,
World!".
On the other
hand, a number
in Python
represents
numerical
values and can
be of dierent
types, such as
integers(whole
numbers),
oang-point
numbers
(decimal
numbers),
or complex
numbers.
Here are a few
examples of
numbers in
Python:
my_integer = 42
my_oat =
3.14
my_complex =
2 + 3j
The main
dierence
between strings
and numbers in
Python is their
representaon
and the
operaons that
can
beperformed on
them.
Strings are
treated as text
and
support various
string-specic
operaons like
concatenaon,
slicing,and
string methods.
Numbers, on
the other hand,
are used for
mathemacal
operaons and
support
arithmecopera
ons such as
addion,
subtracon,
mulplicaon,
and division.
Here's an
example that
showcases the
dierence
between a
string and a
number
in Python:
my_string =
"42"
my_number =
42
print(my_string
+ my_string) #
Concatenates
two strings:
"4242"
print(my_numb
er
+ my_number)
# Adds two
numbers: 84
In the above
example, when
the + operator
is used
with strings,
it concatenates
the two
strings together
, whereaswhen
it is used
with numbers, it
performs
addion.
23) Explain
the concept
of an
"expression"
in Python
with
example.
Soluon:
In Python,
an expression is
a combinaon
of values,
variables,
operators, and
funcon calls
that evaluates
to a singlevalue.
Expressions can
be as simple as
a single value or
as complex as a
combinaon of
mulple
operaons.
Here's an
example of an
expression in
Python:
ADDownload to read ad-free.
Introduction to
Python Program
ming
BPLCK205B
22
Mrs. Annie
Sujith, CSE, JIT
x=5
y=3
result = x + y *
2
print(result)
The expression
result = x + y *
2 assigns the
value of the
expression x +
y * 2 (which is
11) to the
variable result.
The expression
print(result)
calls the print()
funcon with
the value of the
variable result
as an argument.
It outputsthe
value 11 to the
console.
Expressions can
also involve
other operators,
funcon calls,
and more
complex
combinaons of
values and
variables.They
are the
building blocks
of any program
and are used
to perform
calculaons,
manipulate
data, and make
decisionsbased
on
the evaluated
results.
24) Identify
and explain
the
components
of a Python
statement.
Soluon:
In Python, a
statement is a
line of code that
performs a
specic acon
or operaon. A
statement
typically
consists ofone
or
more componen
ts as follows:
1) Keywords:
Keywords are
reserved words
in Python
that have
predened
meanings and
cannot be
used as
variablenames.
Examples of
keywords
include if, for,
while, def,
class, import,
etc. Keywords
dene
the structure
and ow ofthe
program.
2) Variables:
Variables are
used to store
and manipulate
data. They are
named
containers that
hold values of
dierenttypes,
such
as integers,
strings,
lists, etc.
Variables are
assigned values
using the
assignment
operator
(=) and can
beused
in expressions
and statements.
3) Operators:
Operators are
symbols or
special characte
rs that perform
specic
operaons on
one or more
values.Python
supports
various types of
operators, such
as arithmec
operators (+, -,
*, /),
comparison
operators (>, <,
==, !
=),assignment
operators (=,
+=, -=),
logical operator
s (and, or, not),
etc. Operators
help in
performing
calculaons,co
mparisons, and
logical
operaons.
4) Funcons:
Funcons are
reusable blocks
of code that
perform
specic tasks.
They take input
arguments (if
any),perform
operaons, and
may return a
value. Python
provides built-in
funcons like
print(), len(),
input(),
etc.Addionally,
you can dene
your own
funcons to
modularize and
organize your
code.
5) Control Flow
Structures:
Control
ow structures
determine the
order in
which statemen
ts are executed.
Commoncontrol
ow structures
include if-else
statements,
loops (for and
while), and
funcon
calls. They allow
you
to makedecision
s, repeat code
blocks, and
control the
ow of your
program based
on certain
condions.
These
components
come together
to form
complete
Python stateme
nts that instruct
the interpreter
on what acons
toperform.
Reward Your Curiosity
Everything you want to read.
Anytime. Anywhere. Any device.
Read free for 30 days
No Commitment. Cancel anytime.
Share this document
Share or Embed Document
Sharing Options
Share on Facebook, opens a new window
Share on Twitter, opens a new window
Share on LinkedIn, opens a new window
Share with Email, opens mail client
Copy link
Document28 pages
Document64 pages
Document6 pages
Model QP Programs
thor kumar
89% (9)
D. Null Operator
Document49 pages
D. Null Operator
PlayIt All
100% (2)
Communication Round - Hexaware
Document4 pages
Communication Round - Hexaware
arjun allu
100% (1)
Cts Automata Fix Previous Error Debugging: Cognizant Telegram Group
Document56 pages
Document3 pages
Document2 pages
Document120 pages
Study Material XI Computer Science
Priyanshu
0% (1)
DSDV Lab Manual PDF
Document15 pages
Document28 pages
Document22 pages
Document11 pages
SQP1 12 CS Yk
Md Ashfaq
No ratings yet
Python For Data Science PDF
Document30 pages
Python For Data Science PDF
pdrpatnaik
100% (5)
Write A Program To Implement Job Sequencing Algorithm
Document2 pages
Document2 pages
Document22 pages
Document5 pages
Maventic Questions
Manjusha Gowda
No ratings yet
P1
Document7 pages
P1
Chandra Sekar
67% (6)
CPP Hand Written Notes
Document55 pages
Document5 pages
Document20 pages
Lab Manual Python - Laboratory - 2022-23
Manjunath NR
No ratings yet
Aptitude QUESTIONS
Document21 pages
Aptitude QUESTIONS
Maheedhar Reddy
No ratings yet
MCQ's On Files and Streams: #Include #Include
Document9 pages
Document55 pages
Document4 pages
Experiment No.1:: Write A LEX Program To Scan Reserved Word & Identifiers
of C Language
RADHARAPU DIVYA PEC
No ratings yet
CN Lab Manual 18CSL57 2020
Document60 pages
Document8 pages
Document45 pages
Document7 pages
Python Question Bank-BCCA SEM6
Sara Rai
100% (1)
FDS MCQ Question Bank Unit 1 To 4
Document15 pages
Document17 pages
Document92 pages
Document75 pages
Computer Science Project 12th
harshit
100% (1)
Isc Computer Practical Project File
Document31 pages
Document94 pages
Document31 pages
Document7 pages
Java MCQS
szar
No ratings yet
AMCAT Computer Programming1 - Part2
Document35 pages
Document4 pages
Document5 pages
Document5 pages
Document23 pages
Unit Ii, PPS PDF
VARUN KUMAR V S
No ratings yet
LAB # 12 To Understand The Control Structure Using FOR LOOP: Objective
Document5 pages
Document7 pages
Lab 5 Loops
Waqas Qureshi
No ratings yet
Unit 1 - Introduction To Python-Part-2
Document36 pages
Document
100%
Document
71%
Document
75%
83%
Application Development Using Python: Model Question Paper-1 With Effect From 2018-19
(CBCS Scheme)
Document
Application Development Using Python: Model Question Paper-1 With Effect From
2018-19 (CBCS Scheme)
Added by subhash
100%
Model QP Programs
Document
Model QP Programs
Added by thor kumar
89%
D. Null Operator
Document
D. Null Operator
Added by PlayIt All
100%
100%
Document
50%
Document
100%
100% found this document useful
Document
0 ratings
Document
0 ratings
Document
0 ratings
100%
Document
100%
Document
100%
Document
Python Programming Lab Manual: 1. Write A Program To Demonstrate Different
Number Datatypes in Python
Added by Naresh Babu
100%
Document
0 ratings
SQP1 12 CS Yk
Document
SQP1 12 CS Yk
Added by Md Ashfaq
0 ratings
Document
100%
100% found this document useful
Document
64%
Document
0 ratings
Document
0 ratings
0 ratings
Maventic Questions
Document
Maventic Questions
Added by Manjusha Gowda
0 ratings
P1
Document
P1
Added by Chandra Sekar
67%
Document
CPP Hand Written Notes
Added by santhosh guggilla
0 ratings
Document
70%
Document
50%
Document
0 ratings
0% found this document useful
Aptitude QUESTIONS
Document
Aptitude QUESTIONS
Added by Maheedhar Reddy
0 ratings
Document
0 ratings
Document
91%
71%
Experiment No.1:: Write A LEX Program To Scan Reserved Word & Identifiers of C Language
Document
Experiment No.1:: Write A LEX Program To Scan Reserved Word & Identifiers of C
Language
Added by RADHARAPU DIVYA PEC
0 ratings
Document
50%
Document
Programming For Problem Solving Unit 1 Multiple Choice Questions MCQ
Added by MAHESHWAR M R (RA2111004010136)
0 ratings
Document
60%
Document
100%
Document
100%
100% found this document useful
Document
100%
Document
100%
Document
100%
100%
Document
100%
Document
67%
Document
Accenture Coding Handout
Added by Aishwarya km 4GW19CS003
100%
Document
100%
Document
67%
Java MCQS
Document
Java MCQS
Added by szar
0 ratings
0% found this document useful
Document
100%
Document
100%
Document
0 ratings
Implement On A Data Set of Characters The Three CRC polynomials-CRC 12, CRC 16, CRC
CCIP
Document
Implement On A Data Set of Characters The Three CRC polynomials-CRC 12, CRC 16,
CRC CCIP
Added by gdayanand4u
100%
Document
100%
Document
0 ratings
Document
Unit Ii, PPS PDF
Added by VARUN KUMAR V S
0 ratings
Document
0 ratings
Lab 5 Loops
Document
Lab 5 Loops
Added by Waqas Qureshi
0 ratings
Document
0 ratings
0% found this document useful
Related titles
Click to expand Related Titles
Footer menu
Back to top
About
About Scribd
Everand: Ebooks & Audiobooks
SlideShare
Press
Join our team!
Contact us
Invite friends
Scribd for enterprise
Support
Help / FAQ
Accessibility
Purchase help
AdChoices
Legal
Terms
Privacy
Copyright
Cookie Preferences
Do not sell or share my personal information
Social
InstagramInstagram
TwitterTwitter
FacebookFacebook
PinterestPinterest
Documents
Language:
English