0% found this document useful (0 votes)
5 views19 pages

Introduction To Python

Python is a high-level, interpreted programming language created by Guido van Rossum in 1991, known for its simplicity, readability, and versatility. Key features include dynamic typing, cross-platform compatibility, an extensive standard library, and a strong community. The document also covers Python's history, installation, basic syntax, data types, and how to write and run a simple program.

Uploaded by

Sk Shafi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views19 pages

Introduction To Python

Python is a high-level, interpreted programming language created by Guido van Rossum in 1991, known for its simplicity, readability, and versatility. Key features include dynamic typing, cross-platform compatibility, an extensive standard library, and a strong community. The document also covers Python's history, installation, basic syntax, data types, and how to write and run a simple program.

Uploaded by

Sk Shafi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Introduction to Python

Python is a high-level, interpreted programming language known for its


simplicity, readability, and versatility. It was created by Guido van Rossum
and was first released in 1991. Python's design philosophy emphasizes code
readability and its clean syntax allows programmers to express concepts in
fewer lines of code compared to other programming languages.
Here are some key features and characteristics of Python:
A. Readability: Python code is designed to be easy to read and
understand. It uses indentation (whitespace) to define code blocks,
which enforces a consistent and clear structure.
B. Simplicity: Python's syntax is straightforward and concise, making it an
ideal language for beginners. It avoids unnecessary complexity and
punctuation.
C. Interpreted Language: Python is an interpreted language, which
means that you don't need to compile your code before running it. An
interpreter reads and executes the code line by line.
D. Dynamically Typed: In Python, you don't need to declare the data type
of a variable explicitly. The interpreter determines the type of the
variable based on the assigned value.
E. High-Level Language: Python abstracts low-level details like memory
management, making it easier for programmers to focus on solving
problems rather than dealing with technical details.
F. Cross-Platform: Python is available for various operating systems
(Windows, mac OS, Linux) and can run on different hardware platforms
without modification.
G. Extensive Standard Library: Python comes with a rich standard
library that provides ready-to-use modules and functions for various
tasks, such as file handling, networking, and more.
H. Open Source: Python's source code is open and available to the public,
allowing the community to contribute to its development and
improvement.
I. Versatility: Python can be used for a wide range of applications,
including web development, data analysis, machine learning, scientific
computing, automation, and more.
J. Community and Ecosystem: Python has a large and active community
of developers, which has led to the creation of a vast ecosystem of third-
party libraries and frameworks. These libraries extend Python's
capabilities and enable developers to build complex applications more
easily.
K. Indentation: Unlike many other languages that use braces {} to define
code blocks, Python uses indentation. Proper indentation is crucial for
defining the structure of your code.
L. Philosophy: Python follows a set of guiding principles called the "Zen of
Python," which emphasizes simplicity, readability, and practicality. You
can access these principles by typing import this in the Python
interpreter.
History and Background
Python's history and background trace back to the late 1980s when its
creator, Guido van Rossum, began working on the language. Let's explore the
history and evolution of Python:
Late 1980s: Inception and Early Development
1. Guido van Rossum, a Dutch programmer, started working on Python in
December 1989 during his Christmas holidays at the Centrum Wiskunde
& Informatica (CWI) in the Netherlands.
2. He aimed to create a successor to the ABC language, which was used at
CWI and had features that he found useful.
3. Guido wanted to create a language that was both powerful and readable,
with a syntax that emphasized code clarity.
Early 1990s: Python's First Release
1. Python's first public release, version 0.9.0, came in February 1991.
2. The language was named after the British comedy series "Monty
Python's Flying Circus," as Guido was a fan of the show and wanted a
name that would be unique and memorable.
1994: Python 1.0
1. Python 1.0 was released in January 1994. This version introduced
features like lambda, map, filter, and reduce, which are commonly used
in functional programming.
Late 1990s: Python 2.x Series
1. Python 2.0 was released in October 2000 and brought list
comprehensions, garbage collection, and Unicode support.
2. Python 2 went through multiple releases in the 2.x series, introducing
various improvements and new features.
Early 2000s: PEPs and Python Enhancement Proposals
1. The Python community began using Python Enhancement Proposals
(PEPs) to propose and discuss new features, improvements, and
standards for the language's development.
2008: Python 3.0 (Python 3000)
1. Python 3.0, also known as Python 3000 or simply Python 3, was
released in December 2008.
2. This release introduced significant changes and improvements, but also
backward-incompatible changes from Python 2.x. It aimed to address
design flaws and inconsistencies.
2010s: Python's Popularity Surges
1. Throughout the 2010s, Python's popularity soared due to its simplicity,
versatility, and vibrant community.
2. The language gained traction in various fields, including web
development, data science, machine learning, and scientific computing.
2020s: Continued Growth and Development
1. Python's growth continued into the 2020s, with an ever-expanding
ecosystem of libraries, frameworks, and applications.
2. Python 3 became the dominant version, as Python 2 reached its end of
life on January 1, 2020, and is no longer maintained.
Installation and Setup
Installing Python and setting up your development environment is a
crucial first step to start coding in Python. Here's a guide on how to install
Python and set up your environment:
1. Download Python:
Visit the official Python website (https://www.python.org/downloads/) to
download the latest version of Python. Choose the appropriate version for
your operating system (Windows, macOS, or Linux). As of my last update in
September 2021, the latest stable version is Python 3.x.
2. Install Python:
Windows:
Run the downloaded executable file.
Make sure to check the box that says "Add Python X.X to PATH" during
installation. This ensures that Python is added to your system's PATH
environment variable, allowing you to run Python from the command prompt.
3. Verify Installation:
After installation, you can verify that Python is installed correctly by
opening a terminal or command prompt and entering the following command:

This should display the version of Python you installed.


Writing Your First Python Program
Writing your first Python program is an exciting step! Let's go through
the process of creating a simple "Hello, World!" program, which is a classic
first program that prints a message to the screen.
Here's how you can write and run your first Python program:
1. Choose a Text Editor:
You can use any text editor to write Python code. Common options
include Notepad (Windows), TextEdit (macOS), Visual Studio Code, Sublime
Text, and many others. Integrated Development Environments (IDEs) like
PyCharm and Visual Studio Code can also be used.
2. Write the Code:
Open your chosen text editor and create a new file. Then, type the
following code:
This code uses the built-in print ( ) function to display the message
"Hello, World!" on the screen.
3. Save the File:
Save the file with a .py extension, which is the standard extension for
Python source code files. You can give it any name you like. For example, you
could save it as hello.py.
4. Run the Program:
To run the program, follow these steps based on your operating system:
Windows:
1) Open the Command Prompt (CMD).
2) Navigate to the directory where you saved the .py file using the cd
command.
3) Run the program by typing:

