Introduction

Python is a high-level, It’s a very popular programming language. The Python programming language (later Python 3) is used for web development machine learning applications and all cutting edge technologies in the software industry. The Python programming language is very suitable for beginners as well as experienced programmers using other programming languages ​​such as C and Java.

Features

Pyhon is a popular programming language. It offers a wide range of features that make it suitable for various operations. also are some notable features of Python

  1. Easy to Learn and Readability.
  2. Interpreted Language.
  3. Cross-Platform Compatibility.
  4. Large Standard Library.
  5. Third-Party Libraries and Frameworks.
  6. Object-Oriented Programming (OOP) Support.
  7. Dynamic Typing and Automatic Memory Management.
  8. Integration Capabilities.
  9. Extensibility and Customizability.
  10. Community and Support.

Setup Path

To set up a path on your computer, follow these steps:

  1. Determine the directory or folder you want to add to the path. For Ex let’s say you want to add the directory “C:\Programs” to the path.
  2. Open the System Properties dialog on your computer. You can usually access it by right-clicking on the “This PC” icon on your desktop, selecting “Properties,” and then clicking on “Advanced system settings” or “Advanced” tab.
  3. In the System Properties dialog, click on the” terrain Variables” button. This will open the terrain Variables dialog.
  4. In the terrain Variables dialog, under the” System variables” section, scroll down and find the” Path” variable. elect it and click on the” Edit” button.
  5. In the Edit Environment Variable dialog, click on the “New” button to add a new entry to the path.
  6. Enter the path of the directory you want to add (e.g., “C:\Programs”) and click “OK.”
  7. Click “OK” on all the open dialogs to save the changes and close them.
  8. Restart any open command prompt or terminal windows for the changes to take effect.

Basic Syntax

Python syntax defines a set of rules used to create Python statements when writing Python programs. The syntax of the Python programming language is in many ways similar to that of the Perl, C, and Java programming languages. However, there are certain differences between the languages.

Variable

Variables and data types in Python are, as their names suggest, different values. In a programming language, a variable is a location in memory that stores a value. Stored values ​​may change according to future specifications.

Data Types Operator

Python data types are used to define variable types. Specifies the type of data to store in the variable. Data stored in memory can be of different types. For example, a person’s age is stored as a numeric value and their address is stored as an alphanumeric value.

Conditional Statements

you can use tentative statements to control the inflow of your program grounded on certain conditions. The three main types of tentative statements are if, if- differently, and nested if- additional. Let me explain each of them with exemplifications.

If statement

The if statement is used to execute a block of law only if a particular condition is true. Then is the syntax

if condition:
    # Code block to execute if the condition is true

If-else statement

The if-else statement allows you to execute one block of code if a condition is true, and another block of code if the condition is false. Here’s the syntax:

if condition:
    # Code block to execute if the condition is true
else:
    # Code block to execute if the condition is false

Nested if-else statement

You can nest if-else statements within each other to handle multiple conditions. Here’s the syntax:

if condition1:
    # Code block to execute if condition1 is true
    if condition2:
        # Code block to execute if both condition1 and condition2 are true
    else:
        # Code block to execute if condition1 is true but condition2 is false
else:
    # Code block to execute if condition1 is false

Looping

you can use various looping constructs and control statements to control the flow of your program. Let’s go through each of them:

For Loop

The for loop is used to iterate over a sequence (such as a list, tuple, or string) or other iterable objects. It executes a block of code for each element in the sequence. Here’s the syntax:

for item in sequence:
    # Code block

While Loop

The while circle constantly executes a block of law as long as the specified condition is true. It’s used when you do not know the exact number of duplications demanded. Then is the syntax

while condition:
    # Code block

Nested Loops

You can have loops within loops, known as nested loops, to perform more complex iterations. Each iteration of the outer loop triggers a complete iteration of the inner loop. Here’s an example:

for i in range(3):
    for j in range(2):
        print(i, j)

Control Statements

Control statements help alter the flow of a loop or conditionally execute code. The main control statements are break, continue, and pass.

Break

The break statement is used to exit the loop prematurely, bypassing the remaining iterations. It is typically used when a certain condition is met. Example:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    if fruit == "banana":
        break
    print(fruit)

Continue

The continue statement is used to skip the current replication of a circle and move to the coming replication. It’s useful when you want to skip certain rudiments or conditions. illustration

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    if fruit == "banana":
        continue
    print(fruit)

Pass:

The pass statement is a placeholder that does nothing. It’s used when you need a statement syntactically but don’t want to perform any action. illustration

for i in range(5):
    pass  # Placeholder, no action performed

String Manipulation

String manipulation is the most important technique when parsing text data. Python has many built-in methods for working with strings. In this article, we’ll look at the most commonly used Python string methods for string manipulation.

