Getting Started with Python  Class 11 Computer Science  Chapter 5  Notes, NCERT Solutions & Extra Questions
Renews every month. Cancel anytime
Your personal doubtsolving assistant
Chatterbot AI gives you 100% accurate answers to your questions in an instant.
Notes  Getting Started with Python  Class 11 NCERT  Computer Science
Getting Started with Python: Comprehensive Class 11 Notes
Python is a versatile and powerful highlevel programming language, renowned for its ease of use and readability. Whether you're new to programming or looking to expand your knowledge, this guide will help you get started with Python, tailored for Class 11 students.
Introduction to Python
What is Python?
Python is a highlevel, interpreted programming language known for its readability and versatility. It supports multiple programming paradigms, including procedural, objectoriented, and functional programming.
Why Learn Python in Class 11?
Learning Python in Class 11 provides a strong foundation for future studies in computer science and various realworld applications. Python’s simplicity makes it an ideal first language to learn.
Installing Python
System Requirements
Python runs on various operating systems including Windows, macOS, and Linux. Ensure your system meets the basic requirements and has an internet connection for downloading Python.
Steps to Install Python on Windows, macOS, and Linux
 Windows: Download the Python installer from the official website, run the installer, and follow the instructions.
 macOS: Download the installer, open the package, and follow the instructions to complete the installation.

Linux: Use your distribution's package manager (e.g.,
sudo aptget install python3
for Debianbased systems).
Verifying Your Installation
Open a terminal or command prompt and type python version
or python3 version
to check the installed version.
Python Basics
Python Interpreter and Interactive Mode
What is the Python Interpreter?
The Python interpreter reads and executes Python code directly, offering an interactive environment for testing small code segments.
How to Use Python in Interactive Mode
To start the interpreter, type python
or python3
in your terminal. You'll see the Python prompt >>>
, where you can type and execute Python commands interactively.
Script Mode in Python
Writing Your First Python Script
Create a new file with a .py
extension and write your Python code. Below is an example of a simple Python script.
### script1.py
print("Hello, Class 11!")
Running Python Scripts
You can run the script by typing python script1.py
or python3 script1.py
in your terminal.
Key Features of Python
 HighLevel Language: Easy to read and write, abstracting complex details.
 Interpreted Language: Executes code linebyline, making debugging easier.
 Easy Syntax: Clean and simple to understand.
 Case Sensitivity: Differentiates between uppercase and lowercase characters.
 Portability: Runs on various operating systems without modification.
 Rich Library Support: Extensive libraries for various applications.
 Indentation: Uses indentation to define code blocks, enhancing readability.
Basic Concepts in Python
Python Keywords
Keywords are reserved words in Python with special meanings, like if
, else
, while
, and break
. They must be used exactly as they are.
Identifiers
Identifiers are names given to variables, functions, and other entities. They must start with a letter (az, AZ) or an underscore (_) and be followed by letters, digits (09), or underscores.
Comments
Comments are used to annotate and explain code. They start with a #
symbol and extend to the end of the line.
Data Types in Python
Numbers

Integer (int): Whole numbers, e.g.,
5
,10
. 
Float (float): Decimal numbers, e.g.,
2.5
,0.75
. 
Complex (complex): Complex numbers, e.g.,
3+4j
.
Sequences

String (str): Sequence of characters, e.g.,
"Hello"
. 
List: Ordered collection of items, e.g.,
[1, 2, 3]
. 
Tuple: Immutable ordered collection, e.g.,
(1, 2, 3)
.
Set
An unordered collection of unique items, defined using {}
, e.g., {1, 2, 3}
.
Mapping (Dictionary)
A collection of keyvalue pairs, defined using {}
, e.g., {'name': 'John', 'age': 25}
.
Boolean and None Types

