0% found this document useful (0 votes)
10 views

Ch 4 Assignment soln

The document provides an overview of fundamental programming concepts in Python, including variables, mutable and immutable types, and different types of errors. It explains built-in data types, operators, and their precedence, as well as the importance of comments in code. Additionally, it includes practical programming exercises related to Fibonacci series, user input, and temperature calculations.

Uploaded by

jiya23022009
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)
10 views

Ch 4 Assignment soln

The document provides an overview of fundamental programming concepts in Python, including variables, mutable and immutable types, and different types of errors. It explains built-in data types, operators, and their precedence, as well as the importance of comments in code. Additionally, it includes practical programming exercises related to Fibonacci series, user input, and temperature calculations.

Uploaded by

jiya23022009
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
You are on page 1/ 20

1. What are variables? How are they important for a program?

Variables are fundamental concepts in programming. They are used to


store and represent data that can be manipulated or used throughout a
program. Think of them as containers or placeholders for values like
numbers, text, or other types of data. Variables are essential for making
programs flexible, interactive, and functional.
2. Define’ Mutable’ and ‘immutable’ terms in Python.
An object is mutable if its contents or state can be changed after it is
created. In other words, you can modify, add, or remove elements from
the object.
Examples of mutable types:
• Lists: You can change, add, or remove elements.
• Dictionaries: You can add, modify, or remove key-value pairs.
• Sets: You can add or remove elements.
An object is immutable if its contents cannot be changed after it is
created. If you try to modify the object, it will result in a new object
being created instead.
Examples of immutable types:
• Strings: You can't change individual characters in a string.
• Tuples: Once created, the values in a tuple cannot be altered.
• Integers: You cannot change the value of an integer in-place.
3. What is an error in Python? Explain different types of errors with
examples.
1. Syntax Errors:
A syntax error occurs when the Python code is not written correctly
according to the rules of the Python language. This typically happens
when there is a typo, missing punctuation, or incorrect indentation.
Example of a Syntax Error:
# Missing parenthesis
print ("Hello, World!" # Syntax Error: unexpected EOF while parsing
2. Runtime Errors (Exceptions):
A runtime error (also known as an exception) occurs during the
execution of the program. These errors happen while the program is
running and can vary widely depending on the situation. Python raises
an exception when it encounters an unexpected situation, like trying to
divide by zero or accessing an index that doesn't exist in a list.
Examples of Runtime Errors:
• ZeroDivisionError: Trying to divide by zero.
x = 10
y=0
result = x / y # ZeroDivisionError: division by zero
3. Logical Errors:
A logical error occurs when the program runs without crashing, but the
output is not what the programmer expected. These errors happen
because of a flaw in the program's logic or reasoning, not because of a
syntax or runtime issue. Logical errors are often hard to debug because
the code runs without any exceptions.
Example of a Logical Error:
# Incorrect calculation
def calculate_area(length, width):
return length + width # Logical error: should be multiplication
area = calculate_area(5, 3)
print(area) # Output will be 8, but it should be 15
Other Error Types:
• Indentation Error: Occurs when the indentation of the code is
incorrect.
if True:
print("Hello") # Indentation Error: expected an indented block
• Type Error: Raised when an operation or function is applied to an
object of an inappropriate type.
x = "hello"
y=5
print(x + y) # Type Error: can only concatenate str (not "int") to str

4. Write a Python program for the Fibonacci series using a for loop.
5. Write a Python program to receive the numbers from the user
through the keyboard until the user gives 0 (to end the input process)
then, the program calculates and displays the sum of given odd
numbers and even numbers, respectively.
EXAMPLE: if the user gives the following sequence of numbers:
7 5 10 14 3 9 11 12
Then the output should be as follows: The Sum of even numbers in the
given input sequence = 36 The Sum of odd numbers in the given input
sequence = 35
6. Write a program that displays a joke. But display the punchline only
when the user presses the enter key. (HINT: you may use input() )

7. Write a program that generates the following output: 5 10 9


Assign 5 to a variable using the assignment operator (=). Multiply it with
2 to generate 10 and subtract 1 to generate 9.
8.If you give the following for str1=’’Hello’’ , why does python report
error? Str1[2]=’p’
• str1 = "Hello" creates a string.
• str1[2] = 'p' tries to modify the character at index 2 (which is 'l')
and replace it with 'p'.
Since strings are immutable, this operation is not allowed, and Python
raises a Type Error.
9. Explain Python Tokens and character sets in brief.
Python Tokens (in brief):
1. Keywords: Reserved words with predefined meanings, e.g., if,
else, def.
2. Identifiers: Names used for variables, functions, classes, e.g.,
my_var, total_sum.
3. Literals: Constant values like numbers (100), strings ("Hello"), and
Boolean values (True).
4. Operators: Symbols to perform operations, e.g., +, -, ==, and.
5. Separators: Characters that separate code elements, e.g., (), ,, :.
6. Comments: Non-executed text for explaining code, e.g., # this is a
comment.
Python Character Set (in brief):
1. Letters: Uppercase and lowercase English letters (a-z, A-Z).
2. Digits: Numeric characters (0-9).
3. Whitespace: Spaces, tabs, newlines for separation and
indentation.
4. Punctuation: Symbols like +, -, =, (), {}, [], . used for operations and
structure.

10. What is the importance of comments in Python?


Importance of Comments in Python (in small points):
1. Explain Code: Clarify the purpose of code for others or yourself.
2. Improve Readability: Make code easier to read and understand.
3. Aid Debugging: Temporarily disable code without deleting it.
4. Help Maintenance: Simplify future updates and modifications.
5. Facilitate Collaboration: Provide context for team members.
6. Document Assumptions: Record conditions or limitations of code.
7. Mark TODOs: Highlight areas needing further work or
improvement.

11. Explain different types of built-in data types in Python with


appropriate examples.
Different Types of Built-in Data Types in Python (in small points):
1. Integers (int):
o Whole numbers, positive or negative.
o Example: x = 10, y = -5
2. Floating-point numbers (float):
o Numbers with decimals.
o Example: x = 10.5, y = -3.14
3. Strings (str):
o Sequence of characters enclosed in single or double quotes.
o Example: name = "Alice", message = 'Hello'
4. Booleans (bool):
o Represents True or False values.
o Example: is_valid = True, is_done = False
5. Lists (list):
o Ordered collection of items (mutable).
o Example: numbers = [1, 2, 3], fruits = ['apple', 'banana']
6. Tuples (tuple):
o Ordered collection of items (immutable).
o Example: point = (1, 2), coordinates = (4, 5, 6)
7. Dictionaries (dict):
o Unordered collection of key-value pairs (mutable).
o Example: person = {'name': 'John', 'age': 30}
8. Sets (set):
o Unordered collection of unique items.
o Example: unique_numbers = {1, 2, 3}, letters = {'a', 'b', 'c'}
9. None Type (None):
o Represents the absence of a value or a null value.
o Example: result = None
These are the core built-in data types in Python that allow you to work
with different kinds of data.

12. Differentiate between explicit and implicit type conversion in


Python.
Here’s a simple tabular comparison between explicit and implicit type
conversion in Python:

Feature Explicit Type Conversion Implicit Type Conversion

Automatic conversion done by


Manual conversion of one
Definition Python between compatible
data type to another.
types.

Done using functions like Done automatically by Python


Method
int(), float(), str(), etc. during execution.

The programmer has The programmer has no


Control control over the control; Python does it
conversion. automatically.
Feature Explicit Type Conversion Implicit Type Conversion

x = int("10") (String to x = 5 + 3.2 (Integer and Float,


Example
Integer) result is a Float)

When Python decides a


When When you need to explicitly
conversion is safe and
Used change data types.
required.

Can cause errors if


Risk of Rarely causes errors, but can
conversion is not valid (e.g.,
Error lead to loss of precision.
int("abc")).

Example:
• Explicit: x = float("10") → Here, you manually convert a string "10"
to a float.
• Implicit: x = 10 + 2.5 → Python automatically converts the integer
10 to a float before performing the addition, resulting in a float
value 12.5.

13. Write down the syntax and use of the following data types: i) List,
ii)Tuple, iii)Dictionary, iv)Set, v)String
1. List
• Syntax:
• my_list = [element1, element2, element3, ...]
• Use:
o Ordered, mutable collection of elements.
o Can store elements of different types.
o Supports indexing, slicing, and modifying elements.
Example:
my_list = [1, 2, 3, "apple"]
my_list[0] = 5 # List is mutable
2. Tuple
• Syntax:
• my_tuple = (element1, element2, element3, ...)
• Use:
o Ordered, immutable collection of elements.
o Can store elements of different types.
o Faster than lists for fixed data.
Example:
my_tuple = (1, 2, 3, "apple")
3. Dictionary
• Syntax:
• my_dict = {key1: value1, key2: value2, key3: value3}
• Use:
o Unordered collection of key-value pairs.
o Keys are unique, and values can be of any type.
o Efficient for looking up values based on keys.
Example:
my_dict = {"name": "Alice", "age": 25}
print(my_dict["name"]) # Accessing value using key
4. Set
• Syntax:
• my_set = {element1, element2, element3, ...}
• Use:
o Unordered collection of unique elements.
o Does not allow duplicate values.
o Supports mathematical set operations like union,
intersection, etc.
Example:
my_set = {1, 2, 3, 4}
my_set.add(5) # Adding an element
5. String
• Syntax:
• my_string = "This is a string"
• Use:
o Immutable sequence of characters.
o Supports various methods for string manipulation like slicing,
concatenation, and formatting.
Example:
my_string = "Hello"
print(my_string[0]) # Accessing the first character
Summary of Usage:
• List: Ordered, mutable collection.
• Tuple: Ordered, immutable collection.
• Dictionary: Key-value pairs, unordered.
• Set: Unordered collection of unique elements.
• String: Immutable sequence of characters.

