Python Assign 1
Python Assign 1
Python Assign 1
Python is a versatile and powerful programming language known for several key features
that make it popular among developers. Here are the main features of Python with simple
and relatable examples:
Example:
python
Explanation: In Python, you don’t need to declare variable types explicitly. This simplicity
lets you focus more on the logic than on language specifics.
2. Interpreted Language
No Compilation Step: Python is an interpreted language, meaning the code is executed
line by line, which makes debugging easier.
Example:
python
3. Dynamically Typed
No Need to Declare Variable Types: You don’t need to define the type of variables (like
int , float , or string ). Python determines the type at runtime.
Example:
python
Explanation: You can change the type of a variable on the fly. This dynamic typing allows
for faster development but may require more caution to avoid type-related errors.
Example:
python
import math
print(math.sqrt(16)) # Outputs 4.0
Explanation: The math module is part of Python’s standard library and provides access
to mathematical functions, so you don’t have to manually implement such functionality.
5. Cross-Platform Language
Run on Multiple Operating Systems: Python is platform-independent, meaning you can
run the same Python code on different operating systems (Windows, macOS, Linux)
without modification.
Example:
Explanation: You don’t need to worry about platform-specific issues while writing
Python code, making it ideal for cross-platform development.
Example (Object-Oriented):
python
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(f"{self.name} says Woof!")
my_dog = Dog("Buddy")
my_dog.bark()
Explanation: Here, Python’s OOP features allow the creation of objects (like my_dog )
with methods like bark() .
Example (Functional):
python
def square(x):
return x * x
8. High-Level Language
Closer to Human Language: Python is a high-level language, meaning it abstracts away
most of the complexities of the machine, like memory management.
Example:
python
Example:
Popular libraries like NumPy (for scientific computing), Pandas (for data
manipulation), and Django (for web development) are created and maintained by
the Python community.
Example:
python
Explanation: Python’s ability to interface with other languages makes it ideal for
combining the ease of Python with the speed of lower-level languages for critical
operations.
Example:
python
a = 5
a = None # Previous memory is freed automatically
Example (Tkinter):
python
Explanation: Using Tkinter , Python makes it easy to create desktop applications with
graphical interfaces.
These features together make Python a powerful, flexible, and easy-to-use language for
beginners and experts alike.
The CPU is the brain of the computer. It performs arithmetic and logic operations,
controls all the other components, and processes instructions from programs.
Control Unit (CU): Directs the operations of the CPU by fetching and executing
instructions.
Registers: Small storage areas within the CPU that store temporary data and
instructions.
2. Memory (RAM):
Random Access Memory (RAM) is the temporary memory used by the computer to
store data that is actively being worked on.
RAM is volatile, meaning the data is lost when the computer is turned off.
3. Storage (HDD/SSD):
Hard drives (HDD) and solid-state drives (SSD) store data permanently. This includes
the operating system, applications, and user files.
Unlike RAM, data in storage is retained even when the power is off.
4. Input Devices:
Devices like keyboards, mice, and scanners allow users to interact with the computer
by sending data and commands to the system.
Devices like monitors and printers display or produce the results of the computer’s
processing.
6. Motherboard:
The motherboard is the main circuit board that connects the CPU, memory, storage,
and other components. It serves as the communication hub for all hardware
components.
7. Bus:
A bus is a communication system that transfers data between the CPU, memory,
and other devices.
There are various types of buses, such as data bus (for transferring data), address
bus (for transferring memory addresses), and control bus (for controlling
operations).
8. Power Supply:
The power supply converts electrical power from an outlet into a form that the
computer components can use to function properly.
Neat Diagram:
Imagine a simple block diagram where each component is connected to the Motherboard
(acting as a central unit). The CPU is at the core, connected to RAM, Storage, and
Input/Output Devices via Buses.
1. CPU ↔ RAM
Main Roles:
They also test the code to ensure it works as expected, fixing any bugs or errors
along the way.
Once the code is written, a programmer continuously monitors the software for
errors or bugs and resolves these issues through debugging.
Maintenance involves updating the software over time to add new features or
improve performance.
These skills ensure that a programmer can write efficient, functional, and maintainable code.
1. Python Datatypes
Datatypes in Python define the kind of value a variable can hold. Python provides several
built-in datatypes to handle different types of data.
a. Numeric Datatypes
Example:
python
age = 25
print(type(age)) # Output: <class 'int'>
Example:
python
price = 99.99
print(type(price)) # Output: <class 'float'>
Complex ( complex ): Used to represent complex numbers with a real and imaginary
part.
Example:
python
num = 3 + 5j
print(type(num)) # Output: <class 'complex'>
Example:
python
is_valid = True
print(type(is_valid)) # Output: <class 'bool'>
A string is a sequence of characters enclosed within single ( ' ) or double ( " ) quotes.
Example:
python
name = "John"
print(type(name)) # Output: <class 'str'>
d. Sequence Datatypes
List ( list ): A mutable collection of items, which can store different datatypes.
Example:
python
Example:
python
python
numbers = range(5)
print(list(numbers)) # Output: [0, 1, 2, 3, 4]
e. Mapping Datatype
Dictionary ( dict ): Stores key-value pairs. Keys must be unique and immutable.
Example:
python
f. Set Datatypes
Example:
python
unique_numbers = {1, 2, 3, 3, 4}
print(unique_numbers) # Output: {1, 2, 3, 4}
Example:
python
g. NoneType
python
result = None
print(type(result)) # Output: <class 'NoneType'>
2. Python Expressions
a. Arithmetic Expressions
Operators:
Addition: +
Subtraction: -
Multiplication: *
Division: /
Exponentiation: **
Example:
python
x = 10
y = 3
result = x + y # Addition
print(result) # Output: 13
Operators:
Equal to: ==
Example:
python
a = 5
b = 10
print(a > b) # Output: False
print(a == b) # Output: False
c. Logical Expressions
Operators:
Example:
python
a = True
b = False
print(a and b) # Output: False
print(a or b) # Output: True
print(not a) # Output: False
d. Assignment Expressions
Operators:
= : Basic assignment.
:= : Walrus operator that assigns and returns a value at the same time.
Example:
python
x = 5 # Basic assignment
print(x) # Output: 5
# Walrus operator
print(x := 10) # Output: 10
print(x) # Output: 10
e. Membership Expressions
Used to check if a value is a member of a sequence (like a list, tuple, set, etc.).
Operators:
not in : Returns True if the value does not exist in the sequence.
Example:
python
f. Identity Expressions
Used to check if two objects are the same (i.e., have the same memory location).
Operators:
Example:
python
x = [1, 2, 3]
y = [1, 2, 3]
print(x is y) # Output: False (different memory locations)
print(x == y) # Output: True (same values)
In summary, datatypes define the type of values in Python, and expressions allow you to
perform operations on those values, resulting in a new value.
Here’s a detailed explanation of the print() , input() , and string replication in Python,
with examples for each:
1. print() Function
The print() function in Python is used to display output to the console.
Syntax:
python
sep: Specifies how multiple objects should be separated (default is a space ' ' ).
end: Specifies what to print at the end of the output (default is a newline \n ).
Example:
2. input() Function
The input() function allows the user to take input from the keyboard. It always returns the
input as a string, even if the input looks like a number.
Syntax:
python
input([prompt])
prompt: Optional. A string that is displayed as a prompt to the user before input is
taken.
Example:
python
3. String Replication
String replication is a simple way to repeat a string multiple times in Python. This is done
using the * operator with a string.
Syntax:
python
string * n
Example:
python
# Replicating a string
greeting = "Hello! " * 3
print(greeting)
# Output: Hello! Hello! Hello!
Summary
print() displays output to the console.
Each of these features is simple and powerful, making them fundamental to interacting with
Python.
What are Variables and how they are declared and defined.
Explain Values, Types, Variables and Keywords with
example code in detail
Declaration: In Python, variables are implicitly declared when you assign a value to
them.
Example:
python
x is an integer variable.
a. Values:
A value is the actual data stored in a variable. Values can be of different types such as
numbers, strings, lists, etc.
Example:
python
Here, 25 and "Alice" are the values stored in the variables num and name .
b. Types:
Each value in Python has a specific type. The type defines what kind of value a variable holds
and what operations can be performed on it. Common types in Python include:
Example:
python
x = 10 # x is of type int
y = 3.14 # y is of type float
name = "Alice" # name is of type str
is_valid = True # is_valid is of type bool
You can check the type of a variable using the type() function:
python
c. Variables:
As mentioned earlier, a variable is a name that refers to a memory location where a value is
stored. Variables can be assigned different types of values, and they can change over time
(i.e., they are mutable).
Example:
python
Variable names are case-sensitive ( age and Age are different variables).
Valid Examples:
python
python
d. Keywords:
Keywords are reserved words in Python that have special meanings and cannot be used as
variable names. Python has a set of built-in keywords that are used to define the syntax and
structure of the language.
You can get the list of all keywords in Python using the keyword module:
python
import keyword
print(keyword.kwlist)
python
Example of trying to use a keyword as a variable name (this will cause an error):
python
Variables: Names that refer to a memory location where values are stored (e.g., age ,
name ).
Keywords: Reserved words in Python that cannot be used as variable names (e.g., if ,
else , for ).
By understanding how these components work together, you can write clear, efficient Python
code.
1. Conditional Statements
Conditional statements allow the program to execute a certain block of code based on
whether a condition is True or False .
a. if Statement:
Syntax:
if condition:
# Code to execute if the condition is True
Example:
python
age = 18
if age >= 18:
print("You are an adult.")
# Output: You are an adult.
b. if-else Statement:
If the condition in the if statement is False , the else block will be executed.
Syntax:
python
if condition:
# Code to execute if the condition is True
else:
# Code to execute if the condition is False
Example:
python
age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
# Output: You are a minor.
c. if-elif-else Statement:
This structure is used when you have multiple conditions to check. The elif allows you to
add additional conditions between the if and else statements.
python
if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition1 is False and condition2 is True
else:
# Code to execute if all conditions are False
Example:
python
marks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 80:
print("Grade: B")
else:
print("Grade: C")
# Output: Grade: B
2. Looping Statements
Loops allow you to repeat a block of code multiple times based on a condition.
a. while Loop:
The while loop executes the block of code as long as the condition is True . It checks the
condition before every iteration.
Syntax:
python
while condition:
# Code to be executed while the condition is True
python
count = 0
while count < 5:
print("Count is:", count)
count += 1
# Output:
# Count is: 0
# Count is: 1
# Count is: 2
# Count is: 3
# Count is: 4
b. for Loop:
The for loop iterates over a sequence (like a list, tuple, string, or range) and executes the
block of code for each element in the sequence.
Syntax:
python
Example:
python
python
a. break Statement:
The break statement is used to exit a loop prematurely, even if the loop condition is still
True .
Syntax:
python
break
Example:
python
for i in range(10):
if i == 5:
break
print(i)
# Output:
# 0
# 1
# 2
# 3
# 4
The continue statement is used to skip the current iteration of the loop and move to the
next iteration.
Syntax:
python
continue
Example:
python
for i in range(5):
if i == 2:
continue
print(i)
# Output:
# 0
# 1
# 3
# 4
c. pass Statement:
The pass statement is a placeholder for future code. It doesn’t execute anything, but is used
when syntactically a statement is required.
Syntax:
python
pass
Example:
python
for i in range(5):
if i == 2:
pass # Placeholder, no action is taken
else:
Summary
Conditional Statements:
if-else : Executes one block of code if the condition is True , otherwise executes
another block.
Looping Statements:
Control Statements:
These flow control statements allow you to control the execution flow of your Python
programs effectively.