You are on page 1of 77

.

Python Programming

MODULE 1
What are the needs of any programming language?
Programming languages are essential tools in the field of computer science and
software development. They serve various needs and purposes, contributing to the
creation, maintenance, and execution of software applications. Here are some key
needs and purposes of programming languages:
Communication with Computers:
Instruction Set: Programming languages provide a way for humans to
communicate instructions to computers. They define a set of rules and syntax
that computers can understand and execute.
Abstraction:
Higher-Level Abstraction: Programming languages allow developers to
work at higher levels of abstraction, hiding complex details and providing
simpler interfaces. This abstraction helps in managing complexity and
building more sophisticated software.
Efficiency and Optimization:
Low-Level Control: Some programming languages (like C and C++)
provide low-level control over hardware, enabling programmers to optimize
code for performance and resource utilization.
Portability:
Cross-Platform Development: Programming languages facilitate the
development of cross-platform applications. Code written in a high-level
language can be executed on different operating systems with minimal or no
modification.
Productivity:
Rapid Development: High-level programming languages often provide
features and libraries that accelerate development, making it easier to write
and maintain code.
Problem Solving:
Algorithm Implementation: Programming languages help in expressing
algorithms and solving complex problems. They enable developers to
translate problem-solving logic into executable code.
Maintainability:
Code Readability: Programming languages with clear syntax and
conventions contribute to code readability, making it easier for developers to
understand, modify, and maintain code.
Scalability:
Support for Large Systems: Programming languages offer features that
support the development of large and scalable software systems, such as
modularization, encapsulation, and object-oriented programming.
History of Python

Python is a widely used general-purpose, high-level programming language. It was


initially designed by Guido van Rossum in 1991 and developed by Python
Software Foundation. It was mainly developed for emphasis on code readability, and
its syntax allows programmers to express concepts in fewer lines of code.

• A high-level language is any programming language that enables development of


a program in a much more user-friendly programming context and is generally
independent of the computer's hardware architecture.

• Python has become one of the most popular programming languages globally.

• It is widely used in various domains, including web development, data science,


machine learning, artificial intelligence, and more.

• Python's extensive standard library and a vibrant community contribute to its


widespread adoption.
History of Python
Here's a brief history of Python:
• Origins (Late 1980s):
 Guido van Rossum, a Dutch programmer, started working on Python in
December 1989.
 The project was initiated as a Christmas hobby project, inspired by the ABC
language, which Guido had worked on at Centrum Wiskunde & Informatica
(CWI) in the Netherlands.
• Python 0.9.0 (February 1991):
 The first official version, Python 0.9.0, was released in February 1991.
 It included exception handling, functions, and modules, which are
fundamental features of the language.

• Python 1.0 (January 1994):


 Python 1.0 was released with new features like lambda, map, filter, and
reduce.
 The language began to gain popularity and saw an increase in community
involvement.
History of Python
• Python 2.0 (October 2000):
 Python 2.0 introduced list comprehensions, garbage collection, and Unicode
support.
 This version continued to enhance the language's features and performance.
• Python 3.0 (December 2008):
 Python 3.0, also known as Python 3000 or "Py3k," was a major overhaul of
the language.
 It introduced backward-incompatible changes to improve code clarity and
eliminate redundancy.
 Key changes included the introduction of the "print" function, removal of
the "raw_input" function, and improvements to Unicode support.
• Subsequent Releases:
 Python has continued to evolve with regular releases, introducing new
features, optimizations, and bug fixes.
 Major version releases (e.g., 3.1, 3.2, etc.) brought incremental
improvements to Python 3.
Python timeline
Some Frequently asked Question

Q1. Who developed Python programming language?

Q2. What are the uses of Python?


Some Frequently asked Question
Q1. Who developed Python programming language?

Answer: Python programming language was developed by Guido van Rossum. He


started working on Python in December 1989, and the first official release, Python
0.9.0, came out in February 1991. Guido van Rossum continued to lead the
development of Python for many years, earning the title "Benevolent Dictator For
Life" (BDFL) within the Python community. While he stepped down from the role of
BDFL in 2018, his contributions to Python remain significant.
Some Frequently asked Question
Q2. What are the uses of Python?
Python is a versatile programming language with a wide range of applications. Some
of the key uses of Python include:
1. Web Development:
• Frameworks like Django and Flask enable developers to build robust and
scalable web applications.
2. Data Science and Machine Learning:
• Python is widely used in data science and machine learning. Libraries like
NumPy, Pandas, SciPy, and scikit-learn provide powerful tools for data
analysis, manipulation, and machine learning.
3. Artificial Intelligence (AI) and Natural Language Processing (NLP):
• Python is employed in AI and NLP applications, with libraries like
TensorFlow and PyTorch being popular for deep learning tasks.
4. Automation and Scripting:
Python's simplicity and readability make it an excellent choice for writing scripts
and automating repetitive tasks.
Some Frequently asked Question
5. Scientific Computing:
• Scientists use Python for scientific computing, simulations, and research.
Libraries like Matplotlib and SciPy are essential for scientific applications.
6. Game Development:
• Python is used in game development, and libraries like Pygame provide tools
for creating 2D games.
7. Desktop GUI Applications:
• Python can be used to create desktop applications with graphical user
interfaces (GUIs) using frameworks like Tkinter, PyQt, or Kivy.
8. Network Servers and Protocols:
• Python is utilized for developing network servers and handling network
protocols due to its ease of use and extensive libraries.
9. Databases:
• Python can connect to various databases, and libraries like SQLAlchemy
simplify database interactions.
Some Frequently asked Question
10. Cybersecurity:
• Python is used in cybersecurity for tasks such as penetration testing, script
automation, and developing security tools.
11. Education:
• Python is widely used in educational settings for teaching programming due
to its readability and beginner-friendly syntax.
12. Financial and Trading Applications:
• Python is utilized in the finance industry for tasks like algorithmic trading,
data analysis, and risk management.
13. DevOps and System Administration:
• Python scripts are commonly used for tasks related to system administration,
automation, and configuration management in the field of DevOps.
Install Python