Boolean (bool): Represents
True
orFalse
. 
NoneType: Represents the absence of value,
None
.
Variables and Operators
Defining Variables
Assign values to variables using the =
operator. E.g., x = 10
Arithmetic Operators
Perform mathematical operations like addition (+
), subtraction (
), multiplication (*
), division (/
).
Relational Operators
Compare values, e.g., ==
, !=
, <
, >
.
Logical Operators
Combine conditional statements, e.g., and
, or
, not
.
Assignment Operators
Assign or modify variable values, e.g., +=
, =
, *=
, /=
.
Identity Operators
Check if two variables refer to the same object, e.g., is
, is not
.
Membership Operators
Check membership in sequences, e.g., in
, not in
.
Python Expressions
What are Expressions?
Expressions are combinations of values, variables, and operators that evaluate to a single value.
Precedence of Operators
Operators have a specific order of precedence. For example, multiplication and division are performed before addition and subtraction.
graph TD;
A(Precedence of Operators);
B(Exponentiation ^);
C(Multiplication *);
D(Division /);
E(Addition +);
F(Subtraction );
A > B;
A > C;
A > D;
A > E;
A > F;
Input and Output in Python
Using the input()
Function for User Input
The input()
function reads a line from input and returns it as a string.
Example:
name = input("Enter your name: ")
print("Hello, " + name + "!")
Using the print()
Function for Output
The print()
function outputs data to the screen.
Example:
print("Hello, World!")
Type Conversion in Python
Explicit Conversion
Convert data types using functions like int()
, float()
, and str()
.
Example:
num = int("10")
pi = float("3.14")
Implicit Conversion
Python automatically converts types when needed.
Example:
result = 10 + 3.5 # result is a float
Debugging Python Programmes
Common Errors in Python
 Syntax Errors: Code does not conform to Python's syntax rules.
 Logical Errors: Code runs but produces incorrect results.
 Runtime Errors: Errors that occur during execution.
Techniques for Debugging
 Print Statements: Add print statements to observe variable values.

Debugging Tools: Use Python's builtin
pdb
module.
Advanced Topics
Working with Python Sequences
Understand and manipulate sequences like strings, lists, and tuples.
Conditional Statements and Loops
Control the flow of execution using if
, else
, while
, and for
loops.
Defining and Using Functions
Create reusable code blocks using def
to define functions.
Conclusion
This guide has provided an overview of Python programming for Class 11 students, covering everything from installation to basic syntax and debugging techniques. For further learning, explore additional resources and practice by writing your own Python programmes.
🚀 Learn more about Notes with Chatterbot AI
NCERT Solutions  Getting Started with Python  NCERT  Computer Science  Class 11
Which of the following identifier names are invalid and why?
i 

ii 

iii 

iv 

v 

vi 

vii 

viii 

Here are the identifier names and whether they are valid or not, along with reasons for the invalid identifiers:
#  Identifier  Validity  Reason 