Accessing Strings

strings are sequences of characters and can be accessed using indexing and slicing. Here are some ways to access and manipulate strings in Python:

  1. Accessing individual characters.
  2. Slicing a string.
  3. Negative indexing.
  4. Modifying a string (strings are immutable, so you need to create a new string).
  5. String length.
  6. Iterating over a string.

Basic Operations

This section explains how to use basic operators in Python.

  • Arithmetic Operators
  • Comparison (Relational) Operators
  • Assignment Operators
  • Logical Operators
  • Bitwise Operators
  • Membership Operators
  • Identity Operators

String Slices

String slicing is the process of removing parts of a string. The characters in the extracted part can be contiguous or at regular intervals in the original string.

Function

  1. A function is a block of code that is also referred to by name. (independent)
  2. Functions can have different parameters or none at all. When data (parameters) are passed, they are passed explicitly.
  3. It may or may not return data.
  4. Functions do not deal with the concept of a class and its instances.

Method

  1. Methods are called by name, but are associated with (subordinate to) objects.
  2. Method definitions always include “i” as the first parameter.
  3. Methods are implicitly passed to the object on which they are called.
  4. It may or may not return data.
  5. Methods can operate on data (instance variables) contained in that class.

Lists

Lists in Python are used to store sequences of data of various types. A list can be defined as a collection of values ​​or elements of various types. Python lists are mutable. That is, even after the list is formed, its elements can be changed. Items in the list are separated by commas (,) and enclosed in square brackets [ ] .

Accessing list

In Python, you can accessing individual rudiments in a list using their indicators. The indicators start from 0 for the first element and proliferation by 1 for each posterior element.

Operations

You can perform various operations on lists, such as adding elements, removing elements, or modifying existing elements

Tuple

A tuple is an ordered collection of immutable, heterogeneous data. Heterogeneity means that any type of variable can be stored in a tuple.

Tuples have the following characteristics:

  1. Ordered : Tuples are part of a sequence data type, so they preserve the order in which the data is inserted. It keeps the index value for each element.
  2. Unchangeable : Tuples are immutable. That is, once a tuple is created, elements cannot be added or removed.
  3. Heterogeneous: Tuples are sequences of data of different types (e.g. integers, floating point, lists, strings, etc.) that can be accessed through indexing and slicing.
  4. Contain duplicates: A tuple can contain duplicates. That is, you can have elements with the same value.

Introducation

A tuple is an ordered collection of rudiments in Python. It’s a data structure that’s analogous to a list, but with one crucial difference tuples are inflexible, which means their values can not be modified once they’re created.

Accessing tuples

Tuples are inflexible, and generally, they contain a sequence of miscellaneous rudiments that are penetrated via discharging or indexing( or indeed by trait in the case of named tuples). Lists are variable, and their rudiments are generally homogeneous and are penetrated by repeating over the list.

Operations

Operations refer to the actions performed on data, such as arithmetic, assignment, comparison, and logical operations. Examples include addition (+), subtraction (-), multiplication (*), division (/), assignment (=), equality (==), greater than (>), less than (<), and logical AND (and), OR (or), and NOT (not). Operations allow you to manipulate and transform data within your code.

Working

Working in Python generally refers to the process of executing a program or script. When you run a Python program, the interpreter executes the code line by line, following the specified logic and performing the defined operations. The working of a Python program involves interpreting and executing statements, processing data, and producing the desired output.

Functions

Functions are applicable blocks of law that perform a specific task. They synopsize a set of instructions and can be called from different corridor of a program. Functions help in organizing law, promoting law exercise, and perfecting maintainability. In Python, you can define functions using the def keyword followed by the function name, parameters( if any), and a block of law. Functions can have return values and can be invoked by using the function name followed by hiatuses.

Methods

Methods are functions that are associated with objects. They are called on specific instances of a class and can modify the object’s state or provide some functionality related to that object. Methods are defined within a class and typically have access to the object’s attributes and other methods.

Dictionaries

Dictionaries, also known as associative arrays or hash maps, are a fundamental data structure in Python. Used to store key-value pairs where each key is unique and used to access the associated value. This section covers the basics of dictionaries, including how to create, access, and manage dictionaries.

Accessing Dictionary Values

Of course, the elements of the dictionary must be accessible in some way. If you don’t get it by index, how do you get it?

dict() Function

Python dict() Function is used to create a Python dictionary, a collection of key-value pairs.

Example

dict(One = “1”, Two = “2”)

Output:

{‘One’: ‘1’, ‘Two’: ‘2’}

Defining a Function

you can define your own functions using the def keyword followed by the function name and a brace of hiatuses. You can also specify parameters inside the hiatuses if the function needs to accept input values.

Calling a Function

