Python Coding
Python Coding
In Simpler terms,
Python is a widely used, high-level programming
language that is popular for its simplicity and
versatility. Its easy-to-learn syntax and broad range of
applications, including web development, data
analysis, artificial intelligence, and more, make it a
valuable tool for developers of all skill levels. Whether
you're just starting out in tech or you're a seasoned
programmer, Python is definitely a language worth
learning.
Keywords
Operators
Arithmetic operators: These operators are used to
perform arithmetic operations, such as addition (+),
subtraction (-), multiplication (*), division (/), and
modulo (remainder) (%).
Comparison operators: These operators are used to
compare values and return a boolean value (True or
False). Examples include "==" (equal to), "!=" (not
equal to), ">" (greater than), "<" (less than), ">="
(greater than or equal to), and "<=" (less than or
equal to).
Comments
Single-line comments: Single-line comments begin with
the "#" symbol and are used to provide a brief
explanation or annotation for a single line of code.
Anything after the "#" symbol is ignored by the Python
interpreter.
"""
This is a multi-line comment.
It can span multiple lines of code.
This comment is enclosed in triple quotes.
"""
Docstrings: Docstrings are special comments that
provide documentation for a module, function, class, or
method. They are also enclosed in triple quotes and
can span multiple lines of code.
def my_function():
"""
This function does something.
It takes no arguments and returns nothing.
"""
print("Hello, world!")
Numbers in Python
Integers: Integers are whole numbers (positive,
negative, or zero) that do not have a fractional
component. They are represented in Python using
the "int" data type.
Example: x = 5
Example: y = 3.14
Complex numbers: Complex numbers are numbers
with a real and imaginary component. They are
represented in Python using the "complex" data
type.
Example: z = 2 + 3j
Example: a = True
Data Types
Variables
Strings
String is a sequence of characters. Strings are a built-in
data type and are defined by enclosing characters in
quotes. Python supports single quotes ('...') and double
quotes ("...") to define a string.
Tuples
Tuple is a collection of ordered, immutable elements
enclosed in parentheses. Once a tuple is created, it
cannot be modified. Tuples are often used to represent
fixed collections of related values.
Dictionaries
Dictionary is a collection of key-value pairs, enclosed in
curly braces {}. Dictionaries are unordered and mutable,
which means that you can add, remove, and modify
elements in a dictionary after it is created.
You can add and remove elements from a set using the
add(), remove(), and discard() methods.
x = 10
if x > 0:
print("x is positive")
x=0
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
while condition:
# code to be executed as long as the condition is
true
Example:
i=1
while i < 5:
print(i)
i += 1
result = add_numbers(2, 3)
print(result) # Output: 5
def get_name_and_age():
name = 'John'
age = 30
return name, age
result = get_name_and_age()
print(result) # Output: ('John', 30)
x = 10 # global namespace
def my_function():
y = 20 # local namespace
print(x) # Accesses x from global namespace
print(y)
my_function()
Recursion in Python
Recursion is a programming technique where a function
calls itself to solve a problem.
Examples
Factorial Calculation: The factorial of a number is the
product of all positive integers up to that number. For
example, the factorial of 5 (written as 5!) is 5 x 4 x 3 x 2 x
1 = 120. We can calculate the factorial using recursion as
follows:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
Object-Oriented Programming
def say_hello(self):
print("Hello, my name is " + self.name + " and I
am " + str(self.age) + " years old.")
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
print("I am an animal.")
class Dog(Animal):
def speak(self):
print("I am a dog.")
In this example, we have two classes, Animal and Dog.
Dog is a subclass of Animal, meaning it inherits all the
properties and methods of Animal. Dog also defines its
own speak method that overrides the speak method of
Animal.
We can create an object of the Dog class as follows:
dog1 = Dog("Buddy", 5)
class Dog(Animal):
def speak(self):
print("I am a dog.")
class Cat(Animal):
def speak(self):
print("I am a cat.")
def get_balance(self):
return self._balance
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
In this example, we have an abstract Shape class that
defines an abstract method area. The Shape class cannot
be instantiated, but it can be used as a base class for
other classes that implement the area method.
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
class Beverage:
def get_cost(self):
pass
class Coffee(Beverage):
def get_cost(self):
return 1.0
class Decorator(Beverage):
def __init__(self, beverage):
self.beverage = beverage
def get_cost(self):
return self.beverage.get_cost()
class Sugar(Decorator):
def get_cost(self):
return self.beverage.get_cost() + 0.5
class Milk(Decorator):
def get_cost(self):
return self.beverage.get_cost() + 1.0
class Subject:
def __init__(self):
self._observers = []
class Observer:
def __init__(self, subject):
self.subject = subject
self.subject.attach(self)
def update(self):
pass
Writing to a file:
This will open the file "example.txt" in read mode, read the
contents of the file, and print them to the console. To write
to a file, you can use the open() function to open the file in
write mode, and then use the write() method to write to the
file. Here's an example:
file = open("example.txt", "w")
file.write("Hello, world!")
file.close()
import socket
client_socket = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
client_socket.connect(("localhost", 5000))
client_socket.send("Hello, server!")
Using the print() function: You can use the print() function
to format output by using placeholders and format
specifiers. Placeholders are used to indicate where values
should be inserted into the string, and format specifiers
control how those values are displayed. Here's an example:
name = "John"
age = 30
print("My name is {} and I am {} years
old.".format(name, age))
This will print the message "My name is John and I am 30
years old."
This will print the message "The price is $9.99", with the
price formatted to two decimal places.
try:
num = int(input("Enter a number: "))
result = 10 / num
print(result)
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Please enter a valid integer.")
In this example, the try block prompts the user for a number,
divides 10 by that number, and prints the result. If the user
enters 0 or a non-integer value, the corresponding except
block will be executed instead.
try:
result = divide(10, 0)
print(result)
except ZeroDivisionError as e:
print(e)