Additional Notes:
A. Make sure you have Python installed and added to your system's PATH
as explained in the "Installation and Setup" section.
B. Pay attention to indentation. Python uses indentation to define code
blocks, so be consistent with your spacing.
C. Remember that Python is case-sensitive. print("Hello") and
Print("Hello") are different.
Python Interactive Mode
Python Interactive Mode, also known as the Python REPL (Read-Eval-
Print Loop), is an interactive environment where you can directly write and
execute Python code line by line. It's a valuable tool for testing code snippets,
exploring language features, and experimenting with Python without the need
to write full scripts or programs.
Here's how to use Python's Interactive Mode:
Starting Python Interactive Mode:
Windows:
A. Open the Command Prompt (CMD).
B. Type python or python3 and press Enter.
You should see the Python interpreter prompt (>>>), indicating that
you're in the interactive mode and can start typing Python code.
Using Python Interactive Mode:
In the interactive mode, you can type any valid Python code and press
Enter. The interpreter will immediately execute the code and display the
result, if applicable. Here's an example:

As shown in the example, you can perform calculations, create variables,


define functions, and even use control structures like loops and conditionals
directly in the interactive mode.
Exiting Python Interactive Mode:
To exit the interactive mode and return to the regular terminal or
command prompt, you can use the exit ( ) function or press Ctrl+D (or Ctrl+Z
on Windows). For example:
Exiting the interactive mode doesn't close the terminal or command
prompt; it simply returns you to the regular command line.
Benefits of Interactive Mode:
A. Rapid Testing: Interactive mode allows you to quickly test code
snippets without having to create a separate script or file.
B. Immediate Feedback: You receive instant feedback on the results of
your code, which is great for learning and debugging.
C. Exploration: You can explore language features, experiment with new
concepts, and interactively learn how Python works.
Basic Syntax and Data Types
Basic Syntax:
Python's syntax is designed to be easy to read and understand. Here are
some key components of Python's basic syntax:
 Comments: Use the # symbol to write comments in your code.