14. Define operators. Explain Arithmetic operator, Relational operator,


logical operator, identity operator and membership operator.
Operators in Python:
Operators are special symbols used to perform operations on variables
and values. They are used to manipulate data and variables.
1. Arithmetic Operators:
• Use: Perform basic mathematical operations.
• Operators: +, -, *, /, //, %, **

Operator Description Example

+ Addition a+b

- Subtraction a-b

* Multiplication a*b
Operator Description Example

/ Division (float result) a/b

// Floor Division (integer) a // b

% Modulus (remainder) a%b

** Exponentiation (power) a ** b

• Example:
• x=5
• y=2
• print(x + y) # Output: 7
2. Relational Operators:
• Use: Compare two values and return a Boolean (True or False).
• Operators: ==, !=, >, <, >=, <=

Operator Description Example

== Equal to a == b

!= Not equal to a != b

> Greater than a>b

< Less than a<b

>= Greater than or equal to a >= b

<= Less than or equal to a <= b

• Example:
• x = 10
• y = 20
• print(x < y) # Output: True
3. Logical Operators:
• Use: Perform logical operations and return a Boolean value.
• Operators: and, or, not

Operator Description Example

and Returns True if both are true a and b

or Returns True if at least one is true a or b

not Inverts the Boolean value not a

