Python Programming
👋 Welcome! to Ontime Updates
What is Python?
Python is a high-level programming language known for its simplicity and readability. It is widely used in various domains, such as web development, data analysis, artificial intelligence, and automation. Python has a large and active community, which contributes to its extensive library ecosystem and makes it a popular choice among developers.
History of Python:
Python was created by Guido van Rossum and first released in 1991. It was designed to be a simple and easy-to-read programming language that emphasizes code readability. Python's syntax is known for its use of whitespace indentation instead of curly brackets or keywords, which makes it highly readable and helps maintain a clean and organized code structure.
Over the years, Python has gained popularity and has become one of the most widely used programming languages in the world. Its versatility allows it to be used for a wide range of applications, from web development to scientific computing and machine learning.
Python's success can be attributed to its extensive library ecosystem, which provides developers with a vast collection of pre-built modules and packages that can be easily integrated into their projects. This allows developers to leverage existing solutions and accelerate their development process.
With its simplicity, readability, and powerful features, Python continues to be a popular choice among programmers of all levels of experience.
Python Features:
- Simple and Readable Syntax: Python's syntax is designed to be simple and easy to read, using whitespace indentation instead of curly brackets or keywords.
- Extensive Library Ecosystem: Python has a vast collection of pre-built modules and packages that can be easily integrated into projects, allowing developers to leverage existing solutions.
- Versatility: Python can be used for various applications, including web development, data analysis, artificial intelligence, and automation.
- Active Community: Python has a large and active community that contributes to its development and provides support to developers.
- Cross-Platform Compatibility: Python programs can run on different operating systems, including Windows, macOS, and Linux.
- Scalability: Python supports both small and large-scale projects and can handle complex tasks efficiently.
- Integration Capabilities: Python can easily integrate with other languages, allowing developers to combine different tools and technologies.
- Learning Resources: Python has a wealth of learning resources, including documentation, tutorials, and online communities, making it accessible for beginners and experienced programmers.
Applications of Python:
Python is widely used in various domains, including:
- Web development: Python frameworks like Django and Flask are popular for building web applications.
- Data analysis: Python's libraries like Pandas, NumPy, and Matplotlib are widely used for data manipulation, analysis, and visualization.
- Artificial intelligence and machine learning: Python is a preferred language for developing AI and ML models, with libraries like TensorFlow and PyTorch.
- Automation: Python's simplicity and versatility make it ideal for automating tasks and scripting.
- Scientific computing: Python is used extensively in scientific computing for simulations, data analysis, and visualization.
- Robotics: Python is used in robotics for programming and controlling robots.
- Game development: Python is used to develop games with libraries like Pygame.
- Scripting: Python is often used for scripting tasks, system administration, and network programming.
Variables & Datatypes:
Variables:
In Python, variables are used to store data values. They can be assigned different types of values, such as numbers, strings, or boolean values. Unlike some other programming languages, Python does not require explicit declaration of variables.
To assign a value to a variable, you can use the assignment operator =
. For example:
x = 5 # Here x is Variable and 5 is Value
In this example, we assigned the value 5
to the variable x
. The variable x
now holds the value 5
.
Datatypes:
Python supports the following datatypes:
- Numbers: Python supports integers, floating-point numbers, and complex numbers.
- Strings: Strings are sequences of characters enclosed in single quotes (
'
) or double quotes ("
).
- Boolean: Boolean values can be either True or False.
- Lists: Lists are ordered collections of items, enclosed in square brackets (
[]
).
- Tuples: Tuples are similar to lists but are immutable, meaning they cannot be modified once created.
- Dictionaries: Dictionaries are key-value pairs enclosed in curly braces (
{}
).
Here's an example of creating and using variables with different datatypes in Python:
# Numbers
age = 25
weight = 65.5
complex_number = 2 + 3j
# Strings
name = "John Doe"
message = 'Hello, world!'
# Boolean
is_active = True
is_admin = False
# Lists
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange"]
# Tuples
coordinates = (10, 20)
person = ("John", 25, "USA")
# Dictionaries
student = {"name": "Alice", "age": 20, "major": "Computer Science"}
employee = {"name": "Bob", "age": 30, "department": "Sales"}
In Python, variables are dynamically typed, which means you can assign different types of values to the same variable. The data type of a variable is determined by the value it holds at runtime.
Operators in Python:
1. Arithmetic Operators:
These operators perform basic mathematical operations.
+
(Addition)
(Subtraction)
(Multiplication)
/
(Division)
%
(Modulus)
//
(Floor Division)
*
(Exponentiation)
a = 10
b = 3
addition_result = a + b # 13
subtraction_result = a - b # 7
multiplication_result = a * b # 30
division_result = a / b # 3.3333333333333335
modulus_result = a % b # 1
floor_division_result = a // b # 3
exponentiation_result = a ** b # 1000
2. Comparison Operators:
These operators are used to compare values.
==
(Equal to)
!=
(Not equal to)
<
(Less than)
>
(Greater than)
<=
(Less than or equal to)
>=
(Greater than or equal to)
x = 5
y = 10
is_equal = x == y # False
is_not_equal = x != y # True
is_less_than = x < y # True
is_greater_than = x > y # False
is_less_than_or_equal = x <= y # True
is_greater_than_or_equal = x >= y # False
3. Logical Operators:
These operators perform logical operations.
and
(Logical AND)
or
(Logical OR)
not
(Logical NOT)
a = True
b = False
result_and = a and b # False
result_or = a or b # True
result_not = not a # False
a = True
b = False
result_and = a and b # False
result_or = a or b # True
result_not = not a # False
4. Assignment Operators:
These operators are used to assign values to variables.
=
(Assignment)
+=
(Add and assign)
=
(Subtract and assign)
=
(Multiply and assign)
/=
(Divide and assign)
%=
(Modulus and assign)
//=
(Floor divide and assign)
*=
(Exponentiate and assign)
x = 10
x += 5 # Equivalent to x = x + 5
5. Bitwise Operators:
These operators perform bit-level operations.
&
(Bitwise AND)
|
(Bitwise OR)
^
(Bitwise XOR)
~
(Bitwise NOT)
<<
(Left shift)
>>
(Right shift)
a = 5 # Binary: 0101
b = 3 # Binary: 0011
result_and = a & b # Binary: 0001 (1 in decimal)
result_or = a | b # Binary: 0111 (7 in decimal)
result_xor = a ^ b # Binary: 0110 (6 in decimal)
result_not_a = ~a # Binary: 1010 (-6 in decimal)
6. Membership Operators:
These operators test membership in a sequence.
in
(True if a value is found in the sequence)
not in
(True if a value is not found in the sequence)
my_list = [1, 2, 3, 4, 5]
is_in_list = 3 in my_list # True
is_not_in_list = 6 not in my_list # True
7. Identity Operators:
These operators compare the memory locations of two objects.
is
(True if the operands are identical)
is not
(True if the operands are not identical)
a = [1, 2, 3]
b = [1, 2, 3]
is_identical = a is b # False
is_not_identical = a is not b # True
Conditional Statements:
Conditional statements in Python allow you to execute different blocks of code based on whether a given condition is true or false. The primary conditional statements in Python are if
, elif
(short for "else if"), and else
. Here are examples of how they are used:
1. if
Statement:
The if
statement is used to execute a block of code if a specified condition is true.
x = 10
if x > 5:
print("x is greater than 5")
Output:
x is greater than 5
2. if-else
Statement:
The if-else
statement allows you to execute one block of code if a condition is true and another block if the condition is false.
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
Output:
x is less than or equal to 5
3. if-elif-else
Statement:
The if-elif-else
statement is used when you have multiple conditions to check. It allows you to specify a series of conditions, and the first one that is true will execute its associated block of code.
score = 75
if score >= 90:
print("A grade")
elif score >= 80:
print("B grade")
elif score >= 70:
print("C grade")
else:
print("Fail")
Output:
C grade
4.Nested if
Statement
The if statement consits of inside the another if statement is called nested-if
statement
x = 10
y = 5
if x > 5:
if y > 2:
print("Both conditions are true")
else:
print("Inner condition is false")
else:
print("Outer condition is false")
Output:
Both conditions are true
5.Ternary Conditional Expression:
Python also supports a ternary conditional expression, which is a concise way to write simple if-else
statements in a single line.
age = int(input("Enter age:"))
message = "You are an adult" if age >= 18 else "You are a minor"
print(message)
Output:
Enter age:19
You are an adult
Loops:
In Python, loops are used to repeatedly execute a block of code. The two main types of loops are for
and while
. Here are examples of how they work:
1. for
Loop:
The for
loop is used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code for each item in the sequence.
Example with a List:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
#Output:
apple
banana
cherry
Example with a Range:
for i in range(5):
print(i)
#Output:
0
1
2
3
4
for
Loop with else
:
You can include an else
block which will be executed when the loop is exhausted (i.e., when there are no more items in the sequence).
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
else:
print("No more fruits")
#Output:
apple
banana
cherry
No more fruits
2. while
Loop:
The while
loop is used to repeatedly execute a block of code as long as a specified condition is true.
count = 0
while count < 5:
print(count)
count += 1
#Output:
0
1
2
3
4
while
Loop with else
:
Similar to the for
loop, a while
loop can also have an else
block that is executed when the loop condition becomes false.
count = 0
while count < 5:
print(count)
count += 1
else:
print("Loop completed")
#Output:
0
1
2
3
4
Loop completed
Loop Control Statements:
break
Statement:
The break
statement is used to exit a loop prematurely.
for i in range(10):
if i == 3:
break
print(i)
#Output:
0
1
2
continue
Statement:
The continue
statement is used to skip the rest of the code inside the loop for the current iteration and move to the next iteration.
for i in range(5):
if i % 2 == 0:
continue
print(i)
#Output:
1
3
Nested Loops:
You can also nest loops inside each other for more complex scenarios.
for i in range(3):
for j in range(2):
print(i, j)
#Output:
0 0
0 1
1 0
1 1
2 0
2 1