Basics of Python - Volume 1-3

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 30

Pytho

n
Table of Contents
1. Comments......................................................................................................................1
2. Variables........................................................................................................................2
1. Variable assignment:..................................................................................................2
2. Variable naming:........................................................................................................2
3. Variable types:............................................................................................................2
4. Variable reassignment:...............................................................................................3
5. Variable operations:...................................................................................................3
3. Data Types.....................................................................................................................4
1. Numeric data types.....................................................................................................5
2. Text data type.............................................................................................................6
3. Sequence data types....................................................................................................7
4. Mapping data type......................................................................................................8
5. Set Data Types............................................................................................................8
4. Operators......................................................................................................................13
1. Arithmetic Operators:...............................................................................................13
2. Assignment Operators:.............................................................................................13
3. Comparison Operators:.............................................................................................14
4. Logical Operators:....................................................................................................14
5. Bitwise Operators:....................................................................................................14
6. Membership Operators:............................................................................................15
7. Identity Operators:....................................................................................................15
5. Control Flow................................................................................................................16
1. Conditional Statements:...........................................................................................16
2. Loop Statements:......................................................................................................16
6. Functions......................................................................................................................18
Defining a Function:.......................................................................................................18
1. Calling a Function:...................................................................................................18
2. Parameters and Arguments:.....................................................................................18
7. Modules........................................................................................................................20
1. Creating a Module:...................................................................................................20
2. Importing a Module:.................................................................................................20
3. Renaming a Module:................................................................................................20

1|Page
4. Importing Specific Functions:..................................................................................21
8. Input/Output.................................................................................................................22
1. Printing to the Console:............................................................................................22
2. Reading Input from the User:...................................................................................22
3. Writing to a File:......................................................................................................22
4. Reading from a File:.................................................................................................22
5. Working with Binary Data:......................................................................................23

2|Page
I. Overview
Overview of the basic syntax of Python
1. Comments: In Python, you can add comments to your code by starting the line
with a # symbol. Comments are ignored by the interpreter and can be used to add
notes to your code.

2. Variables: In Python, you can assign values to variables using the = symbol.
Variable names can include letters, numbers, and underscores, but cannot start
with a number. For example, x = 5 assigns the value 5 to the variable x.

3. Data Types: Python has several built-in data types, including integers, floating-
point numbers, strings, and booleans. You can use the type() function to determine
the type of a variable.

4. Operators: Python supports a variety of operators, including arithmetic operators


(+, -, *, /), comparison operators (>, <, ==), and logical operators (and, or, not).

5. Control Flow: Python uses if/else statements for conditional logic and for/while
loops for iterative logic. Indentation is important in Python, as it is used to define
the scope of code blocks.

6. Functions: In Python, you can define your own functions using the def keyword.
Functions can take parameters and return values.

7. Modules: Python has a large standard library of modules that provide additional
functionality. You can import modules using the import keyword.

8. Input/Output: You can read and write data to files using the open() function and
file objects. You can also read user input using the input() function and print
output using the print() function.
These are just a few of the basic elements of Python syntax. For more information, you
can consult the official Python documentation or a beginner's guide to Python
programming.

1. Comments

In Python, you can write comments to add notes and explanations to your code. There
are two ways to write comments in Python:
1. Single-line comments start with the # character and continue until the end of the
line. For example:

