0% found this document useful (0 votes)
11 views24 pages

Convert Decimal to Binary and Python Basics

The document provides a series of programming exercises and explanations related to Python, covering topics such as number conversion, type conversion, control structures, functions, file access modes, and turtle graphics. It includes code examples and explanations for concepts like while loops, default arguments, and dictionary creation. Additionally, it discusses Python's applications in various fields including AI, data science, and web development.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views24 pages

Convert Decimal to Binary and Python Basics

The document provides a series of programming exercises and explanations related to Python, covering topics such as number conversion, type conversion, control structures, functions, file access modes, and turtle graphics. It includes code examples and explanations for concepts like while loops, default arguments, and dictionary creation. Additionally, it discusses Python's applications in various fields including AI, data science, and web development.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

13.

How can you convert the decimal number (99)10 to

a binary number

Answer :

Step 1: Divide the number by 2 and record the remainder.

99 ÷ 2 = 49 remainder 1

49 ÷ 2 = 24 remainder 1

24 ÷ 2 = 12 remainder 0

12 ÷ 2 = 6 remainder 0

6 ÷ 2 = 3 remainder 0

3 ÷ 2 = 1 remainder 1

1 ÷ 2 = 0 remainder 1

Step 2: Write the remainders in reverse order (from last to first).

Binary = 1100011

Answer:

(99)_{10} = (1100011)_{2}

Alternative in Python:

decimal = 99

binary = bin(decimal)

print(binary) # Output: 0b1100011

14. Compare and contrast the “implicit type

conversion” with “explicit type conversion”

Answer :

Feature Implicit type conversion Explicit type conversion


Definition Conversion of one data type Conversion of one data type
to another automatically by to another **manually
the compiler/interpreter.

Also called Type coercion Type casting

Control Control by python Control by programmer

Example python x = 5 y = 2.5 python x = 5 y = int(2.5)

z = x + y # x is # explicitly converting

