Class 10: Programming in Python

 PYTHON PROGRAMMING

INTRODUCTION TO PYTHON

Write short answers to these questions.

1)      What is python? Write its advantages and disadvantages.

Python is a high-level programming language that is easy to debug and understand. The advantages of python are:

i) It is simple and easy to understand.

ii) It is free and open source.

iii) It has large standard library.

Disadvantages;

i) It is slower than compiled languages like c++.

ii) It consumes high memory.

iii) Less suitable for mobile app development.

2)      What are input and output statements in python? Discuss with examples.

Input/Output (I/O) statements allow interaction with the program.  The input() function captures user data, such as number = input("Enter number: ").

3)      What is the use of 'sep' and 'end' with print statement?

The sep (separator) parameter is used to specify the character or string placed between multiple values printed by the print() function. Example: print(10, 20, 30, sep="-")

Output:

10-20-30

In Python, the end parameter in a print() statement specifies what to print at the end of the line instead of the default newline. For example, print(a, b, end=" ") prints a space after the output instead of moving to a new line.

4)      What is the use of f-string and format() function in string format?

An f-string is used for string formatting by allowing expressions to be embedded directly inside string literals using curly braces, such as print(f"Result: {result}"). The string formatting can also be done using the % operator for random number display, but they do not explicitly define the format() function.

5)      Describe local and global variable used in python with example.

A local variable is declared inside a function and is only accessible within that function's code block. A global variable is declared outside any function (at the top level) and can be accessed from anywhere in the program.

6)      What is the purpose of indentation in python?

Indentation in Python is used to define blocks of code. For instance, statements must be indented to be considered part of a function's body; statements outside that indentation are not part of the function.

7)      What is looping? Write the role of the range() function in python for loop.

Looping (Iteration) is the process of repeating a task until a specific condition is satisfied. The range() function defines a sequence of numbers, allowing a for loop to repeat a block of code a specific number of times.

8)      Write the differences between break and continue statement.

In Python, the break statement completely stops a loop, while the continue statement skips the current iteration and moves to the next one.

9)      How is built-in-function help in reducing code complexity.

Built-in functions reduce complexity by providing organized, reusable code for common tasks like sum() or len(). They are always available in memory, allowing for better modularity without the need for manual programming of standard operations.

10)   What is the primary function of the input() function in Python?

The primary function of the input() function is to allow a user to provide data to the program during execution.

11)   Provide an example of a string literal in Python.

A string literal consists of text or alphanumeric values enclosed in double quotes. An example is "hello".

12)   What is an identifier in the context of Python programming?

An identifier is a user-defined name given to various program units, including variables, functions, or classes.

13)   Explain the difference between the division operator (/) and the floor division operator (//) in Python.

The division operator (/) performs standard division, such as 20 / 10 = 2. The floor division operator (//) performs division and returns only the whole number part of the result, such as 9 // 2 = 4.

14)   Define the concept of data types in Python.

Data types define the kind of information a variable can store, such as whole numbers (integers), decimals (floats), text (strings), or Boolean values (True/False).

15)      Describe the functionality of the else block in an if-else statement.

In an if-else statement, the else block contains the code that will be executed if the condition in the if statement is False.

16)      What is a nested if statement?

A nested if is a programming construct where an if statement is placed inside another if statement.

17)      When would you typically use a for loop instead of a while loop?

We typically use a for loop when we know exactly how many times a block of code should repeat. A while loop is preferred when you want to repeat a task as long as a certain condition remains true.

18)      What is the role of the range() function often used with for loops?

The range() function provides the sequence of items that the for loop iterates through.

19)      Define a Python list and provide a simple example.

A Python list is a built-in data type used to store multiple items in a single variable. A simple example is thislist = ["Computer", "Science", 20, True].

20)      Discuss the concept of iteration in programming.

Iteration refers to the process of doing things repeatedly in a program until a target condition is met. It is fundamental for managing repetitive tasks through structures like loops. 