To install Python, we can follow these general steps. The specific details may vary
based on your operating system. Python 3 is the recommended version, and Python 2
has reached its end of life. We can check the official Python website for the latest
information.
Installing Python on Windows:
1. Visit the Python Official Website:
• Go to Python's official website
2. Download Python:
• Click on the "Downloads" tab.
• Download the latest version of Python 3 for Windows.
3. Run the Installer:
• Double-click on the downloaded installer (.exe file).
• Check the box that says "Add Python to PATH" during installation.
4. Complete Installation:
• Follow the on-screen instructions to complete the installation.
Install Python
Installing Python on macOS:
1. Visit the Python Official Website:
• Go to Python's official website
2. Download Python:
• Click on the "Downloads" tab.
• Download the latest version of Python 3 for macOS.
3. Run the Installer:
• Double-click on the downloaded installer (.pkg file).
4. Complete Installation:
• Follow the on-screen instructions to complete the installation.
Installing Python on Linux:
1. Check if Python is Installed:
• Many Linux distributions come with Python pre-installed. Open a terminal
and type python3 or python to check if it's already installed.
Install Python
2. Install Python:
• Use the package manager for your distribution to install Python.
• For Debian/Ubuntu-based systems, we can use:

sudo apt-get update


sudo apt-get install python3

3. Verify Installation:
• Open a terminal and type python3 --version or python --version to verify the
installation.
Verifying the Installation:
1. Open a Terminal or Command Prompt:
Open a terminal on Linux or macOS, or Command Prompt on Windows.
2. Check Python Version:
Type the following command:
python3 --version # On Linux or macOS
python --version # On Windows (This should display the installed Python version.)
Install Python
3. Check Pip (Python Package Installer):
Type the following command:
pip3 --version # On Linux or macOS
pip --version # On Windows
Python 2 vs Python 3
Python 2 and Python 3 are two major versions of the Python programming language,
with Python 3 being the latest and recommended version. Here are some key
differences between Python 2 and Python 3:
1. Print Statement:
Python 2: Uses the print statement without parentheses.
print "Hello, World!"
Python 3: Uses the print() function with parentheses.
print("Hello, World!")
2. Division:
Python 2: The division of two integers results in integer division by default.
result = 5 / 2 # Results in 2 (integer division)
Python 3: Division of integers results in float division by default.
result = 5 / 2 # Results in 2.5
3. Unicode Support:
Python 2: String handling is not Unicode by default. Unicode strings are defined
with a u prefix.
Python 3: Strings are Unicode by default, and the u prefix is not used.
Python 2 vs Python 3
4. Range and xrange:
Python 2: Has both range() and xrange(). xrange() returns an iterator and is
more memory-efficient for large ranges.
Python 3: Only has range(), which behaves like xrange() from Python 2.
5. Iterating through Dictionaries:
Python 2: Uses .iteritems() for iterating through dictionary items.
Python 3: Uses .items() for the same purpose.
6. Error Handling:
Python 2: Uses except Exception, e: syntax for catching exceptions.
Python 3: Uses except Exception as e: syntax.
7. Input Function:
Python 2: Uses raw_input() for user input and input() for evaluating user input
as a Python expression.
Python 3: Uses input() for user input, and raw_input() is no longer available.
Python 2 vs Python 3
8. Byte and String Handling:
Python 2: Implicitly treats a string as bytes. To represent Unicode, a u prefix is
used.
Python 3: Explicitly differentiates between bytes (bytes) and Unicode strings
(str). Unicode is the default string type.
9. Library Compatibility:
Python 2: Some older libraries may not be compatible with Python 3 without
modification.
Python 3: Has improved support for modern libraries and is the recommended
version for new projects.
10. Development and Support:
Python 2: Reached its end of life on January 1, 2020, and no longer receives
official support or updates.
Python 3: Actively developed, and new features and improvements are regularly
introduced.
Some Frequently asked Question
Q1. How is the print statement different in Python 2 and Python 3?
Q2. Describe the default behavior of division for integers in Python 2 and Python 3.
Q3. How does Python 2 handle Unicode strings, and how is it different from Python
3?
Q4. What does it mean for Python 2 to have reached its end of life, and how does this
affect developers?
Q5. Which version of Python is currently recommended for new projects, and why?
Some Frequently asked Question
Q1. How is the print statement different in Python 2 and Python 3?
Answer: In Python 2, the print statement is used without parentheses:
print "Hello, World!“
In Python 3, print is a function, and it requires parentheses:
print("Hello, World!")
Q2. Describe the default behavior of division for integers in Python 2 and Python 3.
Answer:
In Python 2, when we perform division between two integers using the / operator, the
result is an integer division, and any fractional part is truncated. This means that if we
divide two integers, the result will be an integer:
result = 5 / 2 # In Python 2, this results in 2
To perform true division (including the fractional part), you can use the / operator
with at least one of the operands being a float:
result = 5.0 / 2 # In Python 2, this results in 2.5
Python 3:
In Python 3, the default behavior of the / operator between two integers is true
division. The result includes the fractional part, and the result is a float:
Some Frequently asked Question
result = 5 / 2 # In Python 3, this results in 2.5
If we want to perform integer division (floor division) in Python 3, you can use the //
operator:
result = 5 // 2 # In Python 3, this results in 2

