DEV Community

Cover image for Day -1 Python In One Shot 🐍
Pranjal Sharma
Pranjal Sharma

Posted on

Day -1 Python In One Shot 🐍

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 -

  1. Foundations

    1. Keywords, Identifiers, and Comments
      • Understanding the building blocks of Python.
    2. Indentation
      • Exploring the significance of proper indentation in Python code.
    3. Statements and Variables
      • Delving into the fundamental elements of scripting.
  2. Data Types Mastery

    1. Numeric and Textual Data
      • Comprehensive coverage of integers, floats, and strings.
    2. Collections
      • Introduction to lists, tuples, sets, and dictionaries.
  3. Input/Output Operations

    1. Standard Input/Output
      • Navigating the standard channels of data.
    2. Redirecting Input/Output
      • Manipulating data flow within Python scripts.
  4. Operational Dynamics

    1. Operators
      • Unraveling the functionality of Python operators.
    2. Control Flow Structures
      • Mastery of if-else, elif, and loops.
  5. Advanced Data Handling

    1. List Operations
      • Techniques for efficient list manipulation.
    2. Tuple and Set Operations
      • Understanding the unique attributes of tuples and sets.
    3. Dictionary Operations
      • Exploring the functionalities of Python dictionaries.
  6. Functionality Elegance

    1. User-Defined Functions
      • Crafting reusable and modular code.
    2. Lambda Functions
      • Introduction to concise, anonymous functions.
    3. Recursion
      • Understanding recursive function implementation.
  7. Error Handling and Logging

    1. Exception Handling
      • Strategies for identifying and managing errors.
    2. User-Defined Exceptions
      • Creating custom exception classes.
    3. Logging
      • Implementing effective logging practices.
  8. Object-Oriented Programming (OOP)

    1. Inheritance and Classes
      • Grasping the principles of inheritance and class structures.
    2. Access Modifiers
      • Understanding access control within classes.

Let the Python begin! 🎉🐍

Keywords-

Here are the key points related to keywords in Python:

  1. 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.

  2. Immutability: Keywords are immutable. This means their meaning and definition can't be altered.

  3. Case Sensitivity: Keywords are case-sensitive. For example, True is a valid keyword, but true is not.

  4. Total Number: As of Python 3.9, there are 35 keywords.

  5. 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.

  6. Special Keywords: async and await are used for handling asynchronous processing, and they became keywords in Python 3.7.

  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 and while are used for loops, class is used for defining a class, and so on.

  8. 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)
Enter fullscreen mode Exit fullscreen mode

Identifier

Here are the key points related to identifiers in Python:

  1. Definition: An identifier is a name given to entities like class, functions, variables, etc. It helps to differentiate one entity from another.

  2. 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 (_).

  3. No digits: They must start with a letter or the underscore character, but not with a digit.

  4. Case-Sensitive: Identifiers in Python are case-sensitive. For example, myVariable and myvariable are two different identifiers in Python.

  5. No Special Characters: Identifiers cannot have special characters such as !, @, #, $, %, etc.

  6. 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 typing help("keywords") in the Python interpreter.

  7. 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.

  8. 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.

  9. 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'
Enter fullscreen mode Exit fullscreen mode

Comments

Here are some key points about comments in Python:

  1. 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.
  2. 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. 
  3. 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.
  4. 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 ' 
Enter fullscreen mode Exit fullscreen mode

Indentation

Indentation

  1. 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.

  2. 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.

  3. Colon: Usually, a colon (:) at the end of the line is followed by an indented block of code. This is common with structures like if, for, while, def, class, etc.

def fun1():
  print("Hi")  # Correct Indentation

def fun2():
print('hi')  # Incorrect Indendation
Enter fullscreen mode Exit fullscreen mode

Statements

  1. 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.
  2. Types: Python includes several types of statements including assignment statements, conditional statements, looping statements, etc.
for i in range(5):
    print(I)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Variables

  1. Definition: In Python, a variable is a named location used to store data in memory.

  2. 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Data types in Python

Integers

Integers are whole numbers, without a fractional component. They can be positive or negative.

x = 10
y = -3
Enter fullscreen mode Exit fullscreen mode

Floats

Floats represent real numbers and are written with a decimal point.

x = 10.0
y = -3.14
Enter fullscreen mode Exit fullscreen mode

Strings

Strings in Python are sequences of character data. They are created by enclosing characters in quotes.

s = "Hello, World!"
print(s)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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'}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Updating Values

You can update the value for a particular key by using the assignment operator =.

my_dict["age"] = 20
print(my_dict)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Sets

A set is an unordered collection of items where every element is unique.

colors = {"red", "green", "blue"}
print(colors)
Enter fullscreen mode Exit fullscreen mode

Type checking

To determine the type of a variable, you can use the type() function.

x = 10
print(type(x))
Enter fullscreen mode Exit fullscreen mode

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}")
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

This prints numbers from 0 to 4. You can also specify a start and end point:

for i in range(2, 5):
    print(i)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
photon_ray profile image
Vijay

Thank you for this

Collapse
 
camilo805doctom profile image
Juan Camilo Muñoz Bautista

Muchas gracias

Collapse
 
pranjal_ml profile image
Pranjal Sharma

De nada