Write the output of the given program with dry run table:

Program: 1

x=15

y = 5

z = x-y

w=z+6

print(“Result:”, w)

 

Step

Statement

x

y

z

w

Output

1

x = 15

15

–

–

–

–

2

y = 5

15

5

–

–

–

3

z = x – y

15

5

10

–

–

4

w = z + 6

15

5

10

16

–

5

print("Result:", w)

15

5

10

16

Result: 16

 

Program 2:

l=8

b=4

a=l*b

p=2*(l+b)

print(“Area=”, a)

print(“Perimeter=”, p)

 

Step

Statement

l

b

a

p

Output

1

l = 8

8

–

–

–

–

2

b = 4

8

4

–

–

–

3

a = l * b

8

4

32

–

–

4

p = 2 * (l + b)

8

4

32

24

–

5

print("Area=", a)

8

4

32

24

Area= 32

6

print("Perimeter=", p)

8

4

32

24

Perimeter= 24

 Program 3

c=25

t= (c*9/5)+32

print(“Fahrenheit=”, t)

 

Step

Statement

c

t

Output

1

c = 25

25

–

–

2

t = (c * 9 / 5) + 32

25

77.0

–

3

print("Fahrenheit=", t)

25

77.0

Fahrenheit= 77.0

 Program 4

m=78

s=85

e=72

a=(m+s+e)/3

print(“Average=”, a)


Step

Statement

m

s

e

a

Output

1

m = 78

78

–

–

–

–

2

s = 85

78

85

–

–

–

3

e = 72

78

85

72

–

–

4

a = (m + s + e) / 3

78

85

72

78.33

–

5

print("Average=", a)

78

85

72

78.33

Average= 78.33

 Program 5

x=7

if x>5:

    print(“big”)

print(“done”)

 

Step

Statement

x

Condition (x > 5)

Output

1

x = 7

7

–

–

2

if x > 5

7

True

–

3

print("big")

7

True

big

4

print("done")

7

True

done

 

Program 6:

n=2       

if n%2==0:

    print(“Even”)

else

    print(“odd”)

print(“Finish”)

 

Step

Statement

n

Condition (n % 2 == 0)

Output

1

n = 2

2

–

–

2

if n % 2 == 0

2

True

–

3

print("Even")

2

True

Even

4

else (skipped)

2

–

–

5

print("Finish")

2

–

Finish

 

Program 7:

s=75

if s>=90:

    print(“A”)

elif s>=60:

    print(“B”)

else:

    print(“C”)

print(“done”)

 

Step

Statement

s

Condition Checked

Result

Output

1

s = 75

75

–

–

–

2

if s >= 90

75

75 >= 90

False

–

3

elif s >= 60

75

75 >= 60

True

B

4

else (skipped)

75

–

–

–

5

print("done")

75

–

–

done

program 8:

ch=’A’

if ch.isdigit():

    print(“Digit”)

elif ch.isalpha():

    print(“Alphabet)

else:

    print(“Other”)

 

Step

Statement

ch

Condition Checked

Result

Output

1

ch = 'A'

A

–

–

–

2

if ch.isdigit()

A

'A'.isdigit() → False

False

–

3

elif ch.isalpha()

A

'A'.isalpha() → True

True

Alphabet

4

else (skipped)

A

–

–

–

program 9:

y=2024

if y%400==0 or (y%4==0 and y%100!=0):

    print(f"{y} is a leap year.")

else:

    print(f"{y} is not a leap year.")

 

Step

Statement

y

Condition Checked

Result

Output

1

y = 2024

2024

–

–

–

2

if y % 400 == 0

2024

2024 % 400 == 0 → False

False

–

3

(y % 4 == 0 and y % 100 != 0)

2024

(2024 % 4 == 0 → True) and (2024 % 100 != 0 → True)

True

–

4

Overall condition: False or True → True

2024

–

True

–

5

print(f"{y} is a leap year.")