Q3. How does Python 2 handle Unicode strings, and how is it different from Python
3?
The handling of Unicode strings is one of the significant differences between Python
2 and Python 3. Here's a brief overview of how each version deals with Unicode
strings:
Python 2:
In Python 2, there are two types of strings:
ASCII Strings (str):
The default string type (str) in Python 2 represents ASCII text and is a sequence
of bytes. Each character is encoded using the ASCII encoding.
Unicode Strings (unicode):
To work with Unicode characters, Python 2 has a distinct Unicode string type
(unicode). Unicode strings use a wider range of characters and support different
character encodings.
Some Frequently asked Question
When working with Unicode characters in Python 2, you explicitly use the unicode
type:
unicode_string = u"This is a Unicode string."
Python 3:
In Python 3, the handling of strings was unified, and there is only one string type:
Unicode Strings (str):
The default string type in Python 3 (str) represents Unicode text. Unicode strings
use the UTF-8 encoding by default, allowing for a more consistent and
internationalized approach to text handling.

In Python 3, no longer need a separate unicode type. The default str type is Unicode:
unicode_string = "This is a Unicode string."
Key Differences:
Syntax:
In Python 2, we need to use the u prefix for Unicode literals: u"Unicode string".
In Python 3, Unicode strings are the default, and the u prefix is not used.
Some Frequently asked Question
Unicode Support:
In Python 2, Unicode support is not as pervasive, and mixing ASCII and
Unicode strings in operations may lead to unexpected results.
In Python 3, Unicode support is integrated more consistently, providing a more
straightforward and predictable behavior when working with text in different
languages.
Print Statement:
The print statement in Python 2 behaves differently when printing Unicode and
ASCII strings. In Python 3, the print() function is used uniformly.
String Literals:
Python 2 treats string literals as ASCII by default. Unicode literals require the u
prefix.
Python 3 treats string literals as Unicode by default, and you need a prefix (e.g.,
b for bytes literals) to create non-Unicode strings.
Some Frequently asked Question
The end of life (EOL) for Python 2 means that the Python Software Foundation
(PSF) has officially stopped providing updates, including bug fixes and security
patches, for Python 2. The specific date for Python 2's end of life was January 1,
2020.
Here's how this impacts developers:
1. No Official Support:
• Python 2 no longer receives official support from the PSF. This means that
any vulnerabilities or bugs discovered in Python 2 will not be addressed by
the core development team.
2. Security Risks:
• With the end of life, using Python 2 in production systems poses a security
risk. Any security vulnerabilities discovered after the end of life will not be
patched, potentially leaving systems vulnerable to attacks.
3. Compatibility Challenges:
• Newer libraries and frameworks are designed to work with Python 3. As a
result, developers using Python 2 may face compatibility issues when trying
to use or integrate newer tools and libraries.
Some Frequently asked Question
4. Community and Third-Party Support:
The broader Python community, including third-party library maintainers, is
focusing on Python 3. Developers using Python 2 may find decreasing
community and third-party support for their projects.
5. Adoption of Modern Features:
Python 3 introduces numerous improvements, features, and optimizations over
Python 2. Developers are encouraged to upgrade to Python 3 to take advantage
of these enhancements and ensure compatibility with the evolving Python
ecosystem.
6. Industry Best Practices:
Following industry best practices and maintaining up-to-date software is crucial
for the long-term stability and security of projects. Using an outdated and
unsupported version of Python is contrary to these best practices.
7. Migration Efforts:
Developers relying on Python 2 need to invest in migrating their codebase to
Python 3. This may involve updating syntax, addressing library compatibility
issues, and making other necessary adjustments to ensure a smooth transition.
Some Frequently asked Question
8. Long-Term Viability:
Choosing to stick with Python 2 might lead to challenges in maintaining and
evolving projects. Adopting Python 3 ensures long-term viability and aligns with
the direction of the Python community.
Different Environment Variables
Here we will explore some of the most prominent environment variables in Python.
PYTHONPATH
The PYTHONPATH environment variable plays a crucial role in facilitating the
importation of user-defined modules directly into Python programs. It governs the default
search path for Python modules and is responsible for extending the sys.path directory list
with directories specified in its string value. By setting PYTHONPATH, users can include
directories that contain modules not yet made installable, enabling seamless importation
and use within Python programs.
PYTHONHOME
This variable defines the default location for Python's standard libraries. By default,
Python looks for its libraries in the directories specified by the variables
prefix/lib/pythonversion and exec_prefix/lib/pythonversion. In this context, prefix and
exec_prefix represent installation-dependent directories, both of which default to
/usr/local.