• Example:
• x = True
• y = False
• print(x and y) # Output: False
4. Identity Operators:
• Use: Compare the memory locations of two objects.
• Operators: is, is not

Operator Description Example

is Returns True if both are the same object a is b

is not Returns True if both are not the same object a is not b
• Example:
• a = [1, 2, 3]
• b=a
• print(a is b) # Output: True
5. Membership Operators:
• Use: Test if a value is a member of a sequence (like a list, string, or
tuple).
• Operators: in, not in

Operator Description Example

in Returns True if value is present in sequence x in list

Returns True if value is not present in x not in


not in
sequence list

• Example:
• fruits = ['apple', 'banana', 'cherry']
• print('apple' in fruits) # Output: True
Summary:
• Arithmetic Operators: Perform mathematical calculations.
• Relational Operators: Compare values and return Boolean results.
• Logical Operators: Combine or invert Boolean expressions.
• Identity Operators: Check if two variables point to the same
object.
• Membership Operators: Check if a value is part of a sequence.

15. Draw the precedence of all the operators in Python.


Here is a table showing the operator precedence in Python, which
determines the order in which operations are evaluated in an
expression:
Operator Precedence in Python

Precedence
Operators Description
Level

Parentheses for grouping


1 () (Parentheses)
operations

Exponentiation (right-to-left
2 ** (Exponentiation)
associativity)

Unary plus, Unary minus, Bitwise


3 +x, -x, ~x
NOT

Multiplication, Division, Floor


4 *, /, //, %
Division, Modulus

5 +, - Addition, Subtraction

6 <<, >> Bitwise shift operators

7 & Bitwise AND

8 ^ Bitwise XOR
Precedence
Operators Description
Level

9 ` `

Relational (Comparison)
10 ==, !=, >, <, >=, <=
operators

11 not Logical NOT

12 and Logical AND

13 or Logical OR

Identity and Membership


14 is, is not, in, not in
operators

=, +=, -=, *=, /=, //=,


15 =, <<=, >>=, **=`
%= , &=, ^=, `

The comma (used for separating


16 ,
arguments in function calls)
16. Write a program to obtain the temperature for 7 days (Monday,
Tuesday…Sunday) and then display the average temperature of the
week.

You might also like