2024

–

–

2024 is a leap year.

6

else (skipped)

2024

–

–

–

Program 10:

a=10

b=20

c=15

if a>b and a>c) or (a<b and a>c):

    print("a is the middle value")

    elif (b>a and b>c) or (b<a and b>c):

    print("b is the middle value")

else:

    print("c is the middle value")

 

Step

Statement / Condition

a

b

c

Condition Result

Output

1

a = 10

10

–

–

–

–

2

b = 20

10

20

–

–

–

3

c = 15

10

20

15

–

–

4

if (a > b and a > c) → (10 > 20 and 10 > 15)

10

20

15

False

–

or (a < b and a > c) → (10 < 20 and 10 > 15)

False

–

Overall condition → False

False

–

5

elif (b > a and b > c) → (20 > 10 and 20 > 15)

10

20

15

True

b is the middle value

6

else (skipped)

10

20

15

–

–

 program 11:

u=85

if u<=50:

    print("Charge=5 per unit")

elif u<=100:

    print ("Charge=7 per unit")

else:

    print("Charge=10 per unit")


Step

Statement

u

Condition Checked

Result

Output

1

u = 85

85

–

–

–

2

if u <= 50

85

85 <= 50

False

–

3

elif u <= 100

85

85 <= 100

True

Charge=7 per unit

4

else (skipped)

85

–

–

–

 

Program  12:

for i in range(1, 11):

    print(3,"X",i,"=",3*i)

 

Step

i

Expression (3 * i)

Output

1

1

3 × 1 = 3

3 X 1 = 3

2

2

3 × 2 = 6

3 X 2 = 6

3

3

3 × 3 = 9

3 X 3 = 9

4

4

3 × 4 = 12

3 X 4 = 12

5

5

3 × 5 = 15

3 X 5 = 15

6

6

3 × 6 = 18

3 X 6 = 18

7

7

3 × 7 = 21

3 X 7 = 21

8

8

3 × 8 = 24

3 X 8 = 24

9

9

3 × 9 = 27

3 X 9 = 27

10

10

3 × 10 = 30

3 X 10 = 30

 program 13:

s=0

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

    s=s+i

    print("Sum=",s)

 

Step

i

Previous s

New s (s+i)

Output

1

2

0

2

Sum= 2

2

4

2

6

Sum= 6

3

6

6

12

Sum= 12

4

8

12

20

Sum= 20

5

10

20

30

Sum= 30

 

Program 14:

for c in "Computer":

    if c in "aeiou":

        print(c)

Program 15:

t=(5,10,15)

for I in range(len(t)):

print(I,”-->”, t[i]) 

 

Step

c

Condition (c in "aeiou")

Output

1

C

False

–

2

o

True

o

3

m

False

–

4

p

False

–

5

u

True

u

6

t

False

–

7

e

True

e

8

r

False

–

Program 16:

i=1

s=0

while i<4:

    s=s+i

    i=i+1

    print(s)

 

Step

i (before loop)

s (before loop)

Condition (i < 4)

New s (s+i)

New i (i+1)

Output

1

1

0

True

1

2

1

2

2

1

True

3

3

3

3

3

3

True

6

4

6

4

4

6

False

–

–

–

 

 

3. Write long answers to these questions.

a) Explain the different categories of operators available in Python (arithmetic, relational, and logical) with examples of each.