i  Serial_no.  Invalid  Identifiers cannot contain special characters like a period (. ). 
ii  lst_Room  Valid  It follows all identifier naming rules. 
iii  Hundred$  Invalid  Identifiers cannot contain special characters like a dollar sign ($ ). 
iv  Total Marks  Invalid  Identifiers cannot contain spaces. 
v  Total_Marks  Valid  It follows all identifier naming rules. 
vi  totalMarks  Invalid  Identifiers cannot contain hyphens ( ). 
vii  _Percentage  Valid  It follows all identifier naming rules. 
viii  True  Invalid  True is a reserved keyword in Python and cannot be used as an identifier. 
Summary:
Invalid identifiers: Serial_no.
, Hundred$
, Total Marks
, totalMarks
, True
.
Special characters (
.
,$
,
) are not allowed in identifiers.Spaces in identifiers are not permitted.
Keywords like
True
,False
, etc., cannot be used as identifiers.
Write the corresponding Python assignment statements:
a) Assign 10 to variable length
and 20 to variable breadth
.
b) Assign the average of values of variables length
and breadth
to a variable sum.
c) Assign a list containing strings 'Paper', 'Gel Pen', and 'Eraser' to a variable stationery
.
d) Assign the strings 'Mohandas', 'Karamchand', and 'Gandhi' to variables first
, middle
and last
.
e) Assign the concatenated value of string variables first
, middle
and last to variable fullname
. Make sure to incorporate blank spaces appropriately between different parts of names.
Here's how you can write the corresponding Python assignment statements:
# Part a
length = 10
breadth = 20
# Part b
sum = (length + breadth) / 2
# Part c
stationery = ['Paper', 'Gel Pen', 'Eraser']
# Part d
first = 'Mohandas'
middle = 'Karamchand'
last = 'Gandhi'
# Part e
fullname = first + ' ' + middle + ' ' + last
Explanation:
In Part a, the assignment statements assign 10 to
length
and 20 tobreadth
.In Part b, the average of
length
andbreadth
is calculated and assigned tosum
.In Part c, a list containing the strings 'Paper', 'Gel Pen', and 'Eraser' is assigned to
stationery
.In Part d, the strings 'Mohandas', 'Karamchand', and 'Gandhi' are assigned to
first
,middle
, andlast
, respectively.In Part e, the string values of
first
,middle
, andlast
are concatenated with spaces in between and assigned tofullname
.
All these statements follow the Python syntax for variable assignments.
Write logical expressions corresponding to the following statements in Python and evaluate the expressions (assuming variables num1
, num2
, num3
, first
, middle
, last
are already having meaningful values):
a) The sum of 20 and 10 is less than 12 .
b) num3
is not more than 24 .
c) 6.75 is between the values of integers num 1 and num2
.
d) The string 'middle' is larger than the string 'first' and smaller than the string 'last'.
e) List Stationery
is empty.
Here are the logical expressions corresponding to the given statements implemented in Python.
# Assuming the variables already have meaningful values
# num1, num2, num3, first, middle, last, Stationery
# a) The sum of 20 and 10 is less than 12
result_a = (20 + (10)) < 12
# b) num3 is not more than 24
result_b = num3 <= 24
# c) 6.75 is between the values of integers num1 and num2
result_c = num1 < 6.75 < num2 if num1 < num2 else num2 < 6.75 < num1
# d) The string 'middle' is larger than the string 'first' and smaller than the string 'last'
result_d = first < middle < last
# e) List Stationery is empty
result_e = len(Stationery) == 0
# Evaluate results
print("a)", result_a)
print("b)", result_b)
print("c)", result_c)
print("d)", result_d)
print("e)", result_e)
These expressions evaluate the specified conditions:
a) The sum of 20 and 10 is checked to be less than 12.
b)
num3
is checked to be not more than 24.c) Checks if 6.75 lies strictly between
num1
andnum2
.d) Checks if the string 'middle' is alphabetically larger than 'first' and smaller than 'last'.
e) Checks if the list
Stationery
is empty by verifying its length is 0.
To evaluate these expressions, you would need to have appropriate values assigned to num1
, num2
, num3
, first
, middle
, last
, and Stationery
.
Add a pair of parentheses to each expression so that it evaluates to True.
a) 0==1==2
b) 2+3==4+5==7
c) 1<1==3>4
Here are the expressions with parentheses added so that they evaluate to True:
a) 0 == (1 == 2)
b) (2 + 3 == 4) + 5 == 7
c) 1 < (1 == 3 > 4)
To explain each one:
In (a), the inner expression
(1 == 2)
evaluates toFalse
, making the comparison0 == False
, which isTrue
.In (b), the inner parenthesis forces
2 + 3 == 4
to be evaluated asFalse
, which is effectively0
, resulting in5 == 7
after addition.In (c),
3 > 4
isFalse
, and1 == False
isTrue
, then the comparison1 < True
is alsoTrue
.
Write the output of the following:
a)
num1 = 4
num2 = num1 + 1
num1 = 2
print (num1, num2)
b)
num1, num2 = 2, 6
num1, num2 = num2, num1 + 2
print (num1, num2)
c)
num1, num2 =2,3
num3, num2 = num1, num3 + 1
print (num1, num2, num3)
a)
num1 = 4
num2 = num1 + 1
num1 = 2
print (num1, num2)
Output:
2 5
b)
num1, num2 = 2, 6
num1, num2 = num2, num1 + 2
print (num1, num2)
Output:
6 4
c)
num1, num2 = 2, 3
num3, num2 = num1, num3 + 1
print (num1, num2, num3)
Output:
This will produce an error because num3
is being used before it is assigned a value.
Which data type will be used to represent the following data values and why?
a) Number of months in a year
b) Resident of Delhi or not
c) Mobile number
d) Pocket money
e) Volume of a sphere
f) Perimeter of a square
g) Name of the student
h) Address of the student
To determine the suitable data types for the given data values, we need to consider the nature of the data:
a) Number of months in a year
Data Type: int
Reason: The number of months in a year is a whole number and does not change, which can be represented using an integer type.
b) Resident of Delhi or not
Data Type: bool
Reason: This represents a binary state (True/False), indicating whether a person is a resident of Delhi or not, suitable for Boolean type.
c) Mobile number
Data Type: str
Reason: Mobile numbers are usually stored as strings to preserve leading zeros and avoid limitations of integer operations (e.g., large number handling).
d) Pocket money
Data Type: float
Reason: Pocket money might involve decimal values, such as cents, making float a suitable data type.
e) Volume of a sphere
Data Type: float
Reason: Volume calculations typically result in real numbers, including floatingpoint representation for accuracy.
f) Perimeter of a square
Data Type: float
Reason: Although the perimeter of a square often results in an integer, using float ensures it can handle any potential decimal values accurately.
g) Name of the student
Data Type: str
Reason: Names are sequences of characters, hence best represented using strings.
h) Address of the student
Data Type: str
Reason: Addresses consist of characters, numbers, and sometimes special symbols, making strings the appropriate type.
Give the output of the following when num1 =4
, num2 =3
, num3=2
a)
num1 += num2 + num3
print (num1)
b)
num1 = num1 ** (num2 + num3)
print (num1)
c)
num1 **= num2 + num3
d)
num1 = '5' + '5'
print (num1)
e)
print (4.00/(2.0+2.0))
f)
num1 =2 + 9 ((3 * 12)8) / 10
print (num1)
g)
num1 = 24 // 4 // 2
h)
num1 = float(10)
print (num1)
i)
num1 = int('3.14')
print (num1)
j)
print('Bye' == 'BYE')
k)
print(10 != 9 and 20 >= 20)
l)
print (10 + 6 * 2 ** 2! = 9 / / 43 and 29 >= 29 / 9)
m)
print(5 % 10 + 10 < 50 and 29 <= 29)
n)
print (( 0 < 6) or (not(10==6) and (10 < 0)))
Let's determine the output of each code segment.
a)
num1 += num2 + num3
print(num1)`
Initial Values:
num1 = 4
,num2 = 3
,num3 = 2
Operation:
num1 += 3 + 2
→num1 = num1 + 5
→num1 = 4 + 5
→num1 = 9
Output:
9
b)
num1 = num1 ** (num2 + num3)
print(num1)
Values from (a):
num1 = 9
,num2 = 3
,num3 = 2
Operation:
num1 ** (3 + 2)
→9 ** 5
→59049
Output:
59049
c)
num1 **= num2 + num3
Values from (a):
num1 = 9
,num2 = 3
,num3 = 2
Operation:
num1 **= 3 + 2
→num1 = 9 ** 5
→num1 = 59049
No Print Statement, so no output.
d)
num1 = '5' + '5'
print(num1)
Operation:
'5' + '5'
→"55"
Output:
"55"
e)
print(4.00 / (2.0 + 2.0))
Operation:
4.00 / 4.0
→1.0
Output:
1.0
f)
num1 = 2 + 9 * ((3 * 12)  8) / 10
print(num1)
Operation: Assuming a typo, it should be:
2 + 9 * (36  8) / 102 + 9 * 28 / 102 + 252 / 102 + 25.227.2
Output:
27.2
g)
num1 = 24 // 4 // 2
Operation:
24 // 4 // 2
→6 // 2
→3
Output: Not printed.
h)
num1 = float(10)
print(num1)`
Operation:
float(10)
→10.0
Output:
10.0
i)
num1 = int('3.14')
print(num1)`
Operation: Attempting to convert
3.14
, a string with a decimal, to an integer will raise a ValueError.Output: Error
ValueError: invalid literal for int() with base 10: '3.14'
j)
print('Bye' == 'BYE')
Operation:
'Bye'
is not equal to'BYE'
because strings are casesensitive.Output:
False
k)
print(10 != 9 and 20 >= 20)
Operation:
10 != 9
evaluates toTrue
,20 >= 20
evaluates toTrue
. Hence,True and True
→True
Output:
True
l)
print(10 + 6 * 2 ** 2 != 9 // 4  3 and 29 >= 29 / 9)
Operation:
6 * 2 ** 2
→6 * 4
→24
10 + 24
→34
9 // 4
→2
2  3
→1
34 != 1
→True
29 / 9
→3.222
29 >= 3.222
→True
True and True
→True
Output:
True
m)
print(5 % 10 + 10 < 50 and 29 <= 29)
Operation:
5 % 10
→5
5 + 10
→15
15 < 50
→True
29 <= 29
→True
True and True
→True
Output:
True
n)
print((0 < 6) or (not(10 == 6) and (10 < 0)))
Operation:
(0 < 6)
→True
10 == 6
→False
not(False)
→True
(10 < 0)
→False
True and False
→False
True or False
→True
Output:
True
Summary of Outputs:
a) 9
b) 59049
c) No output as there's no print statement.
d) "55"
e) 1.0
f) 27.2
g) No output as there's no print statement.
h) 10.0
i) Error: ValueError: invalid literal for int() with base 10: '3.14'
j) False
k) True
l) True
m) True
n) True
Categorise the following as syntax error, logical error or runtime error:
a) 25 / 0
b) num1 = 25; num2 = 0; num1/num2
Here are the categorizations for the given errors:
a) 25 / 0
Runtime Error: This error occurs because division by zero is undefined, causing the interpreter to stop the execution with a runtime error.
b) num1 = 25; num2 = 0; num1/num2
Runtime Error: Similar to the first case, this error also occurs during execution when attempting to divide
num1
bynum2
which is zero. The interpreter will stop execution and throw a runtime error due to division by zero.
A dartboard of radius 10 units and the wall it is hanging on are represented using a twodimensional coordinate system, with the board's center at coordinate $(0,0)$. Variables $\mathrm{x}$ and $\mathrm{y}$ store the $\mathrm{x}$coordinate and the $\mathrm{y}$coordinate of a dart that hits the dartboard. Write a Python expression using variables $\mathrm{x}$ and $\mathrm{y}$ that evaluates to True if the dart hits (is within) the dartboard, and then evaluate the expression for these dart coordinates:
a) $(0,0)$
b) $(10,10)$
c) $(6,6)$
d) $(7,8)$
To determine if a dart lands within a dartboard of radius 10 units centered at (0, 0), we must check if the distance of the dart from the center is less than or equal to the radius of the dartboard. This can be achieved using the distance formula:
$$ \text{distance} = \sqrt{x^2 + y^2} $$
To check if the dart hits the board, the condition should be:
$$ x^2 + y^2 \leq 10^2 $$
In Python, this condition can be expressed as:
x**2 + y**2 <= 100
Let's evaluate this expression for the given coordinates:
For (0,0):
x = 0 y = 0 print(x**2 + y**2 <= 100) # True
For (10,10):
x = 10 y = 10 print(x**2 + y**2 <= 100) # False
For (6,6):
x = 6 y = 6 print(x**2 + y**2 <= 100) # True
For (7,8):
x = 7 y = 8 print(x**2 + y**2 <= 100) # True
Now, we can write a full Python script to evaluate these conditions:
dart_coordinates = [(0,0), (10,10), (6,6), (7,8)]
for x, y in dart_coordinates:
result = x**2 + y**2 <= 100
print(f"For coordinates ({x}, {y}): {result}")
Output:
For (0, 0): True
For (10, 10): False
For (6, 6): True
For (7, 8): True
Write a Python program to convert temperature in degree Celsius to degree Fahrenheit. If water boils at 100 degree $\mathrm{C}$ and freezes as 0 degree $\mathrm{C}$, use the program to find out what is the boiling point and freezing point of water on the Fahrenheit scale.
(Hint: $\mathrm{T}\left({ }^{\circ} \mathrm{F}\right)=\mathrm{T}\left({ }^{\circ} \mathrm{C}\right) \times 9 / 5+32$ )
To convert temperature from degrees Celsius to degrees Fahrenheit, you can use the formula provided:
$$ T(°F) = T(°C) \times \frac{9}{5} + 32 $$
Here's a Python program to perform the conversion and find out the boiling and freezing points of water in the Fahrenheit scale:
# Function to convert Celsius to Fahrenheit
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
# Boiling and Freezing points of water in Celsius
boiling_point_celsius = 100
freezing_point_celsius = 0
# Convert to Fahrenheit
boiling_point_fahrenheit = celsius_to_fahrenheit(boiling_point_celsius)
freezing_point_fahrenheit = celsius_to_fahrenheit(freezing_point_celsius)
# Output the results
print("Boiling point of water in Fahrenheit:", boiling_point_fahrenheit)
print("Freezing point of water in Fahrenheit:", freezing_point_fahrenheit)
Output:
Boiling point of water in Fahrenheit: 212.0
Freezing point of water in Fahrenheit: 32.0
Explanation:
Function Definition: The
celsius_to_fahrenheit
function takes a temperature in degrees Celsius and converts it to degrees Fahrenheit using the formula.Conversion: The program calculates the boiling and freezing points of water in Fahrenheit by passing 100°C and 0°C to the conversion function.
Output: Displays the boiling point (212°F) and freezing point (32°F) on the Fahrenheit scale.
Write a Python program to calculate the amount payable if money has been lent on simple interest.
Principal or money lent $=\mathrm{P}$, Rate of interest $=\mathrm{R} \%$ per annum and Time $=$ T years. Then Simple Interest $(\mathrm{SI})=(\mathrm{P} \times \mathrm{R} \times \mathrm{T}) / 100$
Amount payable $=$ Principal + SI.
$\mathrm{P}, \mathrm{R}$ and $\mathrm{T}$ are given as input to the program.
Here is a Python program to calculate the amount payable if money has been lent on simple interest. The program takes the principal amount (P), rate of interest (R), and time (T) as input from the user and then calculates the simple interest (SI) and the total amount payable.
# Program to calculate the amount payable on simple interest
# Input values
P = float(input("Enter the principal amount (P): "))
R = float(input("Enter the rate of interest (R) per annum: "))
T = float(input("Enter the time (T) in years: "))
# Calculate simple interest
SI = (P * R * T) / 100
# Calculate total amount payable
amount_payable = P + SI
# Display results
print(f"Simple Interest (SI): {SI}")
print(f"Amount Payable: {amount_payable}")
Explanation:
Inputs: The user is prompted to enter the principal amount, rate of interest, and time.
Simple Interest Calculation: The formula $\mathrm{SI} = \frac{\mathrm{P} \times \mathrm{R} \times \mathrm{T}}{100}$ is used to calculate the simple interest.
Total Amount Payable: The principal amount is added to the simple interest to get the total amount payable.
Output: The simple interest and the total amount payable are printed out.
Write a program to calculate in how many days a work will be completed by three persons A, B and C together. A, B, C take $\mathrm{x}$ days, $\mathrm{y}$ days and $\mathrm{z}$ days respectively to do the job alone. The formula to calculate the number of days if they work together is $\mathrm{xyz} /(\mathrm{xy}+\mathrm{yz}+\mathrm{xz})$ days where $\mathrm{x}, \mathrm{y}$, and $\mathrm{z}$ are given as input to the program.
You can use the following Python program to calculate the number of days it will take for three people (A, B, and C) to complete a job together using the given formula:
# Function to calculate the number of days to complete the work together
def calculate_days(x, y, z):
total_days = (x * y * z) / (x * y + y * z + x * z)
return total_days
# Main program
if __name__ == "__main__":
# Input the number of days each person takes to complete the work alone
x = int(input("Enter the number of days A takes to complete the work: "))
y = int(input("Enter the number of days B takes to complete the work: "))
z = int(input("Enter the number of days C takes to complete the work: "))
try:
# Calculate the total number of days to complete the work together
total_days = calculate_days(x, y, z)
print(f"The work will be completed in {total_days} days when A, B, and C work together.")
except ZeroDivisionError:
print("One or more of the inputs are zero, which makes the calculation invalid.")
Explanation:
Function
calculate_days
:Takes as input the number of days
x
,y
, andz
that person A, B, and C take to complete the work alone.Uses the given formula (\mathrm{xyz} /(\mathrm{xy}+\mathrm{yz}+\mathrm{xz})) to calculate the total number of days to complete the work if all three work together.
Main Program:
Prompts the user to enter the number of days
x
,y
, andz
for persons A, B, and C.Calls the
calculate_days
function and prints the result.Includes a tryexcept block to handle any division by zero errors if one of the inputs is zero.
Write a program to enter two integers and perform all arithmetic operations on them.
Here's a Python program that takes two integers as input and performs all arithmetic operations (addition, subtraction, multiplication, division, modulus, exponentiation, floor division) on them.
# Program to perform arithmetic operations on two integers
# Input: Accepting two integers from the user
num1 = int(input("Enter the first integer: "))
num2 = int(input("Enter the second integer: "))
# Performing arithmetic operations and displaying the results
print(f"Addition: {num1} + {num2} = {num1 + num2}")
print(f"Subtraction: {num1}  {num2} = {num1  num2}")
print(f"Multiplication: {num1} * {num2} = {num1 * num2}")
print(f"Division: {num1} / {num2} = {num1 / num2}")
print(f"Modulus: {num1} % {num2} = {num1 % num2}")
print(f"Exponentiation: {num1} ** {num2} = {num1 ** num2}")
print(f"Floor Division: {num1} // {num2} = {num1 // num2}")
Key Points:
The program first prompts the user to enter two integers.
It then performs and prints the results of addition, subtraction, multiplication, division, modulus, exponentiation, and floor division.
Make sure to handle cases where the second integer (num2
) is zero when performing operations like division and modulus to avoid runtime errors.
Write a program to swap two numbers using a third variable.
Here's a simple Python program to swap two numbers using a third variable:
# Program to swap two numbers using a third variable
# First, we define the numbers to be swapped
num1 = 5
num2 = 10
# We print the numbers before swapping
print("Before swapping:")
print("num1 =", num1)
print("num2 =", num2)
# We use a third variable to hold the value of num1 temporarily
temp = num1
num1 = num2
num2 = temp
# We print the numbers after swapping
print("After swapping:")
print("num1 =", num1)
print("num2 =", num2)
Output:
Before swapping:
num1 = 5
num2 = 10
After swapping:
num1 = 10
num2 = 5
This program demonstrates the use of a third variable to temporarily hold the value of one variable while assigning the value of the other variable, achieving the swap.
Write a program to swap two numbers without using a third variable.
You can swap two numbers without using a third variable by using arithmetic operations or the XOR bitwise operator. Here’s a Python program using the arithmetic operations method:
# Program to swap two numbers without using a third variable
# Input: Two numbers
num1 = 5
num2 = 10
print("Before swapping:")
print("num1 =", num1)
print("num2 =", num2)
# Swapping using arithmetic operations
num1 = num1 + num2 # num1 now becomes 15
num2 = num1  num2 # num2 now becomes 5
num1 = num1  num2 # num1 now becomes 10
print("After swapping:")
print("num1 =", num1)
print("num2 =", num2)
Explanation:
Initialize
num1
andnum2
with given values.Add
num2
tonum1
and store the result innum1
.Subtract the new
num1
(which isnum1 + num2
) bynum2
, and store the result innum2
.Subtract the new
num1
by the newnum2
, and store the result innum1
.Print the swapped values.
Output:
Before swapping:
num1 = 5
num2 = 10
After swapping:
num1 = 10
num2 = 5
Write a program to repeat the string "GOOD MORNING" $\mathrm{n}$ times. Here ' $\mathrm{n}$ ' is an integer entered by the user.
To write a Python program that repeats the string "GOOD MORNING" 'n' times, where 'n' is an integer entered by the user, you can use the following code:
# Program to repeat the string "GOOD MORNING" n times
# Take an integer input from the user
n = int(input("Enter the number of times you want to repeat 'GOOD MORNING': "))
# Repeat the string "GOOD MORNING" n times
output = "GOOD MORNING " * n
# Print the output
print(output)
This program uses the *
operator to repeat the string and takes the input using the input()
function. The input is then converted to an integer using int()
.
Write a program to find average of three numbers.
Below is a Python program to find the average of three numbers:
# Program to find the average of three numbers
# Input three numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
# Calculate the average
average = (num1 + num2 + num3) / 3
# Print the result
print("The average of the three numbers is:", average)
Explanation:
Input three numbers: Takes three numbers as input from the user and converts them to float data type.
Calculate the average: Sums the three numbers and divides by 3 to find the average.
Print the result: Outputs the calculated average to the screen.
The volume of a sphere with radius $r$ is $4 / 3 \pi r^{3}$. Write a Python program to find the volume of spheres with radius $7 \mathrm{~cm}, 12 \mathrm{~cm}, 16 \mathrm{~cm}$, respectively.
Here is a Python program to calculate the volume of spheres with given radii:
# Program to calculate the volume of a sphere
import math
def volume_of_sphere(radius):
volume = (4/3) * math.pi * (radius ** 3)
return volume
# Radii of the spheres
radii = [7, 12, 16]
# Calculate volumes
volumes = [volume_of_sphere(r) for r in radii]
# Print the results
for radius, volume in zip(radii, volumes):
print(f"The volume of a sphere with radius {radius} cm is {volume:.2f} cubic cm")
Output
The volume of a sphere with radius 7 cm is 1436.76 cubic cm
The volume of a sphere with radius 12 cm is 7238.23 cubic cm
The volume of a sphere with radius 16 cm is 17157.28 cubic cm
Explanation
Import the
math
module to get the value of π.Define the function
volume_of_sphere(radius)
which uses the formula: $ \text{volume} = \frac{4}{3} \pi r^3 $.Calculate the volume for the radii
[7, 12, 16]
.Output the volume for each radius formatted to two decimal places.
Write a program that asks the user to enter their name and age. Print a message addressed to the user that tells the user the year in which they will turn 100 years old.
Here's a Python program to accomplish that task:
# Program to calculate the year when the user will turn 100 years old
# Taking user's name as input
name = input("Enter your name: ")
# Taking user's age as input and converting it to an integer
age = int(input("Enter your age: "))
# Calculating the current year
from datetime import datetime
current_year = datetime.now().year
# Calculating the year in which the user will turn 100
year_turning_100 = current_year + (100  age)
# Printing the message with the calculated year
print(f"Hello {name}! You will turn 100 years old in the year {year_turning_100}.")
When you run this program, it will ask for the user's name and age, and then it will calculate and print the year in which they will turn 100 years old.
The formula $\mathrm{E}=\mathrm{mc}^{2}$ states that the equivalent energy (E) can be calculated as the mass (m) multiplied by the speed of light ( $\mathrm{c}=$ about $3 \times 10^{8} \mathrm{~m} / \mathrm{s}$ ) squared. Write a program that accepts the mass of an object and determines its energy.
Below is the Python program to calculate the energy (E) using the formula $ E = mc^2 $:
# Define the speed of light in meters per second
speed_of_light = 3 * 10**8
# Accept the mass of the object from the user
mass = float(input("Enter the mass of the object in kilograms: "))
# Calculate the energy using the formula E = mc^2
energy = mass * speed_of_light**2
# Print the calculated energy
print("The energy equivalent of the mass is:", energy, "Joules")
Explanation:
speed_of_light: This variable stores the speed of light in meters per second $3 * 10^8 m/s$.
mass: The mass of the object is taken as input from the user. The
float
function is used to make sure the input is treated as a floatingpoint number.energy: This variable stores the calculated energy using the formula $E = mc^2$.
The
print
statement outputs the calculated energy in Joules.
Presume that a ladder is put upright against a wall. Let variables length and angle store the length of the ladder and the angle that it forms with the ground as it leans against the wall. Write a Python program to compute the height reached by the ladder on the wall for the following values of length and angle:
a) 16 feet and 75 degrees
b) 20 feet and 0 degrees
c) 24 feet and 45 degrees
d) 24 feet and 80 degrees
Here is a Python program to compute the height reached by a ladder on the wall for given lengths and angles:
import math
# Function to calculate the height reached by the ladder
def height_reached(length, angle_degrees):
angle_radians = math.radians(angle_degrees) # Convert angle to radians
height = length * math.sin(angle_radians) # Calculate height using sine
return height
# Test cases
ladder_cases = [
(16, 75),
(20, 0),
(24, 45),
(24, 80)
]
for length, angle in ladder_cases:
height = height_reached(length, angle)
print(f"Length: {length} feet, Angle: {angle} degrees, Height reached: {height:.2f} feet")
Explanation of the Code:
Import the
math
module: This module provides access to mathematical functions likesin
which calculates the sine of an angle.Define a function
height_reached
:Convert the angle from degrees to radians using
math.radians
.Calculate the height using the formula $ \text{height} = \text{length} \times \sin(\text{angle in radians}) $. The sine function is used to find the vertical component of the ladder length.
Iterate through the test cases:
Compute and print the height reached by the ladder for each (length, angle) pair.
Output:
Length: 16 feet, Angle: 75 degrees, Height reached: 15.45 feet
Length: 20 feet, Angle: 0 degrees, Height reached: 0.00 feet
Length: 24 feet, Angle: 45 degrees, Height reached: 16.97 feet
Length: 24 feet, Angle: 80 degrees, Height reached: 23.64 feet
This will show the height on the wall reached by the ladder for the specified lengths and angles.
💡 Have more questions?
Ask Chatterbot AI