Hey, fellow code adventurers! Get ready to hop on the Python party train because we're about to kick off a roller coaster of epic proportions. Welcome to Day -1 of our Python Palooza, where we're serving up Python knowledge like never before, all in one shot!
Let's make Python learning feel like a party, not a lecture! šš
The Roadmap for today is -
-
Foundations
- Keywords, Identifiers, and Comments
- Understanding the building blocks of Python.
- Indentation
- Exploring the significance of proper indentation in Python code.
- Statements and Variables
- Delving into the fundamental elements of scripting.
- Keywords, Identifiers, and Comments
-
Data Types Mastery
- Numeric and Textual Data
- Comprehensive coverage of integers, floats, and strings.
- Collections
- Introduction to lists, tuples, sets, and dictionaries.
- Numeric and Textual Data
-
Input/Output Operations
- Standard Input/Output
- Navigating the standard channels of data.
- Redirecting Input/Output
- Manipulating data flow within Python scripts.
- Standard Input/Output
-
Operational Dynamics
- Operators
- Unraveling the functionality of Python operators.
- Control Flow Structures
- Mastery of if-else, elif, and loops.
- Operators
-
Advanced Data Handling
- List Operations
- Techniques for efficient list manipulation.
- Tuple and Set Operations
- Understanding the unique attributes of tuples and sets.
- Dictionary Operations
- Exploring the functionalities of Python dictionaries.
- List Operations
-
Functionality Elegance
- User-Defined Functions
- Crafting reusable and modular code.
- Lambda Functions
- Introduction to concise, anonymous functions.
- Recursion
- Understanding recursive function implementation.
- User-Defined Functions
-
Error Handling and Logging
- Exception Handling
- Strategies for identifying and managing errors.
- User-Defined Exceptions
- Creating custom exception classes.
- Logging
- Implementing effective logging practices.
- Exception Handling
-
Object-Oriented Programming (OOP)
- Inheritance and Classes
- Grasping the principles of inheritance and class structures.
- Access Modifiers
- Understanding access control within classes.
- Inheritance and Classes
Let the Python begin! šš
Keywords-
Here are the key points related to keywords in Python:
-
Definition: Keywords in Python are reserved words that cannot be used as ordinary identifiers. They are used to define the syntax and structure of the Python language.
-
Immutability: Keywords are immutable. This means their meaning and definition can't be altered.
-
Case Sensitivity: Keywords are case-sensitive. For example,
True
is a valid keyword, buttrue
is not. -
Total Number: As of Python 3.9, there are 35 keywords.
-
List of Keywords: The complete list of Python keywords are
False
,None
,True
,and
,as
,assert
,async
,await
,break
,class
,continue
,def
,del
,elif
,else
,except
,finally
,for
,from
,global
,if
,import
,in
,is
,lambda
,nonlocal
,not
,or
,pass
,raise
,return
,try
,while
,with
,yield
. -
Special Keywords:
async
andawait
are used for handling asynchronous processing, and they became keywords in Python 3.7. -
Usage: Each keyword has a specific meaning and usage in Python programming. For instance,
def
is used for defining functions,if
is used for making conditional statements,for
andwhile
are used for loops,class
is used for defining a class, and so on. -
Identifying Keywords: You can get the list of all keywords in Python by using the following code:
# Import Keywords
import keyword
# Print the list
print(keyword.kwlist)
Identifier
Here are the key points related to identifiers in Python:
-
Definition: An identifier is a name given to entities like class, functions, variables, etc. It helps to differentiate one entity from another.
-
Syntax: Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore (_).
-
No digits: They must start with a letter or the underscore character, but not with a digit.
-
Case-Sensitive: Identifiers in Python are case-sensitive. For example,
myVariable
andmyvariable
are two different identifiers in Python. -
No Special Characters: Identifiers cannot have special characters such as
!
,@
,#
,$
,%
, etc. -
Reserved Words: Python keywords cannot be used as identifiers. Words like
for
,while
,break
,continue
,in
,elif
,else
,import
,from
,pass
,return
, etc. are reserved words. You can view all keywords in your current version by typinghelp("keywords")
in the Python interpreter. -
Unlimited Length: Python does not put any restriction on the length of the identifier. However, it's recommended to keep it within a reasonable size, to maintain readability and simplicity in the code.
-
Private Identifiers: In Python, if the identifier starts with a single underscore, it indicates that it is a non-public part of the class, module, or function. This is just a convention and Python doesn't enforce it. If it starts with two underscores, it's a strongly private identifier. If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.
-
Non-ASCII Identifiers: Python 3 allows the use of non-ASCII letters in the identifiers. This means you can use letters like Ć©, Ʊ, ƶ, Ń, etc. in your identifiers if you wish.
# Valid Identifier
my_name='Pranjal'
My_name='Sharma'
__My_namw="Pj"
## Invalid Identofier
1My_name='Hi'
Comments
Here are some key points about comments in Python:
- Definition: A comment in Python is a piece of text in your code that is not executed. It's typically used to explain what the code is doing or leave notes for developers who will be reading or maintaining the code.
- Single-Line Comments: Python uses the hash symbol (#) to denote a comment. Any text following the # on the same line will be ignored by the Python interpreter.Ā
- Multi-Line Comments: Python does not have a specific syntax for multi-line comments. Developers typically use a single # for each line to create multi-line comments. Alternatively, multi-line strings using triple quotes (''' or """) can also be used as multi-line comments because any string not assigned to a variable is ignored by Python.
- Docstrings or documentation strings: Docstrings are a type of comment used to explain the purpose of a function or a class. They are created using triple quotes and are placed immediately after the definition of a function or a class. Docstrings can span multiple lines and are accessible at runtime using the .__doc__ attribute.
# Single Line
' Multiple line '
"""
Another type of multiline comments
"""
# Doc String
def fun():
" This function will print 'Hello world '"
print('Hello world')
print(fun.__doc__) # This function will print 'Hello world '
Indentation
Indentation
-
Importance: In Python, indentation is not just for readability. It's a part of the syntax and is used to indicate a block of code.
-
Space Usage: Python uses indentation to define the scope of loops, functions, classes, etc. The standard practice is to use four spaces for each level of indentation, but you can use any number of spaces, as long as the indentation is consistent within a block of code.
-
Colon: Usually, a colon (
:
) at the end of the line is followed by an indented block of code. This is common with structures likeif
,for
,while
,def
,class
, etc.
def fun1():
print("Hi") # Correct Indentation
def fun2():
print('hi') # Incorrect Indendation
Statements
- Definition: A statement in Python is a logical instruction that the Python interpreter can read and execute. In general, a statement performs some action or action.
- Types: Python includes several types of statements including assignment statements, conditional statements, looping statements, etc.
for i in range(5):
print(I)
Multi-Line Statements: In Python, end of a statement is marked by a newline character. But we can make a statement extend over multiple lines with the line continuation character (\
), or within parenthesesĀ ()
, bracketsĀ []
, bracesĀ {}
, or strings. You can also write multiple statements on a single line using semicolons (;)
# Multi-Line Statements
# Using line continuation character
s = 1 + 2 + 3 + \
4 + 5
# Using parentheses
s = (1 + 2 + 3 +
4 + 5)
# Multiple Statements on a Single Line
x = 5; y = 10; print(x + y)
Variables
-
Definition: In Python, a variable is a named location used to store data in memory.
-
Declaration and Assignment: Variables are declared by writing the variable name and assigning it a value using the equals sign (
=
). For example:
name= 'Pranjal' # defining a variable
Dynamic Typing: Python is dynamically typed, which means that you don't have to declare the type of a variable when you create one. You can even change the type of data held by a variable at any time.
x=5 # integer now
x=' Hello' # String now
x
Data types in Python
Integers
Integers are whole numbers, without a fractional component. They can be positive or negative.
x = 10
y = -3
Floats
Floats represent real numbers and are written with a decimal point.
x = 10.0
y = -3.14
Strings
Strings in Python are sequences of character data. They are created by enclosing characters in quotes.
s = "Hello, World!"
print(s)
Lists
A list in Python is an ordered collection (also known as a sequence) of items. Lists are similar to arrays in other languages, but with additional functionality.
fruits = ["apple", "banana", "cherry"]
print(fruits)
Heterogeneous Elements
A list can contain elements of different types: integers, floats, strings, and even other lists or tuples.
mixed_list = [1, "Alice", 3.14, [5, 6, 7]]
print(mixed_list)
Indexing and Slicing
Lists support indexing and slicing to access and modify their elements. Python list indices start at 0.
my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # 1
print(my_list[1:3]) # [2, 3]
my_list[0] = 10 # change the first element to 10
print(my_list)
Tuples
A tuple in Python is similar to a list. It's an ordered collection of items.
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple)
Immutable
The major difference from lists is that tuples are immutable, which means their elements cannot be changed (no addition, modification, or deletion) after they are created.
my_tuple = (1, 2, 3, "Tom", [5, 6, 7])
print(my_tuple)
Indexing and Slicing
Tuples also support indexing and slicing, like lists, but you cannot modify their elements.
print(my_tuple[0]) # 1
print(my_tuple[1:3]) # (2, 3)
Dictionaries
A dictionary in Python is an unordered collection of items. Each item stored in a dictionary has a key and value, making it a key-value pair.
person = {"name": "Alice", "age": 25}
print(person)
Mutable
Dictionaries are mutable, which means you can change their elements. You can add, modify, or delete key-value pairs from a dictionary.
my_dict = {1: "Tom", "age": 23, (1, 3): [4, 5, 3]}
print(my_dict)
Unique Keys
Each key in a dictionary should be unique. If a dictionary is created with duplicate keys, the last assignment will overwrite the previous ones.
my_dict = {"name": "Alice", "name": "Bob"}
print(my_dict) # {'name': 'Bob'}
Accessing Values
You can access a value in a dictionary by providing the corresponding key inside square brackets [].
my_dict = {"name": "Tom", "age": 21}
print(my_dict["name"]) # Tom
Updating Values
You can update the value for a particular key by using the assignment operator =.
my_dict["age"] = 20
print(my_dict)
Adding and Deleting Key-Value Pairs
You can add a new key-value pair simply by assigning a value to a new key. You can delete a key-value pair using the del keyword.
my_dict = {"name": "Tom", "age": 20}
my_dict["city"] = "New York" # adding a new key-value pair
del my_dict["age"] # deleting a key-value pair
print(my_dict)
Sets
A set is an unordered collection of items where every element is unique.
colors = {"red", "green", "blue"}
print(colors)
Type checking
To determine the type of a variable, you can use the type() function.
x = 10
print(type(x))
Standard Input and Output
Standard Output
- This is typically the terminal (or the console) where the program is run. When a program wants to output some information, it will typically print to the standard output.
- Python provides
print()
function to send data to standard output. Here is an example:
Standard Input:
- This is usually the keyboard, but it can also be data coming from a file or another program.
- Python provides the
input()
function to read data from standard input. Here is an example:
# Output-
print('Welcome to Python One Shot')
# Input
age=input('What is your age?')
print(f"Your age is {age}")
Redirecting Standard Output and Input:
- Sometimes, you might want to save the output of a program to a file instead of printing it to the terminal. This is called redirecting the standard output.Ā
- While this isn't done with Python code, but with command line syntax, it is still a common and important concept.Ā
- Similarly to redirecting output, you can also redirect the standard input from a file.
# Works only in cmd line
python my_script.py < input.txt
python my_script.py > output.txt
Operators
Various Operators in Python are:
- Arithmetic operators
- Assignment operators
- Comparison operators
- Logical operators
- Identity operators
- Membership operators
- Bitwise operators
Various Operators in Python are:
Arithmetic Operators
Used to perform mathematical operations.
a = 10
b = 3
print(a + b) # Addition, Output: 13
print(a - b) # Subtraction, Output: 7
print(a * b) # Multiplication, Output: 30
print(a / b) # Division, Output: 3.3333333333333335
print(a // b) # Floor Division, Output: 3
print(a % b) # Modulus, Output: 1
print(a ** b) # Exponent, Output: 1000
Assignment Operators
Used to assign values to variables.
a = 10 # Assigns value 10 to a
print(a)
a += 5 # Same as a = a + 5, Output: 15
print(a)
a -= 3 # Same as a = a - 3, Output: 12
print(a)
a *= 2 # Same as a = a * 2, Output: 24
print(a)
a /= 6 # Same as a = a / 6, Output: 4.0
print(a)
Comparison Operators
Used to compare two values.
a = 10
b = 20
print(a == b) # Equal to, Output: False
print(a != b) # Not equal to, Output: True
print(a > b) # Greater than, Output: False
print(a < b) # Less than, Output: True
print(a >= b) # Greater than or equal to, Output: False
print(a <= b) # Less than or equal to, Output: True
Logical Operators
Used to combine conditional statements.
a = True
b = False
print(a and b) # Logical AND, Output: False
print(a or b) # Logical OR, Output: True
print(not a) # Logical NOT, Output: False
Bitwise Operators
Used to perform bitwise calculations on integers.
AND Operator &
Compares each bit of the first operand with the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the result bit is set to 0.
a = 10 # in binary: 1010
b = 4 # in binary: 0100
result = a & b # result is 0 (in binary: 0000)
print(result)
OR Operator |
Compares each bit of the first operand with the corresponding bit of the second operand. If either bit is 1, the corresponding result bit is set to 1. Otherwise, the result bit is set to 0.
a = 10 # in binary: 1010
b = 4 # in binary: 0100
result = a | b # result is 14 (in binary: 1110)
print(result)
NOT Operator ~
Inverts all the bits of the operand. Every 0 is changed to 1, and every 1 is changed to 0.
a = 10 # in binary: 1010
result = ~a # result is -11 (in binary: -1011)
print(result)
XOR Operator ^
Compares each bit of the first operand with the corresponding bit of the second operand. If one of the bits is 1 (but not both), the corresponding result bit is set to 1. Otherwise, the result bit is set to 0.
a = 10 # in binary: 1010
b = 4 # in binary: 0100
result = a ^ b # result is 14 (in binary: 1110)
print(result)
Right Shift Operator >>
Shifts the bits of the number to the right by the number of bits specified. Each shift to the right corresponds to dividing the number by 2.
a = 10 # in binary: 1010
result = a >> 2 # result is 2 (in binary: 0010)
print(result)
Left Shift Operator <<
Shifts the bits of the number to the left by the number of bits specified. Each shift to the left corresponds to multiplying the number by 2.
a = 10 # in binary: 1010
result = a << 2 # result is 40 (in binary: 101000)
print(result)
Remember, bitwise operations are only applicable to integers.
Membership Operators
Used to test whether a value or variable is found in a sequence (string, list, tuple, set, and dictionary).
list = [1, 2, 3, 4, 5]
print(1 in list) # Output: True
print(6 not in list) # Output: True
Identity Operators
Used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location.
# Integers (immutable)
a = 10
b = 10
print(a is b) # True (same memory location for small integers)
# Strings (immutable)
c = "hello"
d = "hello"
print(c is d) # True (often same memory location for small strings)
# Lists (mutable)
e = [1, 2, 3]
f = [1, 2, 3]
print(e is f) # False (different memory locations for mutable objects)
Control flow: if else elif
Ā Conditional statements are used to execute or skip blocks of code based on certain conditions. The if, elif, and else keywords are used to define these conditional statements.
score = 95
if score >= 90:
print("Grade is A")
elif score >= 80:
print("Grade is B")
elif score >= 70:
print("Grade is C")
else:
print("Grade is D")
# Grade is A
Nested For and IF
# Given a list of numbers, we want to check if a number is divisible by 3 and print it if it is.
# Here's our list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# The loop goes through each number in the list
for num in numbers:
# The if statement checks if the number is divisible by 3
if num % 3 == 0:
# If the number is divisible by 3, print it
print(f"{num} is divisible by 3")
1. For Loop: The Workhorse of Iteration
Basic Iteration with range()
Function
The for
loop in Python is widely used for iterating over a sequence of numbers or other iterable objects. One common approach is using the range()
function:
for i in range(5):
print(i)
This prints numbers from 0 to 4. You can also specify a start and end point:
for i in range(2, 5):
print(i)
Here, it prints numbers from 2 to 4. To introduce a step value, use the third parameter:
for i in range(0, 20, 2):
print(i)
This prints even numbers from 0 to 18.
Iterating Over Lists
The for
loop is not limited to numerical ranges. You can iterate over elements in a list:
country = ["India", "UK", "USA", "Germany"]
for ct in country:
print(ct)
This example prints the names of countries one by one.
Pattern Printing
The for
loop is also useful for creating patterns. For instance, a simple asterisk pattern:
for i in range(5):
for j in range(i+1):
print('*', end=' ')
print()
This prints a triangular pattern of asterisks.
2. Nested For Loop: Unleashing the Power
Multiplication Table
Nested for
loops are handy for more complex patterns, such as creating a multiplication table:
for i in range(1, 6):
for j in range(1, 6):
print(i * j, end='\t')
print()
This prints a table where each element is the product of the corresponding row and column.
Pattern with Numbers
Another example is printing a pattern with decreasing numbers:
initial_num = 16
lines = 4
for i in range(lines):
num = initial_num
for j in range(i + 1):
print(num, end=' ')
num //= 2
print()
This produces a pattern with decreasing numbers in each line.
3. While Loop: Dynamic Iteration
Basic Usage
While loops are used when the number of iterations is not known beforehand. A simple counting example:
count = 1
while count <= 5:
print(count)
count += 1
This prints numbers from 1 to 5.
Interactive Input Loop
While loops are also handy for interactive input:
text = ""
while text != "quit":
text = input("Enter a word (or quit to exit):")
print("You entered:", text)
This loop continues to prompt the user until they enter "quit."
Dynamic Salary Update
While loops are beneficial for scenarios where we need to iterate until a specific condition is met. For instance, updating the salary for specific employees:
names = ["Alice", "Tom", "Marry", "James"]
salary = [30000, 40000, 45000, 40000]
for i in range(len(names)):
if names[i] == "James":
increment = salary[i] * 0.05
salary[i] += increment
print(salary)
This updates James's salary by giving a 5% bonus.
Time-Limited Loop
To run a loop for a specific duration, use the time
module:
import time
start_time = time.time()
duration = 10
while time.time() - start_time < duration:
print("hi")
time.sleep(0.3)
This loop prints "hi" every 0.3 seconds for a duration of 10 seconds.
We will continue this for advance data types & Oops in next blog. Stay connected . Pls visit the github for code -
Colab
Drop by our Telegram Channel and let the adventure begin! See you there, Data Explorer! šš
Top comments (3)
Thank you for this
Muchas gracias
De nada