Operators in Python are special symbols used to perform actions on numbers and values. The three primary categories are:

      1. Arithmetic Operators: Used to perform mathematical calculations.
        • Addition (+): 10 + 20 = 30
        • Subtraction (-): 10 - 20 = -10
        • Multiplication (*): 10 * 20 = 200
        • Division (/): 20 / 10 = 2.0
        • Modulus (%): Calculates the remainder of division, e.g., 20 % 10 = 0.
        • Exponent (**): Calculates power, e.g., 10 ** 2 = 100.
        • Floor Division (//): Returns the whole number quotient, e.g., 9 // 2 = 4.
      1. Relational Operators: Used to compare two values.
        • Equal to (==): 5 == 5 (True)
        • Not equal to (!=): 3 != 5 (True)
        • Greater than (>): 7 > 5 (True)
        • Less than (<): 3 < 9 (True)
        • Greater than or equal to (>=): 8 >= 8 (True)
        • Less than or equal to (<=): 4 <= 6 (True)
      1. Logical Operators: Used to combine multiple conditions and make decisions.
        • and: Returns True only if both conditions are true (e.g., a and b).
        • or: Returns True if at least one condition is true (e.g., a or b).
        • not: Reverses the logical state of a condition (e.g., not(a)).

 

b) Describe the three main types of conditional statements in Python (if, if else, and if-elif-else).

Conditional statements execute specific blocks of code based on whether a given condition evaluates to True or False:

      1. if Statement: The simplest form of conditional statement; it executes a block of code only if the specified condition is true.
        • Example:

if number > 0:

    print("The number is positive.")

 

      1. if-else Statement: Allows execution of one code block if the condition is true, and an alternate block under else if the condition is false.
        • Example:

if user_age >= 18:

    print("You are an adult!")

else:

    print("You are a teenager or a kid.")

 

      1. if-elif-else Statement: Allows checking multiple conditions sequentially. If condition1 is false, it evaluates elif condition2; if all conditions are false, the final else block executes.
        • Example:

if user_number > 0:

    print("The number is positive.")

elif user_number == 0:

    print("The number is zero.")

else:

    print("The number is negative.")

 

c) Explain the two types of loops available in Python (for and while) w   ith their respective syntaxes and provide a practical example demonstrating the use of each loop.

Iteration refers to repeating a task until a specified condition is satisfied.

      1. for Loop: Used when you know in advance how many times a block of code needs to be repeated.
        • Syntax:

for item in sequence:

    # Code to execute for each item

      • Practical Example:

# Print "Programming" 5 times using range()

for x in range(5):

    print("Programming")

 

      1. while Loop: A control structure that continuously executes a block of code as long as the specified condition remains True.
        • Syntax:

while condition:

    # Code to execute while condition is True

      • Practical Example:

# Print numbers from 1 to 5

count = 1

while count <= 5:

    print(count)

    count += 1

 

d) Describe the four basic data types covered in the text (integer, float, string, and boolean), providing an example of each. Why is it important to understand data types when writing Python programs?

Four Basic Data Types Covered in the Text

      1. Integer (int): Whole numbers ranging from negative infinity to positive infinity without decimals (e.g., 15, -3, 0).
      2. Float (float): Numbers that contain fractional or decimal points (e.g., 3.14, -0.5).
      3. String (str): Text consisting of letters, numbers, or special characters enclosed within quotes (e.g., "hello", "Python@").
      4. Boolean (bool): Logical data type that holds only True or False values (e.g., is_student = True).

Understanding data types is crucial because the data type defines the kind of values a variable can hold and determines what operations can be performed on it. Selecting the correct data type ensures efficient data storage, prevents errors during arithmetic or string operations, and maintains overall data accuracy.

 

e) Imagine you need to write a Python program that takes an integer input from the user and performs the following actions:

 i. Prints “Positive” if the number is greater than 0.

ii. Prints “Negative” if the number is less than 0.

iii. Prints “Zero” if the number is equal to 0.

iv. If the number is positive, it then checks if it’s even or odd and prints the result.

# Program to check if a number is positive, negative, or zero

# and if positive, determine whether it is even or odd.

 

# Taking integer input from the user

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

 

# Checking the sign of the number

if num > 0:

    print("Positive")

    # Nested check for even or odd

    if num % 2 == 0:

        print("Even")

    else:

        print("Odd")

elif num < 0:

    print("Negative")

else:

    print("Zero") 

Post a Comment

Thank you for your comment

Previous Post Next Post