flowautomatically float to int print(x + y

converted to float

print(z) # Output: 7.5

15. Write a simple Python code to display the number

of days in a given month (Using IF...)

Answer :

# Program to display the number of days in a given month

month = input("Enter the name of the month: ").lower()

if month in ("january", "march", "may", "july", "august", "october", "december"):

print("31 days")

elif month in ("april", "june", "september", "november"):

print("30 days")

elif month == "february":

print("28 or 29 days")

else:

print("Invalid month name")

Explanation:

1. input() takes the month name from the user.


2. .lower() ensures the input is case-insensitive.

3. if...elif...else checks which month it is and prints the number of days.

Sample Output:

Enter the name of the month: March

31 days

Enter the name of the month: February

28 or 29 days

16. Demonstrate the use of “While” Statement in

Python with an example program.

Answer :

Use of while Statement in Python:

The while loop is used to repeatedly execute a block of code as long as a


condition is True. It is useful when the number of iterations is not known in advance.

Example Program:

# Program to print numbers from 1 to 5 using while loop

i = 1 # initialization

while i <= 5: # condition

print(i)

i += 1 # increment to avoid infinite loop

Output:

5
Explanation:

1. i starts at 1.

2. The loop checks the condition i <= 5.

3. If True, it prints i and increments it by 1.

4. The loop stops when i becomes 6 (condition becomes False).

17. Interpret the general syntax of a Function with

proper example.

Answer :

function is a block of code that performs a specific task and can be reused.

Syntax:

def function_name(parameters):

"""Optional docstring to describe the function"""

# statements

return value # optional

Explanation of Syntax:

def → Keyword to define a function.

function_name → Name of the function (should be descriptive).

parameters → Inputs to the function (can be optional).

"""Docstring""" → Optional description of the function.

return → Optional, returns a value from the function.

Example:

def add_numbers(a, b):

"""This function returns the sum of two numbers"""


return a + b

result = add_numbers(5, 3)

print(result) # Output: 8

Explanation:

1. add_numbers is the function name.

2. a and b are parameters.

3. The function returns the sum of a and b.

4. The function is called using add_numbers(5, 3) and the result is printed.

18. Infer a set of instructions for controlling the turtle

to create three concentric circles, each different

color and line width

Answer :

import turtle

# Set up the turtle

t = [Link]()

[Link](1) # Set drawing speed

# Draw first circle

[Link](2) # Line width

[Link]("red") # Color

[Link]()

[Link](0, -50) # Position to center the circle

[Link]()

[Link](50) # Radius 50
# Draw second circle

[Link](4)

[Link]("blue")

[Link]()

[Link](0, -100)

[Link]()

[Link](100)

# Draw third circle

[Link](6)

[Link]("green")

[Link]()

[Link](0, -150)

[Link]()

[Link](150)

# Finish

[Link]()

Explanation:

1. [Link]() creates a turtle object.

2. pensize() sets the line width.

3. pencolor() sets the drawing color.

4. goto() moves the turtle to the correct position so circles are concentric.

5. circle(radius) draws a circle with the given radius.


19. Explain the following file access modes in Python

(a) Read Only (‘r’)

(b) Read and Write (‘r+’)

(c) Write Only (‘w’)

(d) Write and Read (‘w+’)

Answer :

Read Only ('r'):

 Opens the file only for reading.

 The file must exist, otherwise it gives an error.

Example:

f = open("[Link]", "r")

content = [Link]()

[Link]()

(b) Read and Write ('r+'):

 Opens the file for both reading and writing.

 The file must exist.

Example:

f = open("[Link]", "r+")

[Link]("Hello") # Can write

[Link](0)

print([Link]()) # Can read

[Link]()
(c) Write Only ('w'):

 Opens the file only for writing.

 If the file exists, its content is overwritten; if it doesn’t exist, a new file is created.

Example:

f = open("[Link]", "w")

[Link]("Hello World")

[Link]()

(d) Write and Read ('w+'):

 Opens the file for both writing and reading.

 Existing content is overwritten, or a new file is created if it doesn’t exist.

Example:

f = open("[Link]", "w+")

[Link]("Hello World")

[Link](0)

print([Link]())

[Link]()

20. Explain the following fundamental hardware

components

(a) Central Processing Unit

(b) Output Devices.

Answer :

(a) Central Processing Unit (CPU):


 The CPU is the brain of the computer.

 It performs all calculations, logic operations, and controls the execution of instructions.

 It consists of ALU (Arithmetic Logic Unit) for calculations, CU (Control Unit) to manage
instructions, and Registers for temporary storage.

 Example: Intel i5, AMD Ryzen.

(b) Output Devices:

 Output devices are hardware components that display or provide the results of
computer processing to the user.

 They convert digital data into a human-readable or usable form.

 Examples: Monitor, Printer, Speakers.

21. What is a control character? Give an example.

Answer :

Control Character in Python:

A control character is a special character in a string that does not represent a


printable symbol but is used to control the behavior of text (like moving to a new line, tab space,
or carriage return).

Example:

\n → New line

\t → Horizontal tab

Code Example:

print("Hello\nWorld") # \n moves "World" to the next line

Output:

Hello
World

Summary: Control characters are used to format text output or control cursor movement in
programs.

22. Demonstrate the working principle of a While loop with an example.

Answer :

while loop repeatedly executes a block of code as long as a given condition is True. The
loop checks the condition first, and if it is True, executes the code inside the loop. This
continues until the condition becomes False.

Syntax:

while condition:

# code to execute

Example:

# Program to print numbers from 1 to 5 using while loop

i = 1 # initialization

while i <= 5: # condition

print(i)

i += 1 # increment to avoid infinite loop

Output:

Explanation:

1. i is initialized to 1.
2. The loop checks i <= 5. If True, it prints i.

3. i is incremented by 1.

4. The loop stops when i > 5.

Summary: The while loop is useful when the number of iterations is not known beforehand.

[Link] the “if” statement that displays ‘within

range’ if num is between 0 and 100, inclusive and

displays ‘out of range’ otherwise

Answer :

There’s a small error in your code: you are taking input into the variable m but using
num in the if condition. It should be consistent. Here’s the corrected program:

# Program to check if a number is within the range 0 to 100

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

if 0 <= m <= 100:

print("within range")

else:

print("out of range")

Explanation:

int(input()) takes a number from the user.

0 <= m <= 100 checks if the number is between 0 and 100 inclusive.

If true, it prints "within range"; otherwise, it prints "out of range".

Sample Output:

Enter a number: 45

within range

Enter a number: 150

out of range
24. Write a short note on default argument in

Python.

Answer :

Default Argument in Python:

A default argument is a function parameter that assumes a default value if no


value is provided during the function call. It allows functions to be called with fewer arguments
than defined.

Example:

def greet(name="Friend"):

print("Hello,", name)

greet() # Output: Hello, Friend

greet("Yogesh") # Output: Hello, Yogesh

Key Points:

 Default arguments must be placed after non-default arguments in the function definition.

 They make functions more flexible and easier to use.

25.. How module is specified? What is the use of

“docstring” used in it?

Answer :

How a module is specified:

A module in Python is a file that contains Python definitions and statements (like
functions, variables, and classes) and has the .py extension. You can specify or use a module in
another program by using the import statement.

Example:

# math_module.py

def add(a, b):


return a + b

# main_program.py

import math_module

result = math_module.add(5, 3)

print(result) # Output: 8

2. Use of “docstring” in a module:

A docstring is a string literal written at the beginning of a module, function, or class


to describe its purpose. It helps document the code and can be accessed using the __doc__
attribute.

Example:

"""This module performs basic arithmetic operations."""

def add(a, b):

"""This function returns the sum of two numbers."""

return a + b

print(add.__doc__)

Output:

This function returns the sum of two numbers.

26. Outline any four set operators in Python.

Answer :

In Python, set operators are used to perform operations on sets. Four common set
operators are:

1. Union (|) – Combines all elements from two sets, removing duplicates.

set1 | set2

2. Intersection (&) – Returns elements common to both sets.

set1 & set2


3. Difference (-) – Returns elements present in the first set but not in the second.

set1 - set2

4. Symmetric Difference (^) – Returns elements present in either set but not in both.

set1 ^ set2

These operators are very useful for tasks involving comparison, filtering, and data manipulation.

[Link] is Python? Where it is used effectively in

recent technologies?

Answer :

Python is a high-level, interpreted, and general-purpose programming language known for its
simple syntax, readability, and versatility. It supports multiple programming paradigms like
procedural, object-oriented, and functional programming

Key Features:

 Easy to learn and write

 Open-source and cross-platform

 Extensive standard libraries

 Supports rapid development

Uses in Recent Technologies:

1. Artificial Intelligence (AI) & Machine Learning (ML): Python is widely used with
libraries like TensorFlow, PyTorch, and scikit-learn.

2. Data Science & Analytics: Tools like Pandas, NumPy, and Matplotlib make data
analysis and visualization easy.

3. Web Development: Frameworks like Django and Flask help build web applications.

4. Automation & Scripting: Python scripts automate repetitive tasks efficiently.

5. Internet of Things (IoT): Python runs on devices like Raspberry Pi for IoT projects.

6. Cybersecurity & Networking: Python is used for penetration testing, network


automation, and security tools.
[Link] a program to get your name as input

and print the same on the screen.

Answer :

# Get the user's name as input

name = input("Enter your name: ")

# Print the name

print("Your name is:", name)

Explanation:

1. input() is used to take input from the user.

2. The entered value is stored in the variable name.

3. print() displays the value of name on the screen.

Sample Output:

Enter your name: Yogesh

Your name is: Yogesh

29. Illustrate the steps to create a dictionary in

Python with an example.

Answer :

Steps to Create a Dictionary in Python:

1. Use curly braces {} to define a dictionary.

2. Add key-value pairs separated by a colon :.

3. Separate multiple items with commas ,.

Example:

# Creating a dictionary
student = {

"name": "John",

"age": 20,

"grade": "A"

print(student)

Output:

{'name': 'John', 'age': 20, 'grade': 'A'}

Explanation:

"name", "age", "grade" are keys.

"John", 20, "A" are their respective values.

Keys must be unique, and values can be of any data type.

30. Write a program using simple IF statement to

determine a person is eligible to vote or not using

the age of the person. [Note: Eligibility to vote is

on or after 18 years of age].

Answer :

# Input the age of the person

age = int(input("Enter your age: "))

# Check eligibility using if-else

if age >= 18:

print("You are eligible to vote.")

else:
print("You are not eligible to vote.")U po

31. Outline the syntax for declaring a function in

Python.

Answer :

def function_name(parameters):

"""

Optional docstring to describe the function

"""

# Block of statements

statements

return value # Optional

explanation:

1. def keyword is used to define a function.

2. function_name is the name of the function.

3. parameters (optional) are values passed to the function.

4. Docstring (optional) describes the function’s purpose.

5. statements form the body of the function.

6. return (optional) sends a value back to the caller.

Example:

def add(a, b):

"""This function adds two numbers"""

return a + b

32. . Draw a simple square using turtle library in


Python

Answer :

import turtle

# Create a turtle object

t = [Link]()

# Draw a square

for _ in range(4):

[Link](100) # Move forward by 100 units

[Link](90) # Turn right by 90 degrees

# Keep the window open

[Link]()

Explanation:

 [Link](100) moves the turtle forward.

 [Link](90) turns the turtle 90 degrees to the right.

Looping 4 times creates a square.

 [Link]() keeps the window open until closed by the user.

33.. What is a dictionary? How can you create and add

an element to it?

Answer :

Dictionary in Python:

A dictionary is a collection of key-value pairs where each key is unique and maps to a value.
Dictionaries are unordered and mutable.

Creating a Dictionary:

# Empty dictionary
my_dict = {}

# Dictionary with initial values

my_dict = {"name": "Alice", "age": 25}

Adding an Element:

# Adding a new key-value pair

my_dict["city"] = "New York"

print(my_dict)

Output :

{'name': 'Alice', 'age': 25, 'city': 'New York'}

Explanation:

A dictionary is defined using curly braces {}.

New elements can be added by assigning a value to a new key.

34. How Computer Hardware is different from

Computer Software? Explain.

Answer :

Feature Hardware Software

Definition The physical components of a The programs and


computer that you can touch, instructions that tell the
like CPU, monitor, keyboard. computer how to perform
tasks, like Windows, Python,
MS Office.

Tangibility Tangible (can be physically Intangible (cannot be


touched) touched)

Function Performs the actual work of Controls and manages the


input, processing, storage, and hardware to perform specific
output. tasks.

Examples Keyboard, Mouse, Hard Disk, Operating System,


Printer Applications, Games

Dependency Can exist without software Cannot exist without


but cannot operate usefully hardware; requires hardware
without it. to run.

35. Summarize the features of Python language.

Answer :

Features of Python:

1. Easy to Learn and Read: Python has simple syntax similar to English, making it
beginner-friendly.

2. Interpreted Language: Python code is executed line by line, which makes debugging
easier.

3. High-Level Language: Python handles complex details like memory management


automatically.

4. Dynamically Typed: Variable types are determined at runtime, no need to declare


explicitly.

5. Extensive Libraries: Python provides a wide range of built-in modules and libraries for
various tasks.

6. Portable: Python code can run on multiple platforms without modification.

36. Interpret the need for range() function in python

with an example

Answer :

Need for range() function in Python:

The range() function is used to generate a sequence of numbers, which is commonly used in
loops for iteration. It helps avoid manually creating lists of numbers and makes loop control
easier.

Example:
# Using range() to print numbers from 1 to 5

for i in range(1, 6):

print(i)

Explanation:

 range(1, 6) generates numbers from 1 up to 5 (6 is excluded).

 The for loop iterates over each number in the sequence.

Output:

This shows how range() simplifies repetitive tasks in loops.

37. Illustrate any five Siring functions with an

example in Python.

Answer :

1. len() – Returns the length of a string

text = "Hello"

print(len(text)) # Output: 5

2. upper() – Converts all characters to uppercase

text = "hello"

print([Link]()) # Output: HELLO

3. lower() – Converts all characters to lowercase


text = "HELLO"

print([Link]()) # Output: hello

4. replace() – Replaces a substring with another

text = "I like cats"

print([Link]("cats", "dogs")) # Output: I like dogs

5. split() – Splits a string into a list based on a separator

text = "apple,banana,cherry"

print([Link](",")) # Output: ['apple', 'banana', 'cherry']

38. Illustrate the task of returning values by a

function with a simple program

Answer :

# Function to add two numbers and return the result

def add_numbers(a, b):

return a + b

# Calling the function and storing the returned value

result = add_numbers(5, 7)

print("The sum is:", result)

Explanation:

 The function add_numbers takes two parameters a and b.

 return a + b sends the sum back to the caller.

 The returned value is stored in result and displayed.

39. Outline a set of instructions to create a turtle

window of size 400 pixels wide and 600 pixels


high, with a title of ‘Turtle Graphics Window

Answer :

import turtle

# Create a screen object

screen = [Link]()

# Set the size of the window (width=400, height=600)

[Link](width=400, height=600)

# Set the title of the window

[Link]("Turtle Graphics Window")

# Keep the window open

[Link]()

Explanation:

 [Link]() creates a new turtle graphics window.

 setup(width, height) sets the size of the window.

title() sets the window’s title.

 [Link]() keeps the window open until the user closes it.

40. Demonstrate a program segment that opens and

reads a text file and displays how many lines of

text are in the file.

Answer :

# Open the file in read mode

file = open("[Link]", "r")

# Read all lines into a list


lines = [Link]()

# Count the number of lines

line_count = len(lines)

print("Number of lines in the file:", line_count)

# Close the file

[Link]()

Explanation:

 open("[Link]", "r") opens the file for reading.

readlines() reads all lines into a list.

 len(lines) gives the total number of lines.

Finally, the file is closed using [Link]().

You might also like