Once you have defined a function, you can call it by using its name followed by parentheses. If the function expects any arguments, you should provide them within the parentheses. Here’s an example:

# Function definition
def greet(name):
    print("Hello, " + name + "!")

# Function call
greet("Alice")

Types of Functions

there are several types of functions

  1. Built-in Functions.
  2. User-defined Functions.
  3. Recursive Functions.
  4. Higher-order Functions.

Function Arguments

Functions in Python can accept arguments, which are input values handed to the function. There are different types of arguments:

  1. Required Arguments.
  2. Keyword Arguments.
  3. Default Arguments.
  4. Variable-length Arguments.

Anonymous function it means that the function has no name. As you already know, def keyword is used to define normal functions and lambda keyword is used to create anonymous functions.

#Python code to illustrate the cube of a number

#using lambda function

def cube(x): return xxx

cube_v2 = lambda x : xxx

print(cube(7))
print(cube_v2(7))

Output

343
343

Global variables

Global variables are scoped to the entire program, so they can be used anywhere in the program. Let’s understand global variables through a very simple example.

Example

z = 25
def func():
   global z
   print(z)
   z=20
func()
print(z)

Output

25
20

Local Variables

Local variables can only be accessed within their scope (like func() above). As in the program below, we have two local variables x and y.

Example

def sum(x,y):
sum = x + y
return sum
print(sum(5, 10))

Output

The variables x and y are only operated/used inside the sum() function and do not exist outside the function. Therefore, attempting to use a local variable outside its scope may result in a NameError. So obviously the line below doesn’t work.

File “main.py”, line 2
sum = x + y
^
IndentationError: expected an indented block

Module

A module is a file containing executable Python or C code, containing a number of Python statements and expressions. You can use predefined variables, functions, and classes with modules. This saves a lot of development time and allows code reuse. Most modules are concise, clear, and designed to solve a developer’s specific problem.

Importing module

To use functions in a module, you must import the module with an import statement.

An import statement consists of the import keyword followed by the module name.

In a Python file, this is declared at the top of the code, on a shebang line, or below a normal comment.

So, import the random module from the Python program file my_rand_int.py to generate random numbers as follows:

Math Module

Sometimes when working on some financial or scientific projects, the project needs to implement mathematical calculations. Python provides a math module for performing these calculations. The Math module provides functionality for both basic operations such as addition (), subtraction (-), multiplication (*), and division (/), as well as advanced operations such as trigonometric, logarithmic, and exponential functions.

Random module

The random module is a built-in Python module used to generate random numbers. These are pseudorandom numbers, so they are not truly random numbers. This module can be used to perform random operations such as generating random numbers, printing random values ​​to lists or strings, etc.

Packages

We usually organize our files in different folders and subfolders based on some criteria to make managing them easy and efficient. For example, you can store all your games in the games folder and also divide them into subcategories based on game genre and so on. Python packages follow the same analogy.

Composition

Composition is one of the important concepts in object-oriented programming (OOP). Compositions basically allow programs to create complex types of objects by combining objects of different types. Composition represents a “relational” type, or in OOP concepts, composition can be called “relational”. In other words, a composite class represented by a program can contain objects from other components of the class, and this type of relational model is called relational.

Input/Output

Printing on screen

To publish affair on the screen, you can use the print() function. It accepts one or further arguments and displays them on the press.

Illustration

print("Hello, World!")

Reading data from the keyboard

Like other programming languages, Python provides two built-in functions.

  1. raw_input (hint)
  2. input (hint)

raw_input() – reads input or commands and returns a string. That is, even if the user enters an integer value, it is still treated as a string. This built-in function is only available in Python 2.x, not Python 3.x.

input() – Reads input and returns a Python type such as list, tuple, int, etc. That is, if the user enters an integer, an integer is returned, and if the user enters a string, a string is returned.

Opening and Closing a File

When dealing with files, there are two types of files: text files and binary files. You can open a file in python using the open function.

open() function:

This function takes two arguments. The first is the file name with full path and the second is the access mode. This function returns a file object.

Syntax:

open(filename, mode)

close() function:

This function takes no arguments and the close() function can be called directly with the file object. You can call it multiple times, but a “ValueError” exception will be raised if you operate on a closed file.

Syntax:

file.close()

Reading and Writing Files

File objects provide a set of accessor methods to make our lives easier. Let’s look at how to read and write files using the read() and write() methods.

The write() Method

The write() method writes all lines to an open file. It’s important to note that Python strings can contain binary data as well as text.

The write() method does not append a newline character (‘\n’) to the end of the string.

Syntax

fileObject.write(string)

The read() Method

The read() method reads one line from an open file. It’s important to note that Python strings can contain binary data. In addition to text data

Syntax

fileObject.read([count])