PYTHONSTARTUP
the Python interpreter in Unix searches for a readable file named .pythonrc.py and
executes the commands within it. The path to this file is stored in the PYTHONSTARTUP
variable. These files play a role in configuring the PYTHONPATH .
Different Environment Variables
PYTHONINSPECT
If the PYTHONINSPECT variable is an empty string, it compels python to enter into
an interactive python-mode and ignore the PYTHONSTARTUP files. It can
also make changes to the Python code and force it to enter the inspect mode on
program termination. It is equivalent to using the -i command-line option.
PYTHONCASEOK
This environment variable is used to ignore all import statements while calling the
Python interpreter. In a Windows machine, it is used to find the first case-
insensitive match in an import statement.
PYTHONVERBOSE
If this variable is set to an empty string, it prints a message every time a module is
initialized showing the location of the file or the module from where it has been
loaded. It also generates information on module cleanup at the termination of the
python program.

The above variables are the primary environment variables that are frequently
used.
Executing Python from the Command Line
Executing Python from the command line is a fundamental way to run Python scripts
and interact with the Python interpreter. Here's an overview of the basic steps:
Running Python Scripts:
1. Create a Python Script:
Write your Python code in a plain text file with a .py extension. For example,
myscript.py.
2. Open a Terminal or Command Prompt:
Navigate to the directory where your Python script is located.
3. Run the Script:
Use the python command followed by the script's filename to execute it. python
myscript.py
EXAMPLE
Let’s make a python file that simply computes the sum of 5 and 10 and returns the
result and save it as gfg.py file. This would look somewhat like the below:
Executing Python from the Command Line

Now execute the file by using the below command:


python gfg.py
Executing Python from the Command Line

This will result in the following:


Editing Python Files
Editing Python files involves modifying the content of your Python script using a text
editor or integrated development environment (IDE). Here are the basic steps for
editing Python files:
Using a Text Editor:
Open the Text Editor:
Open your preferred text editor. Common choices include:
On Unix/Linux: nano, vim, emacs, gedit
On Windows: Notepad, Visual Studio Code, Atom, Sublime Text
Navigate to the Python File:
Use the text editor's file menu or command-line options to open the Python file
you want to edit.
Make Changes:
Edit the content of the file as needed. Add, modify, or remove Python code.
Save the File:
Save the changes to the file using the text editor's save option (usually Ctrl + S
or Command + S).
Editing Python Files
Using an Integrated Development Environment (IDE):
Open the IDE:
Open your chosen IDE. Popular Python IDEs include:
PyCharm, Visual Studio Code, Atom, Sublime Text, Spyder, IDLE, etc.
Open the Python File:
Use the IDE's file navigation or project explorer to open the Python file you
want to edit.
Make Changes:
Edit the code in the editor window. IDEs often provide features like syntax
highlighting, autocompletion, and code analysis.
Save the File:
Save your changes using the IDE's save option or shortcut.
Python Syntax
Python syntax refers to the set of rules that defines the combinations of symbols that
are considered to be correctly structured programs in the Python language. These
rules make sure that programs written in Python should be structured and formatted,
ensuring that the Python interpreter can understand and execute them correctly.
Python syntax is designed to be clear and readable. Here are some basic elements of
Python syntax:
1. Comments:
Comments in Python start with the # symbol and are used to add explanatory notes to
the code. Comments are ignored by the interpreter.
Python code
# This is a single-line comment
""" This is a multi-line comment """
2. Indentation:
Python uses indentation to define blocks of code. Indentation is crucial for the
structure of the code and replaces curly braces used in many other programming
languages.
Python Syntax