Comments are ignored by the Python interpreter and are used to add
explanations to your code.
# This is a comment
Indentation: Python uses indentation to define code blocks. Proper
indentation is crucial for readability and to indicate nested blocks of code.
if True:
print("Indented block")
Statements: Python code is made up of statements, which are instructions
that perform actions. Statements are typically executed one after another.
x = 5 # Assignment statement
print(x) # Print statement
Data Types:
Python supports various data types, which define the type of data a
variable can hold. Here are some commonly used data types:
Numeric Types:
A. int: Integer data type, e.g., 5, -10.
B. float: Floating-point (decimal) data type, e.g., 3.14, -0.5.
Ex: age = 25
height = 5.9
Strings:
str: String data type, enclosed in single or double quotes, e.g., 'Hello', "Python".
Ex: name = "Alice"
greeting = 'Hello, ' + name
Boolean Type:
bool: Boolean data type representing True or False.
Ex: is_student = True
has_license = False
Lists:
list: Ordered collection of items, enclosed in square brackets [ ], e.g., [1, 2, 3].
Ex: numbers = [1, 2, 3, 4, 5]
fruits = ['apple', 'banana', 'orange']
Tuples:
tuple: Similar to lists but immutable (cannot be changed after creation),
enclosed in parentheses ( ), e.g., (1, 2, 3).
Ex: coordinates = (4, 5)
RGB_color = (255, 0, 0)
Dictionaries:
dict: Collection of key-value pairs, enclosed in curly braces { }, e.g., {'name':
'John', 'age': 30}.
Ex: person = {'name': 'Alice', 'age': 25}
grades = {'math': 90, 'history': 85, 'science': 95}
Sets:
set: Unordered collection of unique elements, enclosed in curly braces { }, e.g.,
{1, 2, 3}.
Ex: unique_numbers = {1, 2, 3, 4, 5}
Variables and Assignments
Variables and assignments are fundamental concepts in programming
that allow you to store and manipulate data. In Python, variables are used to
represent values, and assignments are used to give those values names.
Variables:
A variable is a named container that holds a value. Variables allow you
to store and reference data in your programs. In Python, you don't need to
declare the type of a variable explicitly; Python infers the type based on the
assigned value.
Here's how you create and use variables:
Ex: # Variable assignment
age = 25
name = "Alice"
is_student = True

# Using variables
print(name) # Output: Alice
print(age + 5) # Output: 30
print("Is student?", is_student) # Output: Is student? True

Assignments:
An assignment statement is used to give a variable a value. The =
operator is used for assignment.
Ex: x = 10 # Assigns the value 10 to the variable x
message = "Hello, world!"
You can also assign multiple variables in a single line using a comma-
separated list:
Ex: a, b, c = 5, "Python", True
Naming Conventions:
Python variable names (identifiers) follow specific rules:
A. Start with a letter (a-z, A-Z) or an underscore (_).
B. Can contain letters, digits (0-9), and underscores.
C. Cannot start with a digit.
D. Python is case-sensitive, so myVariable and myvariable are different
variables.
Constant Naming:
Although Python doesn't have constants like some other languages, it's a
convention to use uppercase names for variables that are meant to be treated
as constants:
Ex: PI = 3.14159
GRAVITY = 9.8
Swapping Values:
Python allows you to swap values between variables elegantly:
Ex: x, y = 5, 10
x, y = y, x # Swaps the values of x and y
Type Conversion (Casting):
You can convert variables from one type to another using type
conversion functions like int( ), float( ), and str( ).
Ex: number_str = "42"
number_int = int(number_str) # Converts the string to an integer
Numeric Data Types (int, float, complex)
Python supports several numeric data types that allow you to work with
numbers in different ways. The three primary numeric data types are int,
float, and complex. Let's explore each of these types:
1. Integer (int):
The int data type represents whole numbers without any fractional or
decimal part. Integers can be positive, negative, or zero.
Ex: x = 5
y = -10
z=0
Floating-Point (float):
The float data type represents real numbers with decimal points or
exponent notation. It is used for numbers that have both an integer and
fractional part.
Ex: pi = 3.14159
temperature = -15.5
Complex:
The “complex” data type represents complex numbers in the form ‘a +
bj’, where ‘a’ is the real part and ‘b’ is the imaginary part. You can use ‘j’ or ‘J’
to represent the imaginary unit.
Ex: c1 = 2 + 3j
c2 = -1j