2. Multi-line comments use triple quotes (''' or """) to enclose the comment. This can
be used to write longer comments that span multiple lines. For example:

Remember that comments are an important tool for making your code more readable and
understandable. Try to write clear and concise comments that explain the purpose of your
code and how it works.

1|Page
2. Variables

In Python, you can use variables to store and manipulate data. Here are some basic
examples of how to use variables in Python:

1. Variable assignment:
To assign a value to a variable, use the = operator. For example:

2. Variable naming:
Variable names can contain letters, numbers, and underscores, but cannot start
with a number. Variable names are case-sensitive, so x and X are different variables.
For example:

3. Variable types:
Python is a dynamically typed language, which means that variables can hold
values of any type. The type of a variable is determined at runtime based on the value that
it holds. For example:

2|Page
4. Variable reassignment:
You can change the value of a variable by assigning a new value to it. For
example:

5. Variable operations:
You can perform operations on variables, such as arithmetic operations or string
concatenation. For example:

These are just a few examples of how to use variables in Python. Variables are a
fundamental concept in programming, and understanding how to use them effectively is
essential for writing effective code.

3|Page
4|Page
3. Data Types

In Python, data types are used to define the type of data that a variable can hold.
Python has several built-in data types, which include:
1. Numeric data types:

1. int (integer): represents whole numbers, such as 1, 2, 3, etc.


2. float: represents floating-point numbers, such as 2.5, 3.14, etc.
3. complex: represents complex numbers, such as 1 + 2j.

2. Text data type:

1. str (string): represents a sequence of characters, such as "hello world".


2. Boolean data type:
3. bool (Boolean): represents the values True and False, which are used for logical
operations.

3. Sequence data types:

1. list: represents an ordered collection of items, such as [1, 2, 3].


2. tuple: represents an ordered collection of items, which is similar to a list, but
cannot be modified once it is created.
3. range: represents a range of numbers, which is commonly used for looping.

4. Mapping data type:

1. dict (dictionary): represents a collection of key-value pairs, such as {"name":


"John", "age": 30}.

5. Set data type:

1. set: represents an unordered collection of unique items, such as {1, 2, 3}.

6. Binary data types:

1. bytes: represents a sequence of bytes, such as b"hello".


2. bytearray: represents a mutable sequence of bytes, which can be modified after
creation.
3. memoryview: represents a memory view of a byte array, which can be used for
low-level operations on data.
These data types are used to define variables, which are used to store data in Python
programs. Understanding data types is important for writing effective code, as it helps

5|Page
you choose the appropriate type of data to use for a given situation, and ensures that your
code behaves as expected.

1. Numeric data types

Numeric data types are used to represent numerical values in Python. There are three
built-in numeric data types in Python: int, float, and complex.
1. int (integer): represents whole numbers, such as 1, 2, 3, etc. Integers in Python
can be positive, negative, or zero. Integers have no decimal point, and can be
of arbitrary length, limited only by the amount of memory available.

2. float: represents floating-point numbers, such as 2.5, 3.14, etc. Floating-point


numbers have a decimal point, and can be represented in scientific notation
using an "e" to indicate the power of 10.

3. Complex: represents complex numbers, such as 1 + 2j. Complex numbers


consist of a real part and an imaginary part, separated by a "+" or "-" sign. The
"j" suffix indicates the imaginary part.

6|Page
Numeric data types in Python support a wide range of mathematical operations,
such as addition, subtraction, multiplication, and division. In addition, the math module
provides a range of functions for performing more complex mathematical operations,
such as trigonometric functions, logarithms, and exponential functions.

It is important to understand how numeric data types behave in Python, especially


when performing operations that involve both integers and floating-point numbers, as this
can sometimes lead to unexpected results due to the way that floating-point numbers are
represented internally.

2. Text data type

Text data is represented using the string (str) data type. Strings are used to represent a
sequence of characters, which can include letters, numbers, punctuation marks, and
whitespace.
Strings can be defined using either single quotes ('...') or double quotes ("..."), as long
as the quotes are balanced. For example:

Strings can also be defined using triple quotes ('''...''') or ("""...""") to span multiple
lines. For example:

7|Page
In addition, the backslash () character can be used to escape special characters,
such as newlines (\n), tabs (\t), and quotes. For example:

Strings in Python are immutable, which means that once a string is created, it
cannot be modified. However, it is possible to create new strings by concatenating two or
more existing strings using the + operator. For example:

Strings also support a wide range of methods for manipulating and working with
text data. For example, the len() function can be used to determine the length of a string:

Other common string methods include lower(), upper(), strip(), split(), join(), and
many more.
Understanding text data types and string manipulation is essential for working with
text data in Python, as it is a fundamental aspect of most Python programs.

3. Sequence data types

A sequence is a type of data structure that stores a collection of elements in a specific


order. There are three main built-in sequence data types in Python: lists, tuples, and range
objects.

8|Page
Lists: Lists are a collection of items that can be of different data types such as integers,
strings, and even other lists. They are mutable, which means that you can add, remove, or
modify elements within a list. Lists are defined using square brackets, with each element
separated by a comma. For example, my_list = [1, 2, "three", [4, 5]].
Tuples: Tuples are similar to lists, but they are immutable, which means that once you
create a tuple, you cannot change its elements. Tuples are defined using parentheses, with
each element separated by a comma. For example, my_tuple = (1, 2, "three", [4, 5]).
Range objects: Range objects represent a sequence of numbers and are commonly used
for looping a specific number of times. Range objects are immutable, and they are
defined using the range() function. For example, my_range = range(0, 10, 2) represents
the numbers 0, 2, 4, 6, and 8.
In addition to the built-in sequence data types, Python also includes several sequence-
related functions such as len() to get the length of a sequence, min() and max() to get the
minimum and maximum values within a sequence, and sorted() to sort a sequence.
Overall, sequence data types are versatile and widely used in Python for storing and
manipulating collections of elements.

4. Mapping data type

A mapping is a data type that represents a collection of key-value pairs. The built-in
mapping data type in Python is the dictionary.
A dictionary is an unordered collection of key-value pairs, where each key is unique
and is used to access the corresponding value. The keys must be immutable objects, such
as strings or tuples, while the values can be of any data type.
Dictionaries are defined using curly braces, with each key-value pair separated by a
colon, and each pair separated by a comma. For example, my_dict = {"apple": 1,
"banana": 2, "cherry": 3} defines a dictionary with three key-value pairs.
You can access the value of a specific key in a dictionary using the key in square
brackets, like this: my_dict["apple"]. You can also add, remove, or modify key-value
pairs in a dictionary.
In addition to dictionaries, Python includes several mapping-related functions such as
len() to get the number of key-value pairs in a dictionary, keys() and values() to get the
keys or values of a dictionary, and items() to get a list of key-value tuples.
Overall, mapping data types in Python are useful for representing collections of
related data with unique keys. Dictionaries are widely used in Python for tasks such as
counting occurrences of elements, implementing associative arrays, and representing
JSON data.

9|Page
5. Set Data Types

A set is an unordered collection of unique elements. This means that each element
appears in the set only once, regardless of how many times it was added to the set. Let's
take a look at some examples to understand how sets work in Python.

1. Creating a Set:
Sets can be created using the set() constructor or by enclosing a comma-separated list
of values within curly braces. Here are some examples:

2. Adding Elements to a Set:


We can add elements to a set using the add() method. Here is an example:

3. Removing Elements from a Set:


We can remove an element from a set using the remove() method. Here is an example:

10 | P a g e
4. Set Operations:
Python sets support a variety of operations such as union, intersection, difference, and
symmetric difference. Here are some examples:

As you can see, sets can be very useful for removing duplicates from a list,
checking for membership of an element, and performing mathematical set operations.
However, it is important to note that set elements must be hashable, which means they
should be immutable and have a unique hash value. Common examples of hashable types
include integers, floats, strings, and tuples.
Binary data types are used to represent and manipulate binary data, which is data that
is represented in the binary (base-2) numeral system. Binary data can be represented

11 | P a g e
using bytes and bytearrays, which are both built-in data types in Python. Here's a detailed
view of these binary data types in Python:
5. Bytes:
A byte is a sequence of 8 bits, and in Python, it is represented by the bytes data type.
Bytes are immutable, which means that their values cannot be changed once they are
created. Bytes can be created using the bytes() constructor, and they can also be created
using a binary literal with the prefix "b". Here are some examples:

6. Converting Binary Data:


Binary data can be converted to other data types using various methods. For example,
bytes and bytearrays can be converted to strings using the decode() method, and strings
can be converted to bytes or bytearrays using the encode() method. Here are some
examples:

12 | P a g e
7. Byte array:
A byte array is a mutable sequence of bytes, which means that its values can be
changed after it is created. Byte arrays are created using the bytearray() constructor, and
they can also be created using a binary literal with the prefix "b". Here are some
examples:

13 | P a g e
Binary data types are commonly used in applications that deal with low-level
system operations, such as network protocols and file I/O. They are also useful for
working with binary data formats, such as JPEG and PNG images, and binary file
formats, such as WAV and MP3 audio files.

14 | P a g e
4. Operators

Operators are special symbols or keywords that are used to perform various
operations on variables, values, and expressions. Here is a detailed view of the different
types of operators in Python:

1. Arithmetic Operators:
Arithmetic operators are used to perform mathematical operations on numerical
values. The basic arithmetic operators in Python are:

2. Assignment Operators:
Assignment operators are used to assign values to variables. The basic assignment
operator in Python is:

In addition to the basic assignment operator, there are also compound assignment
operators, which combine an arithmetic operator and an assignment operator. For
example:

15 | P a g e
3. Comparison Operators:
Comparison operators are used to compare two values and return a Boolean value
(True or False). The basic comparison operators in Python are:

4. Logical Operators:
Logical operators are used to combine Boolean values and return a Boolean value.
The basic logical operators in Python are:

5. Bitwise Operators:
Bitwise operators are used to perform bitwise operations on integer values. The
basic bitwise operators in Python are:

16 | P a g e
6. Membership Operators:
Membership operators are used to test if a value is a member of a sequence (such
as a list or a string). The basic membership operators in Python are:

7. Identity Operators:
Identity operators are used to compare the memory addresses of two objects. The
basic identity operators in Python are:

Operators are an essential part of Python programming, and understanding how to


use them is necessary for creating effective and efficient code.

17 | P a g e
5. Control Flow

Control flow statements are used to control the order in which statements are executed
in a program. There are three main types of control flow statements in Python:
conditional statements, loop statements, and function calls.

1. Conditional Statements:
Conditional statements are used to execute a block of code only if a certain condition
is met. In Python, conditional statements are created using the "if", "elif", and "else"
keywords. Here's an example:

In this example, the "if" statement checks whether "x" is greater than 0. If the
condition is true, the code inside the "if" block will be executed. If the condition is false,
the "elif" statement checks whether "x" is less than 0. If the condition is true, the code
inside the "elif" block will be executed. If both the "if" and "elif" conditions are false, the
code inside the "else" block will be executed.

2. Loop Statements:
Loop statements are used to execute a block of code repeatedly. In Python, there are
two main types of loop statements: "for" loops and "while" loops. Here's an example of a
"for" loop:

In this example, the "for" loop iterates over the "fruits" list and prints each item.
And here's an example of a "while" loop:

18 | P a g e
In this example, the "while" loop continues to execute the code inside the loop as long
as the condition (i.e., "i" is less than or equal to 5) is true.
Control flow statements are an essential part of Python programming, and they
allow you to create programs that can make decisions, repeat actions, and execute code
that has been defined elsewhere. By using conditional statements, loop statements, and
function calls, you can create complex programs that can perform a wide variety of tasks.

19 | P a g e
6. Functions

Functions in Python are a way of grouping a set of related instructions into a


single unit that can be easily reused and called from different parts of a program. In this
way, functions can make code more modular, easier to read, and less repetitive. Here are
some key aspects of functions in Python:

Defining a Function:
Functions are defined using the "def" keyword, followed by the name of the
function and a set of parentheses that can optionally contain one or more parameters. The
body of the function is defined using indentation (typically four spaces). Here's an
example:

In this example, we define a function called "greet" that takes one parameter, "name",
and prints a greeting message to the console.

1. Calling a Function:
Once a function is defined, it can be called from other parts of the program using its
name followed by parentheses. Here's an example:

In this example, we call the "greet" function with the argument "Alice".

2. Parameters and Arguments:


Functions can take one or more parameters, which are like variables that the function
can use inside its body. When a function is called, arguments are passed to the function in
the same order as the parameters. Here's an example:

20 | P a g e
In this example, we define a function called "add numbers" that takes two
parameters, "x" and "y", and returns their sum. We then call the function with the
arguments 2 and 3, and assign the result to a variable called "result". Finally, we print the
value of "result" to the console.

In this example, we define a function called "square" that takes one parameter,
"x", and returns its square. We then call the function with the argument 3, assign the
result to a variable called "result", and print the value of "result" to the console.
Functions are an essential part of Python programming, and they allow you to
create reusable blocks of code that can be easily called from different parts of a program.
By using parameters, arguments, and return values, you can create functions that are
flexible, powerful, and easy to use.

21 | P a g e
7. Modules
A module is a file containing Python definitions, statements, and functions. Modules
allow you to organize your code into logical groups and avoid name collisions with other
code. Modules can be imported into other Python programs, making it easy to reuse code
and share it with others. Here are some key aspects of modules in Python:

1. Creating a Module:
A Python module is simply a file with a ".py" extension that contains Python code.
For example, you could create a module called "my_module.py" with the following code:

In this example, we define a function called "greet" that takes one parameter, "name",
and prints a greeting message to the console.

2. Importing a Module:
Once a module is created, it can be imported into other Python programs using the
"import" keyword. For example, to use the "greet" function from our "my_module.py"
module, we could write:

In this example, we import the "my_module" module and call its "greet" function with
the argument "Alice".

3. Renaming a Module:
You can also rename a module when you import it, using the "as" keyword. For
example:

In this example, we import the "my_module" module and rename it to "mm". We then
call its "greet" function with the argument "Bob".

22 | P a g e
4. Importing Specific Functions:
If you only need to use one or two functions from a module, you can import them
directly using the "from" keyword. For example:

In this example, we import the "greet" function from the "my_module" module
and call it directly with the argument "Charlie".
Modules are an important part of Python programming, allowing you to organize
your code into logical groups and reuse it in different parts of your program. By
importing modules and using their functions, you can save time, avoid repetition, and
create more powerful and flexible programs.

23 | P a g e
8. Input/Output

Input and output (I/O) operations are essential for interacting with the user, reading
and writing files, and communicating with other programs. Here are some key aspects of
input and output in Python:

1. Printing to the Console:


To print a message or variable to the console, you can use the "print" function. For
example:

In this example, we print the message "Hello, world!" to the console.

2. Reading Input from the User:


To read input from the user, you can use the "input" function. For example:

In this example, we prompt the user for their name using the "input" function, and
then print a greeting message using their input.

3. Writing to a File:
To write data to a file, you can use the "open" function to create a file object, and
then use the "write" method to write data to the file. For example:

In this example, we create a file object for a new file called "my_file.txt" using the
"open" function, write the text "This is some text." to the file using the "write" method,
and then close the file using the "close" method.

4. Reading from a File:


To read data from a file, you can use the "open" function to create a file object,
and then use the "read" method to read data from the file. For example:

24 | P a g e
In this example, we create a file object for an existing file called "my_file.txt"
using the "open" function, read the text from the file using the "read" method, store the
text in the "text" variable, close the file using the "close" method, and then print the text
to the console.

5. Working with Binary Data:


In addition to reading and writing text data, Python can also read and write binary
data, such as images, audio files, and other binary file formats. To read or write binary
data, you can use the "rb" and "wb" modes with the "open" function, respectively. For
example:

In this example, we open an existing JPEG image file called "my_image.jpg" in


binary mode, read the binary data from the file using the "read" method, store the data in
the "image_data" variable, close the file using the "close" method, and then create a new
JPEG image file called "new_image.jpg" in binary mode, write the binary data to the file
using the "write" method, and then close the file using the "close" method.
Input and output operations are a fundamental part of programming in Python, and
mastering these operations is essential for creating effective and interactive programs that
can read and write data to a variety of sources. By using functions like "print" and "input"
to interact with the user, and functions like "open" and "read" to read and write files, you
can create more powerful and flexible programs that can handle a wide variety of tasks.

25 | P a g e
Thank you

26 | P a g e

You might also like