Python code
if x > 0: print("x is positive")
else: print("x is non-positive")
3. Variables and Data Types:
Variables are created by assigning a value to a name. Python is dynamically typed, so
you don't need to declare the type explicitly.
Python code
name = "John"
age = 25
height = 1.75
is_student = True
4. Print Statement:
The print() function is used to output information.
Python code
print("Hello, World!")
Python Syntax
5. Strings:
Strings are sequences of characters, and you can use single or double quotes to define
them.
Python code
message = 'This is a string.'
6. Numbers:
Python supports integers and floating-point numbers.
Python code
integer_number = 42
float_number = 3.14
7. Lists:
Lists are ordered and mutable collections.
Python code
my_list = [1, 2, 3, "apple", "orange"]
8. Tuples:
Tuples are similar to lists, but they are immutable.
Python Syntax
Python code
my_tuple = (1, 2, "banana")
9. Dictionaries:
Dictionaries are key-value pairs.
Python code
my_dict = {"name": "Alice", "age": 30, "city": "Wonderland"}
10. Control Flow:
if-else:
Python code
if condition: # code to execute if condition is True
else: # code to execute if condition is False
for loop:
Python code
for item in iterable:
# code to execute for each item in the iterable
Python Syntax
while loop:
Python code
while condition:
# code to execute while the condition is True
11. Functions:
Functions are defined using the def keyword.
Python code
def greet(name): return "Hello, " + name + "!"
12. Input:
Taking input from the user can be done with the input() function.
Python code
user_input = input("Enter your name: ")
13. Importing Modules:
Python code
import math
result = math.sqrt(25)
String Values in python
In Python, strings are sequences of characters, and they are used to represent text
data. Strings are one of the fundamental data types in Python, and they are
immutable, meaning their values cannot be changed once they are created. Here are
some key aspects of working with string values in Python:

1. Creating Strings:
Strings can be created using single quotes (') or double quotes ("). Both are
equivalent, and we can choose the style that you find more readable.
Python code
single_quoted_string = 'Hello, World!‘
double_quoted_string = "Hello, World!"

2. Multiline Strings:
For multiline strings, you can use triple single quotes (''') or triple double quotes
(""").
Python code
multiline_string = '''This is a multiline string.'''
3. String Concatenation:
String Values in python
Python code
greeting = "Hello" name = "Alice" full_greeting = greeting + ", " + name + "!"
4. String Repetition:
You can repeat a string using the * operator.
Python code
repeated_string = "abc" * 3
# Results in "abcabcabc"
5. Accessing Characters:
Individual characters in a string can be accessed using indexing. Indexing starts from
0.
Python code
my_string = "Python" first_char = my_string[0]
# 'P'
6. String Slicing:
You can extract a substring using slicing.
String Values in python
Python code
my_string = "Python" substring = my_string[1:4]
# 'yth'
7. String Methods:
Strings have a variety of built-in methods for manipulation and analysis.
Python code
my_string = "Hello, World!"
uppercase_string = my_string.upper()
lowercase_string = my_string.lower()

8. String Formatting:

You can format strings using the % operator or the format() method.
Python code
name = "Alice" age = 25 formatted_string = "My name is %s and I am %d years
old." % (name, age)
String Values in python
Python code
name = "Bob" age = 30 formatted_string = "My name is {} and I am {} years
old.".format(name, age)
9. Escape Characters:
Escape characters are used to include special characters within a string.
Python code
escaped_string = "This is a line break.\nThis is a tab character:\tSee?"
10. String Length:
We can find the length of a string using the len() function.
Python code
my_string = "Hello, World!" length = len(my_string)
# 13

These are some fundamental aspects of working with string values in Python. Strings
are versatile and play a crucial role in various programming tasks, from simple text
manipulation to complex data processing.
String Values in python
Advantages of String in Python:
• Strings are used at a larger scale i.e. for a wide areas of operations such as storing
and manipulating text data, representing names, addresses, and other types of data
that can be represented as text.
• Python has a rich set of string methods that allow you to manipulate and work
with strings in a variety of ways. These methods make it easy to perform common
tasks such as converting strings to uppercase or lowercase, replacing substrings,
and splitting strings into lists.
• Strings are immutable, meaning that once you have created a string, you cannot
change it. This can be beneficial in certain situations because it means that you
can be confident that the value of a string will not change unexpectedly.
• Python has built-in support for strings, which means that you do not need to
import any additional libraries or modules to work with strings. This makes it
easy to get started with strings and reduces the complexity of your code.
• Python has a concise syntax for creating and manipulating strings, which makes it
easy to write and read code that works with strings.
String Values in python
Drawbacks of String in Python:
• When we are dealing with large text data, strings can be inefficient. For instance,
if you need to perform a large number of operations on a string, such as replacing
substrings or splitting the string into multiple substrings, it can be slow and
consume a lot resources.
• Strings can be difficult to work with when you need to represent complex data
structures, such as lists or dictionaries. In these cases, it may be more efficient to
use a different data type, such as a list or a dictionary, to represent the data.
String Operators
String operators in Python allow you to perform various operations on strings. Here
are some commonly used string operators:
1. Concatenation Operator +:
The + operator is used to concatenate (join) two strings.
Python code
string1 = "Hello" string2 = " World"
result = string1 + string2
# "Hello World"
2. Repetition Operator *:
The * operator is used to repeat a string a specified number of times.
Python code
string1 = "abc"
result = string * 3
# "abcabcabc"
3. Membership Operators in and not in:
These operators check if a substring is present in a string.
Python code
String Operators
my_string = "Hello, World!"
# Check if "Hello" is present is_hello_present = "Hello" in my_string # True
# Check if "Python" is not present is_python_not_present = "Python" not in
my_string # True
4. Comparison Operators (==, !=, <, >, <=, >=):
You can use comparison operators to compare strings.
Python code
string1 = "apple" string2 = "orange“
# Equality check is_equal = string1 == string2 # False
# Inequality check is_not_equal = string1 != string2 # True
# Lexicographical comparison is_greater_than = string1 > string2 # False
5. Slice Operator [:]:
The slice operator allows you to extract a portion of a string.
Python code
my_string = "Python Programming"
# Extract characters from index 7 to 16 substring = my_string[7:17]
# "Programming"
String Operators
6. Identity Operators (is, is not):
These operators test if two strings are the same object in memory.
Python code
string1 = "Hello" string2 = "Hello"
# Check if they refer to the same object are_same_objects = string1 is string2 # True
7. Unary Operator + and -:
Unary + and - operators can be used to represent the sign of a string (useful for
numbers represented as strings).
Python code
numeric_string = "-42" # Convert to an integer numeric_value = int(numeric_string)

# -42

These operators provide ways to manipulate and analyze strings in Python.


Understanding and using them effectively can enhance your ability to work with text
data in your programs.
Numeric Data Types Conversions
Numeric data type conversions in Python involve converting values between
different types, such as converting an integer to a floating-point number or a string.
Python provides built-in functions for these conversions. Here are some common
numeric data type conversions:
1. Integer to Float:
We can convert an integer to a floating-point number using the float() function.
Code:
integer_value = 42
float_value = float(integer_value)
print(float_value)
2. Float to Integer:
Converting a floating-point number to an integer truncates the decimal part. We can
use the int() function.
Code:
float_value = 3.14
integer_value = int(float_value)
print(integer_value)
Numeric Data Types Conversions
3. String to Integer or Float:
We can convert a string containing a numeric value to an integer or a float using int()
or float().
Code:
numeric_string = "123"
integer_value = int(numeric_string)
float_value = float(numeric_string)
print(integer_value, float_value)
4. Integer or Float to String:
Converting numeric values to strings is common, and you can use the str() function
for this purpose.
Code:
integer_value = 42
float_value = 3.14
integer_as_string = str(integer_value)
float_as_string = str(float_value)
print(integer_as_string, float_as_string)
Numeric Data Types Conversions
5. Rounding Floating-Point Numbers:
If we need to round a floating-point number to a certain number of decimal places,
you can use the round() function.
Code:
pi = 3.14159265359
rounded_pi = round(pi, 2)
# Rounds to 2 decimal places print(rounded_pi)
6. Complex Numbers:
Python supports complex numbers, and you can create them using the complex()
function.
Code:
real_part = 2
imaginary_part = 3
complex_number = complex(real_part, imaginary_part)
print(complex_number)
Numeric Data Types Conversions
7. Binary, Octal, and Hexadecimal Conversions:
We can convert numbers to binary, octal, and hexadecimal representations using
built-in functions like bin(), oct(), and hex().
Code:
decimal_number = 42
binary_representation = bin(decimal_number)
octal_representation = oct(decimal_number)
hexadecimal_representation = hex(decimal_number)
print(binary_representation, octal_representation, hexadecimal_representation)
8. Handling Errors in Conversions:
When converting a string to a numeric type, it's essential to handle cases where the
string might not represent a valid number. Using try and except blocks can help in
this regard.
Numeric Data Types Conversions
Code:
numeric_string = "abc"
try:
integer_value = int(numeric_string)
print(integer_value)
except
ValueError: print("Invalid numeric string")

These conversions are commonly used in Python programs, especially when dealing
with user input or when manipulating numeric data in various ways. Understanding
how to convert between different numeric types is a fundamental aspect of working
with Python.
Simple Input and Output
In Python, simple input and output operations are achieved using the input() function
for user input and the print() function for displaying output. Here's a basic example:
Input:
The input() function is used to take user input. It reads a line of text from the user and
returns it as a string.
Code:
# Taking user input name = input("Enter your name: ")
age = input("Enter your age: ")
# Note: input() returns a string, so if age is expected to be an integer, conversion is
needed age = int(age)
print("Hello, {}! You are {} years old.".format(name, age))
Output:
The print() function is used to display output. You can print variables, strings, and the
results of expressions.
Code:
# Displaying output
print("This is a simple Python program.")
print("The sum of 5 and 3 is:", 5 + 3) # Using formatted strings (Python 3.6 and later)
Simple Input and Output
fruit = "apple"
quantity = 3
print(f"I have {quantity} {fruit}s.")
In the above example, the print() function is used to display text and the result of the
addition operation. Additionally, a formatted string is used to include variable values
within the output.
Handling User Input as Numbers:
When we use input() to get numeric input, remember that it is returned as a string. If
you need to perform numerical operations with the input, you should convert it to the
appropriate numeric type (e.g., int or float).
Code:
# Taking numeric input
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Performing a calculation
result = num1 + num2 print("The sum of {} and {} is: {}".format(num1, num2,
result))
Language Components
The components of a programming language refer to the fundamental building blocks
that make up the language. These components provide the structure and functionality
necessary for writing and executing computer programs. The key components of a
programming language include:
Syntax:
Syntax defines the set of rules that dictate how programs in a language are
written. It includes the structure, grammar, and punctuation that must be
followed for the code to be valid.
Semantics:
Semantics deals with the meaning of the constructs in a programming language.
It specifies the interpretation of statements and expressions and how they affect
program execution.
Variables:
Variables are used to store and represent data in a program. They have a name, a
type, and a value. Variables allow programs to work with and manipulate data
dynamically.
Language Components
Data Types:
Data types define the nature of data that can be used in a program. Common data
types include integers, floating-point numbers, strings, boolean values, and
more.
Operators:
Operators perform operations on data. Examples include arithmetic operators (+,
-, *, /), comparison operators (==, !=, <, >), and logical operators (and, or, not).
Control Structures:
Control structures dictate the flow of execution in a program. Common control
structures include if statements, loops (for, while), and switch statements.
Functions and Methods:
Functions and methods allow code to be organized into reusable blocks.
Functions typically take inputs (arguments), perform some computation, and
return a result. Methods are functions associated with objects in object-oriented
programming.
Conditional Statements:
Conditional statements, such as if, elif, and else, allow the execution of different
code blocks based on certain conditions.
Language Components
Loops:
Loops (for, while) enable the repetition of code, allowing the execution of a
block of statements multiple times.
Arrays and Collections:
Arrays and collections are used to store multiple values in a single variable.
These include lists, arrays, dictionaries, sets, and other data structures.
Input/Output (I/O):
Input/output operations allow a program to interact with the user or external
systems. This includes reading from and writing to files, printing to the console,
and handling user input.
Exception Handling:
Exception handling mechanisms allow programs to deal with runtime errors
gracefully. This involves catching and handling exceptions to prevent program
crashes.
Comments:
Comments are used to document code for human readers. They are not executed
and are ignored by the interpreter or compiler.
Control Flow structures and Syntax
Control flow structures in programming languages dictate the order in which
statements are executed in a program. They allow you to control the flow of
execution based on conditions, loops, and other control statements. Here are some
common control flow structures and their syntax in Python:
1. Conditional Statements (if, elif, else):
Conditional statements are used to execute different blocks of code based on specific
conditions.
Code:
# if statement
if condition: # code to execute if the condition is True
# if-else statement if condition:
# code to execute if the condition is True
else: # code to execute if the condition is False
# if-elif-else statement if condition1:
# code to execute if condition1 is True
elif condition2: # code to execute if condition2 is
True else: # code to execute if none of the conditions is True
Control Flow structures and Syntax
2. Loops (for, while):
Loops allow you to repeat a block of code multiple times.
For Loop:
Code:
# for loop with a range for variable in range(start, stop, step):
# code to execute in each iteration
# for loop with an iterable (e.g., list) for item in iterable:
# code to execute in each iteration
While Loop:
Code:
# while loop while condition: # code to execute as long as the condition is True

3. Break and Continue:


The break statement is used to exit a loop prematurely.
The continue statement is used to skip the rest of the loop's code and move to the
next iteration.
Control Flow structures and Syntax
Code:
# break statement for variable in iterable: if condition: break #
exit the loop
# continue statement for variable in iterable: if condition: continue
# skip the rest of the loop and move to the next iteration
4. Pass Statement:
The pass statement is a no-operation statement. It is used as a placeholder when
syntactically some code is required, but no action is desired.
Code:
if condition: pass # do nothing else: # code to execute
5. Try-Except Blocks (Exception Handling):
Try-except blocks are used for handling exceptions (runtime errors) gracefully.
Code:
try: # code that might raise an exception except ExceptionType as e:
# code to handle the exception else:
# code to execute if no exception occurred finally:
# code to execute regardless of whether an exception occurred
Control Flow structures and Syntax
These control flow structures are essential for creating flexible and dynamic
programs. They allow you to make decisions, repeat actions, and handle errors,
providing the necessary tools to create sophisticated and responsive applications.
Relational Operators
Relational operators, also known as comparison operators, are used to compare
values in expressions and return Boolean results (True or False). In Python, these
operators are often used in conditions to make decisions based on the relationship
between two values. Here are the commonly used relational operators in Python:
Equal to (==):
Checks if two values are equal.
Code:
x == y
Not equal to (!=):
Checks if two values are not equal.
Code:
x != y
Greater than (>):
Checks if the value on the left is greater than the value on the right.
Code:
x>y
Relational Operators
Less than (<):
Checks if the value on the left is less than the value on the right.
Code:
x<y

Greater than or equal to (>=):

Checks if the value on the left is greater than or equal to the value on the right.
Code:

x >= y
Less than or equal to (<=):
Checks if the value on the left is less than or equal to the value on the right.
Code:
x <= y
Relational Operators
Examples:

# Example values
a = 5 b = 10
# Equal to print(a == b)
# False
# Not equal to print(a != b)
# True
# Greater than print(a > b)
# False
# Less than print(a < b)
# True
# Greater than or equal to print(a >= b)
# False
# Less than or equal to print(a <= b)
# True
These operators are fundamental for making decisions and comparisons within your
Python programs. They are commonly used in conditional statements, loops, and
other control flow structures.
Logical Operators
Logical operators in Python are used to perform logical operations on Boolean
values. These operators allow you to combine or manipulate Boolean values to make
decisions or control the flow of your program. The three main logical operators in
Python are and, or, and not. Here's how they work:
Logical AND (and):
The and operator returns True if both operands are true; otherwise, it returns
False.
Code:
# Example
a = True
b = False
result = a and b
# result is False
Logical OR (or):
The or operator returns True if at least one of the operands is true; it returns
False if both operands are false.
Logical Operators
Code:
# Example
a = True
b = False
result = a or b
# result is True
Logical NOT (not):
The not operator returns the opposite Boolean value of the operand. If the
operand is True, not returns False, and vice versa.
# Example
a = True
result = not a
# result is False
Combining Logical Operators:
Logical operators can be combined to form more complex conditions. Parentheses
can be used to control the order of evaluation.
Logical Operators
Code:
# Example
x = True
y = False
z = True
result = (x and y) or (not z
result is False

In the example above, the expression (x and y) is False, (not z) is False, and False or
False is False.

Logical operators are frequently used in conditions, loops, and other situations where
you need to make decisions based on multiple conditions.
Bitwise Operators
Bitwise operators in Python perform operations at the binary level. They manipulate
individual bits of integers, making it possible to work with the binary representation
of numbers. The bitwise operators include & (AND), | (OR), ^ (XOR), ~ (NOT), <<
(left shift), and >> (right shift).
Here's an overview of bitwise operators in Python:
Bitwise AND (&):
Performs a bitwise AND operation. Sets each bit to 1 if both bits are 1.
x&y
Bitwise OR (|):
Performs a bitwise OR operation. Sets each bit to 1 if at least one of the bits is 1.
x|y
Bitwise XOR (^):
Performs a bitwise XOR (exclusive OR) operation. Sets each bit to 1 if only one
of the bits is 1.
x^y
Bitwise Operators
Bitwise NOT (~):
Inverts the bits of a number. Each 0 becomes 1, and each 1 becomes 0.
~x
Left Shift (<<):
Shifts the bits of a number to the left by a specified number of positions, filling
in with zeros.
x << n
Right Shift (>>):
Shifts the bits of a number to the right by a specified number of positions. The
leftmost bits are filled in based on the sign bit (arithmetic right shift).
x >> n
Bitwise Operators
Examples:
values
x=5
# binary: 0b0101
y=3
# binary: 0b0011
# Bitwise AND result_and = x & y
# binary: 0b0001, decimal: 1
# Bitwise OR result_or = x | y
# binary: 0b0111, decimal: 7
# Bitwise XOR result_xor = x ^ y
# binary: 0b0110, decimal: 6
# Bitwise NOT result_not_x = ~x
# binary: 0b1111...1110, decimal: -6 (due to two's complement representation)
# Left Shift result_left_shift = x << 2
# binary: 0b10100, decimal: 20
# Right Shift result_right_shift = x >> 1 # binary: 0b0010, decimal: 2
bitwise operations are usually performed on integers. Understanding binary representation is useful when
working with bitwise operators. Bitwise operations are commonly used in low-level programming, optimization,
and certain algorithmic applications.
Python for Windows
Python is fully supported on Windows, and you can easily install and use Python on
Windows-based systems. Here are the steps to install Python on Windows:

Installing Python on Windows:

Download Python:
• Visit the official Python website at python.org.
• Click on the "Downloads" tab, and choose the version that corresponds to
your Windows architecture (32-bit or 64-bit). For most modern systems, the
64-bit version is recommended.
Run the Installer:
• Once the installer is downloaded, run the executable file (.exe) to start the
installation process.
Install Python:
• During the installation, make sure to check the box that says "Add Python to
PATH." This allows you to run Python from the command prompt without
specifying the full path.
Python for Windows
Customize Installation (Optional):
• You can customize the installation by clicking on the "Customize installation"
button. This allows you to choose additional features, like adding Python to
the system PATH, installing pip for package management, and associating .py
files with Python.
Complete the Installation:
• Click the "Install Now" button to start the installation. The installer will copy
the necessary files to your system.
Verify the Installation:
• Open a command prompt and type python --version or python -V to verify
that Python is installed. You should see the Python version number.
python --version
Using Python on Windows:
Running Python:
Open a command prompt or PowerShell window and type python to enter the
Python interactive mode.
Python for Windows
python
Running Python Scripts:
• Create a Python script (.py file) using a text editor.
• Open a command prompt and navigate to the directory containing your script.
Run the script using the python command.
python your_script.py
Installing Packages with pip:
• Python comes with pip, a package installer. You can use it to install additional
packages.
pip install package_name
Integrated Development Environments (IDEs):
• Consider using Python IDEs like PyCharm, Visual Studio Code, or IDLE for
a more interactive and feature-rich development experience.
Python for Windows
Virtual Environments:
Use virtual environments to isolate Python projects and manage dependencies.
Example:
# Install a package using pip pip install requests
# Create and activate a virtual environment python -m venv venv venv\Scripts\
activate
# Install packages within the virtual environment pip install package_name

These steps should help you get started with Python on a Windows system. Python
provides a powerful and versatile programming environment on Windows, allowing
you to develop a wide range of applications and scripts.

You might also like