0% found this document useful (0 votes)
8 views8 pages

Seesional Sol

Uploaded by

bittu4554gn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views8 pages

Seesional Sol

Uploaded by

bittu4554gn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Python Programming First Sessional

Solutions
Q1. In Python, variables store data values (e.g., strings, integers, floats) without
needing a type declaration. They’re named containers holding data for reuse or
manipulation. For example:
name = "Alice"
age = 25
print("Name:", name, "Age:", age)
This stores "Alice" in name and 25 in age.

Q2. The input() function in Python allows users to enter data during program
execution. It reads user input as a string, enabling interactive programs. For
example:
name = input("Enter your name: ")
print("Hello, " + name)

Q3. In Python, a local variable is defined within a function and accessible only
inside that function. A global variable is defined outside any function and
accessible throughout the program. For example:
x = 10 # global variable
def func():
y = 5 # local variable
Here, x is global, and y is local.

Q4. In Python, semicolons (;) are optional and not required to end statements, as
Python uses line breaks to separate them. If you add a semicolon at the end, it
won’t cause an error but is generally unnecessary. However, it’s used to write
multiple statements on one line.

Q5. In Python, a single-line comment starts with #, and anything after it is


ignored by the interpreter:
# This is a single-line comment
For multi-line comments, you can use triple quotes (''' or """), often used for
documentation:
"""
This is a
multi-line comment
"""
Q2 (a) The break statement exits a loop entirely when a condition is met, while
continue skips the current iteration, moving to the next one.
# Break example
for i in range(5):
if i == 3:
break
print(i)

# Continue example
for i in range(5):
if i == 3:
continue
print(i)
In the break example, the loop stops when i is 3; in the continue example, it
skips printing 3.
(b) # Input a number from the user
number = float(input("Enter a number: "))

# Check if the number is positive, negative, or zero


if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")
(C) In Python, blocks are groups of statements executed together based on
conditions, loops, or function calls. Python uses indentation to define blocks,
unlike other languages that use braces {}. Indentation helps structure code
clearly.
Examples of Python Blocks
1. Conditional Block: Executes a block only if the condition is true.
age = 18
if age >= 18:
print("You are eligible to vote.") # Indented; part of the block
2. Loop Block: Repeats a block of code for a specified number of iterations.
for i in range(3):
print("Hello") # This block runs 3 times
3. Function Block: Defines reusable code that can be called.
def greet():
print("Hello!") # This block runs when greet() is called

greet()
Each block is defined by indentation, making the code visually structured and
Pythonic. Indentation errors will cause Python to raise an error.

Q3 (a) In Python, data types define the type of data a variable can hold. Python
supports a wide range of built-in data types, which can be categorized into basic
and advanced types. Here, we'll discuss four basic data types.
1. Integer (int)
Represents whole numbers, both positive and negative, without a decimal point.
x=5
print(type(x)) # Output: <class 'int'>
2. Float (float)
Represents numbers with a decimal point, used for more precise values.
python
Copy code
y = 3.14
print(type(y)) # Output: <class 'float'>
3. String (str)
Represents a sequence of characters, enclosed in single, double, or triple quotes.
python
Copy code
name = "Alice"
print(type(name)) # Output: <class 'str'>
4. Boolean (bool)
Represents truth values: True or False.
python
Copy code
is_active = True
print(type(is_active)) # Output: <class 'bool'>
These basic data types form the foundation of variable storage and manipulation
in Python programs.
(b) # Input a number from the user
number = int(input("Enter a number: "))

# Initialize variables
factorial = 1
i=1

# Using while loop to calculate factorial


while i <= number:
factorial *= i
i += 1

# Print the factorial


print(f"The factorial of {number} is {factorial}")
(C) # Input a number from the user
number = int(input("Enter a number: "))

# Check if the number is divisible by both 5 and 3


if number % 5 == 0 and number % 3 == 0:
print(f"{number} is divisible by both 5 and 3.")
else:
print(f"{number} is not divisible by both 5 and 3.")

Q4 (a) # Input a number from the user


number = int(input("Enter a number: "))
# Prime number check
if number <= 1:
print(f"{number} is not a prime number.")
else:
is_prime = True
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
is_prime = False
break

if is_prime:
print(f"{number} is a prime number.")
else:
print(f"{number} is not a prime number.")

(b)
def count_case_letters(input_string):
# Initialize counters for uppercase and lowercase letters
uppercase_count = 0
lowercase_count = 0

# Loop through each character in the string


for char in input_string:
if char.isupper():
uppercase_count += 1
elif char.islower():
lowercase_count += 1

return uppercase_count, lowercase_count

# Example usage
input_string = input("Enter a string: ")
upper, lower = count_case_letters(input_string)
print(f"Uppercase letters: {upper}")
print(f"Lowercase letters: {lower}")
Q5 (a)

# Function to check Armstrong number


def is_armstrong(number):
# Convert the number to a string to easily loop through digits
num_str = str(number)
num_digits = len(num_str)

# Calculate the sum of digits raised to the power of num_digits


sum_of_powers = sum(int(digit) ** num_digits for digit in num_str)

# Check if the sum of powers equals the original number


return sum_of_powers == number

# Input from the user


number = int(input("Enter a number: "))

# Check and display result


if is_armstrong(number):
print(f"{number} is an Armstrong number.")
else:
print(f"{number} is not an Armstrong number.")
Explanation:
1. is_armstrong: This function converts the number to a string to easily
access its digits and calculates the sum of each digit raised to the power
of the number of digits.
2. It then checks if this sum equals the original number.
3. The program takes input from the user and calls the is_armstrong function
to check if the number is Armstrong or not, printing the result accordingly.
Example:
 For the input 153, the program will output: 153 is an Armstrong number.
 For the input 123, the program will output: 123 is not an Armstrong
number.
(b)
What is a Palindrome?
A palindrome is a number (or word) that reads the same backward as forward.
For example, 121 is a palindrome because it remains the same when reversed.
# Function to check if the number is a palindrome
def is_palindrome(number):
# Convert the number to a string to easily reverse it
num_str = str(number)
# Check if the string is the same when reversed
return num_str == num_str[::-1]

# Input from the user


number = int(input("Enter a number: "))

# Check and display result


if is_palindrome(number):
print(f"{number} is a palindrome.")
else:
print(f"{number} is not a palindrome.")

Explanation:
1. is_palindrome: The function converts the number into a string and
compares it with its reverse using slicing ([::-1]).
2. If the number is the same as its reverse, it is a palindrome.
3. The program accepts user input and checks whether the number is a
palindrome or not.
Example:
 For the input 121, the program will output: 121 is a palindrome.
 For the input 123, the program will output: 123 is not a palindrome.

You might also like