Arithmetic Operations:
You can perform various arithmetic operations on numeric data types:
Ex: x = 10
y=3

addition = x + y # 13
subtraction = x - y # 7
multiplication = x * y # 30
division = x / y # 3.33333...
integer_division = x // y # 3
modulo = x % y #1
exponentiation = x ** y # 1000
Type Conversion (Casting):
You can convert between numeric data types using type casting functions like
int ( ), float ( ), and complex ( ).
Ex: number_str = "42"
number_int = int(number_str) # Convert string to int
number_float = float(number_str) # Convert string to float
real_part = 2
imaginary_part = 3
complex_number = complex(real_part, imaginary_part)
Operations on Complex Numbers:
Python also supports operations on complex numbers:
Ex: c1 = 2 + 3j
c2 = 1 - 1j

addition = c1 + c2 # 3 + 2j
multiplication = c1 * c2 # 5 + 1j

Strings and String Manipulation


Strings are sequences of characters and are widely used in Python for
representing text data. They are enclosed in single (') or double (") quotes.
Let's explore how to work with strings and perform string manipulation in
Python:
Creating Strings:
You can create strings by enclosing text within single or double quotes:
Ex: single_quoted = 'Hello, world!'
double_quoted = "Python programming"

String Manipulation:
Python provides various methods and operations for manipulating strings:
Concatenation: You can concatenate strings using the + operator:
Ex: first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
String Repetition: You can repeat a string multiple times using the ‘*’
operator:
Ex: stars = "*" * 10 # Produces **********
String Indexing and Slicing: Strings are sequences, and you can access
individual characters or substrings using indexing and slicing:
Ex: text = "Python programming"

first_character = text[0] # 'P'


substring = text[7:16] # 'programming'
String Length: You can get the length of a string using the ‘len( )’ function:
Ex: message = "Mice Computer Education"
length = len(message) # 23

String Methods: Python provides numerous built-in string methods for


various tasks, such as converting case, finding substrings, and replacing text:
Ex: text = "Python is fun"

# Converting case
uppercase_text = text.upper() # 'PYTHON IS FUN'
lowercase_text = text.lower() # 'python is fun'

# Finding and replacing


position = text.index("is") #7
new_text = text.replace("fun", "awesome") # 'Python is awesome'

String Formatting: You can format strings using f-strings or the format ( )
method to insert variables or values:
Ex: name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."

Escape Sequences: Escape sequences are special codes that start with a
backslash ‘\’ and represent characters that are hard to type directly:
Ex: escaped_string = "This is a \"quote\"."
newline = "Line 1\nLine 2"

Multiline Strings: Use triple quotes (''' or """) to create multiline strings:
Ex: multiline = '''This is a
multiline string.'''
Strings are versatile and widely used in programming for handling textual
data. Mastering string manipulation techniques is crucial for working
effectively with text-based information in your Python programs.
Boolean Data Type
The Boolean data type in Python represents two truth values: True and
False. Booleans are fundamental in programming as they are used for making
decisions and controlling the flow of your programs through conditional
statements (if statements, loops, etc.). Let's explore how Boolean data types
work in Python:
Boolean Values:
Boolean values are the simplest type of data in Python. They represent
the truth or falsity of a condition. True represents a true condition, and False
represents a false condition.
Ex: is_raining = True
is_sunny = False

Boolean Operators:
Python provides several logical operators that work with Boolean values:
A. and: Returns ‘True’ if both operands are ‘True’.
B. or: Returns ‘True’ if at least one operand is ‘True’.
C. not: Returns the opposite of the Boolean value (negation).
Ex: x = True
y = False

result_and = x and y # False


result_or = x or y # True
result_not = not x # False

Comparison Operators:
Comparison operators are used to compare values and return Boolean results:
A. ==: Equal to
B. !=: Not equal to
C. <: Less than
D. <=: Less than or equal to
E. >: Greater than
F. >=: Greater than or equal to
Ex: age = 25
is_adult = age >= 18 # True

Truth and False Values:


In Python, values other than False, None, 0, empty strings "", empty lists
[ ], empty dictionaries { }, and empty sets set ( ) are considered truth. All other
values are considered false.
This behavior is often used in conditions and loops to check whether a
value exists or is non-empty.

Conditional Statements:
Boolean values are commonly used in conditional statements like ‘if’,
‘elif’, and ‘else’:
Ex: temperature = 25

if temperature > 30:


print("It's hot outside!")
elif temperature > 20:
print("It's warm outside.")
else:
print("It's cold outside.")
Operators (Arithmetic, Comparison, Logical, Assignment)
Arithmetic Operators: These are like the tools for doing math with
numbers. You can add, subtract, multiply, and divide numbers using these
operators. There's also one for finding the remainder when you divide, and
another for raising a number to a power.
+ : Adds two numbers.
- : Subtracts one number from another.
* : Multiplies two numbers.
/ : Divides one number by another.
% : Finds the leftover bit when you divide.
** : Multiplies a number by itself a certain number of times.
Example: a = 10
b=3
addition = a + b
multiplication = a * b
division = a / b
remainder = a % b
exponentiation = a ** b

Comparison Operators: These are like questions you can ask about numbers.
You can use them to compare numbers and figure out things like whether
they're equal, greater than, or less than each other.
== : Asks if two numbers are the same.
!= : Asks if two numbers are not the same.
< : Asks if one number is smaller than the other.
> : Asks if one number is bigger than the other.
<= : Asks if one number is smaller than or equal to the other.
>= : Asks if one number is bigger than or equal to the other.
Example x=5
y=8
equals = x == y
not_equals = x != y
less_than = x < y
greater_than = x > y
Logical Operators: Think of these as tools for making decisions based on true
or false questions. You can combine answers to true/false questions and even
flip them around.
and: Combines two true/false answers with "and." Both need to be true for
the whole thing to be true.
or: Combines two true/false answers with "or." At least one needs to be true
for the whole thing to be true.
not: Flips the answer. If it's true, it becomes false, and if it's false, it becomes
true.
Example: p = True
q = False
logical_and = p and q
logical_or = p or q
logical_not = not p
Assignment Operators: These are like giving a name to a value. You use them
to store numbers or results in variables (names you make up) so you can use
them later.
= : Takes a value and puts it in a variable.
+= : Adds a number to the value in a variable and stores the result back in
the variable.
-= : Subtracts a number from the value in a variable and stores the result
back in the variable.
*= : Multiplies the value in a variable by a number and stores the result
back in the variable.
/= : Divides the value in a variable by a number and stores the result back
in the variable.
Example: x = 10
x += 5 # Equivalent to x = x + 5
y = 20
y -= 3 # Equivalent to y = y - 3

Input and Output


Input and output (I/O) are essential concepts in programming that refer
to how programs communicate with the user, devices, and other programs by
receiving and sending data.
Input
Input refers to the data that a program receives from the user, a file, or
another source. This data can be used for processing, calculations, or making
decisions within the program. Common ways of receiving input include
reading from the keyboard, reading from files.
In most programming languages, you use functions or methods to
obtain input from the user or external sources. Here's an example using
Python:
Example:
name = input("Please enter your name: ")
print("Hello,", name)
In this example, “the input ( )” function prompts the user to enter their name,
and the input is stored in the variable “name”.

Output
Output refers to the information that a program displays or sends to the
user, a device, or another program. It could be the result of calculations, status
updates, or any other relevant information. Common output methods include
displaying text on the screen, writing data to files.
In most programming languages, you use functions or methods to
display output. Here's an example using Python:
Example
age = 25
print("Your age is:", age)
In this example, the “print ( )” function displays the message along with the
value of the variable “age”.

Control Flow
Control flow is a concept in programming that refers to the order in
which instructions or statements are executed in a program. It determines
how the program "flows" from one statement to another based on certain
conditions and decisions. Control flow allows you to create more complex and
dynamic programs by making choices, repeating actions, and branching based
on different conditions.
The following are the conditional statements provided by Python.
1) if
2) if..else
3) Nested if
4) if-elif statements.
if Statement
If the simple code of block is to be performed if the condition holds true
then the if statement is used. Here the condition mentioned holds true then
the code of the block runs otherwise not.
Syntax:
if condition:
# Statements to execute if
# condition is true

Example
# if statement example
if 10 > 5:
print("10 greater than 5")
print("Program ended")
Output:
10 greater than 5
Program ended

You might also like