× back

Introduction to Python

Creating, Saving, and Running a Python Script

Basic Input and Output in Python

In Python, handling user input and displaying output is straightforward and flexible. This section will cover the basic methods for taking input and displaying output.

Input in Python

In Python, you can take input from the user using the input() function. This function reads a line from input, converts it into a string, and returns it. You can then convert this string into the desired data type using typecasting.

Example:

                
# Taking input from the user
name = input("Enter your name: ")
print(f"Hello, {name}!")
                
            

Typecasting Input

To convert the input to a specific type, you can use typecasting functions like int(), float(), etc.

Example:

                
# Taking integer input from the user
age = int(input("Enter your age: "))
print(f"You are {age} years old.")
                
            

Output in Python

In Python, you can display output to the user using the print() function. The print() function outputs data to the console.

Example:

                
# Displaying output
print("Hello, World!")
                
            

Formatted Output

You can format the output using formatted strings (f-strings), the format() method, or the % operator.

Example using f-strings:

                
name = "Alice"
age = 30
print(f"{name} is {age} years old.")
                
            

Example using format() method:

                
name = "Alice"
age = 30
print("{} is {} years old.".format(name, age))
                
            

Example using % operator:

                
name = "Alice"
age = 30
print("%s is %d years old." % (name, age))
                
            

Example Program Combining Input and Output

Here’s a simple program that takes an integer input from the user, calculates its square, and displays the result:

                
# Taking integer input from the user
num = int(input("Enter a number: "))

# Using a lambda function to calculate the square of the number
square = lambda x: x * x

# Displaying the result using an f-string
print(f"The square of {num} is {square(num)}")
                
            

Python Data Types

In Python, there is no need to explicitly mention the data type when declaring a variable; Python automatically infers the data type based on the assigned value.

This feature is known as dynamic typing, and it allows for greater flexibility in variable assignment. Unlike statically typed languages, where the data type must be explicitly declared before using a variable, Python allows you to assign values to variables without specifying their types.

For example:

                
# Dynamic Typing in Python
my_variable = 10 # Python infers the data type as integer
my_string = "Hello" # Python infers the data type as string
my_float = 3.14 # Python infers the data type as float

# Variables can change data type dynamically
my_variable = "World" # Now my_variable is a string
                
            

Following are all data type used in python:

Using the `type()` Function

To determine the data type of a variable in Python, you can use the built-in `type()` function.

    
x = 5
data_type = type(x)
print(data_type)  # Output: <class 'int'>
    
  

String

  • String Representation: Strings in Python can be represented using double quotes ("hi"), single quotes ('hi'), and triple single quotes ('''hi''').
  • Handling Multiple Lines: For multiline strings, use three double quotes ("""this is a long sentence""").
  • Immutability: Strings are immutable, meaning their values cannot be changed after creation. However, string manipulation is possible, similar to tuple and list operations.
  • String Operations: Three common string operations include:
    • Concatenation (+): Combining two or more strings to create a new one.
    • Repetition (*): Repeating a string multiple times.
    • Slicing (:): Extracting a portion of the string using indices or slices.

Slicing:

In Python, slicing is a technique used to extract a portion of a string. The syntax for slicing a string is as follows:

                        
string[start:stop:step]
                        
                    
  • Here's what each part of the slicing syntax represents:
    • start: The starting index of the slice (inclusive). If omitted, it defaults to the beginning of the string.
    • stop: The ending index of the slice (exclusive). If omitted, it defaults to the end of the string.
    • step: The step size or the interval between characters. If omitted, it defaults to 1.

We should know about forward and backward indexing:

                        
str = "PROGRAMMING"
print(str[0]) # Output : P
print(str[-1]) # Output : G
                        
                    
                        
# Example String
my_string = "Hello, World!"

# Basic Slicing
substring = my_string[7:12]  # Extracts "World"
print(substring)

# Omitting Start and Stop (Defaults to the entire string)
whole_string = my_string[:]  # Extracts the entire string
print(whole_string)

# Slicing with Step
every_second_char = my_string[::2]  # Extracts every second character
print(every_second_char)

# Reverse the String
reverse_string = my_string[::-1]  # Reverses the string
print(reverse_string)
#When you use a negative step value like -1, it means that you want to iterate over the original sequence in reverse order.
                        
                    

List

A list in Python is a versatile and mutable collection that allows you to store and manipulate a sequence of items. Lists are defined by enclosing comma-separated values within square brackets [ ].

Key characteristics and operations associated with lists:

  • Mutable: Lists are mutable, meaning you can modify their elements after creation.
  • Ordered: Lists maintain the order of elements, and each element has a specific index (position) in the list.
  • Allows Duplicates: Lists can contain duplicate elements.
  • Supports Various Data Types: A single list can contain elements of different data types, such as integers, strings, and even other lists.

Example of creating a list:

                    
my_list = [1, 2, 3, "Hello", 3.14, True]
                    
                

Common operations on lists:

  • Accessing Elements: Elements in a list are accessed using their index. Indexing starts from 0.
  • Slicing: Extracting a portion of the list using a range of indices.
  • Modifying Elements: Modifying elements by assigning new values to specific indices.
  • Appending and Extending: Adding elements to the end of the list using append(), and extending a list with another using extend().
  • Removing Elements: Removing elements by value using remove(), and by index using pop().
  • Length: Finding the length of a list using len().

Example:

                    
numbers = [1, 2, 3, 4, 5]
print(numbers[2])       # Output: 3
print(numbers[1:4])     # Output: [2, 3, 4]
numbers[0] = 10         # Modifying element at index 0
numbers.append(6)       # Appending 6 to the end
numbers.extend([7, 8])  # Extending with another list
numbers.remove(3)       # Removing element with value 3
print(len(numbers))     # Output: 7
                    
                
                            
# Define a list
my_list = [1, 2, 3, 4, 5]

# Print the original list
print("Original list:", my_list)

# Modify the list by changing the second element
my_list[1] = 10

# Print the modified list
print("Modified list:", my_list)
                            
                        

Output:

                    
Original list: [1, 2, 3, 4, 5]
Modified list: [1, 10, 3, 4, 5]
                    
                

Tuples in Python

A tuple in Python is an ordered, immutable collection of elements. Tuples are defined by enclosing comma-separated values within parentheses ( ). Once created, the elements of a tuple cannot be modified or altered.

Key characteristics and considerations related to tuples:

  • Immutable: Tuples are immutable, meaning their elements cannot be changed or reassigned after creation.
  • Ordered: Tuples maintain the order of elements, and each element has a specific index (position) in the tuple.
  • Allows Duplicates: Tuples can contain duplicate elements.
  • Supports Various Data Types: A single tuple can contain elements of different data types.
  • Useful for Unchanging Data: Tuples are well-suited for situations where the data should remain constant throughout the program.

Example of creating a tuple:

                    
my_tuple = (1, 2, 3, "Hello", 3.14, True)
                    
                

Common operations on tuples:

  • Accessing Elements: Elements in a tuple are accessed using their index. Indexing starts from 0.
  • Slicing: Extracting a portion of the tuple using a range of indices.
  • Length: Finding the length of a tuple using len().
  • Unpacking: Assigning individual elements of a tuple to separate variables.

Example:

                    
coordinates = (4, 5)
print(coordinates[1])    # Output: 5
print(coordinates[0:])   # Output: (4, 5)
print(len(coordinates))  # Output: 2

# Unpacking a tuple
x, y = coordinates
print(x)  # Output: 4
print(y)  # Output: 5
                    
                
                            
# Define a tuple
my_tuple = (1, 2, 3, 4, 5)

# Print the original tuple
print("Original tuple:", my_tuple)

# Trying to modify the tuple by changing the second element (this will cause an error)
# my_tuple[1] = 10  # Uncomment this line to see the error

# Print the tuple (unchanged)
print("Tuple after trying to modify:", my_tuple)
                            
                        

Sets in Python

A set in Python is an unordered and mutable collection of unique elements. Sets are defined by enclosing comma-separated values within curly braces {}. Sets provide efficient methods for performing mathematical set operations like union, intersection, and difference.

Key characteristics and considerations related to sets:

  • Mutable: Sets are mutable, allowing you to modify, add, or remove elements after creation.
  • Unordered: Items in a set are not ordered, meaning there is no specific order to the elements.
  • Unique Elements: Sets only allow unique elements, and duplicate elements are automatically ignored.
  • Supports Various Data Types: Elements in a set can be of different data types.

Example of creating a set:

                    
my_set = {1, 2, 3, "apple", 3.14, True}
                    
                

Common operations on sets:

  • Adding Elements: Adding new elements to the set using add() method.
  • Removing Elements: Removing elements using remove() or discard() methods.
  • Set Operations: Performing set operations like union, intersection, and difference using methods like union(), intersection(), and difference().
  • Checking Membership: Checking if an element is present in the set using in keyword.

Example:

                    
my_set.add(4)                   # Adding element 4 to the set
my_set.remove("apple")          # Removing "apple" from the set
other_set = {2, 3, 5, "orange"}
union_result = my_set.union(other_set)          # Union of two sets
intersection_result = my_set.intersection(other_set)  # Intersection of two sets
difference_result = my_set.difference(other_set)  # Difference between two sets

print(union_result)             # Output: {1, 2, 3, 4, 5, 3.14, True, 'orange'}
print(intersection_result)      # Output: {2, 3}
print(difference_result)        # Output: {1, 4, 'apple', 3.14, True}
                    
                

Sets are useful for various tasks, such as removing duplicates from a collection, performing set operations, and checking membership in an efficient manner.

Distinguishing between list, tuple, and set.

Dictionaries in Python

A dictionary in Python is a mutable and unordered collection of key-value pairs. Dictionaries are defined by enclosing comma-separated key-value pairs within curly braces {}. Each key in a dictionary must be unique, and it is associated with a specific value.

Key characteristics and considerations related to dictionaries:

  • Mutable: Dictionaries are mutable, allowing you to modify, add, or remove key-value pairs after creation.
  • Unordered: Items in a dictionary are not ordered, meaning there is no specific order to the key-value pairs.
  • Key-Value Pairs: Data in a dictionary is stored in key-value pairs, where each key is associated with a specific value.
  • Keys Must Be Unique: Each key in a dictionary must be unique, and it provides a way to access the associated value efficiently.
  • Supports Various Data Types: Both keys and values in a dictionary can be of different data types.

Example of creating a dictionary:

                    
my_dict = {"name": "John", "age": 25, "city": "New York"}
                    
                

Common operations on dictionaries:

  • Accessing Values: Accessing values using keys.
  • Modifying Values: Modifying values associated with specific keys.
  • Adding Items: Adding new key-value pairs to the dictionary.
  • Removing Items: Removing key-value pairs using del or pop() methods.
  • Keys and Values: Retrieving keys and values separately using keys() and values() methods.

Example:

                    
print(my_dict["name"])       # Output: John
my_dict["age"] = 26           # Modifying the age
my_dict["gender"] = "Male"    # Adding a new key-value pair
del my_dict["city"]           # Removing the "city" key
print(my_dict.keys())         # Output: dict_keys(['name', 'age', 'gender'])
print(my_dict.values())       # Output: dict_values(['John', 26, 'Male'])
                    
                

Dictionaries are versatile and widely used in Python for tasks such as storing and retrieving data with meaningful labels, configuration settings, and more.

DataFrame

Creating a DataFrame:

You can create a DataFrame in Python using various methods, such as:

  1. From dictionaries.
  2. From lists.
  3. From external data sources like CSV files, SQL databases, or Excel files.
                    
pip install pandas
                    
                

Creating a DataFrame from dictionaries.

                        
import pandas as pd
# Creating a dictionary
data = {
    'Name': ['John', 'Alice', 'Bob', 'Eve'],
    'Age': [28, 24, 22, 26],
    'City': ['New York', 'San Francisco', 'Los Angeles', 'Seattle']
}

# Creating a DataFrame from the dictionary
df = pd.DataFrame(data)

# Displaying the DataFrame
print("Original DataFrame:")
print(df)
                        
                    

If we want to change the indexing of data frame then we can do the following:

                    
import pandas as pd

data = {'Name': ['John', 'Emma', 'Peter'],
        'Age': [30, 25, 35],
        'City': ['New York', 'San Francisco', 'Chicago']}
df = pd.DataFrame(data, index=['a', 'b', 'c'])
print(df.loc['a'])
                    
                

Output:

                
Name         John
Age            30
City     New York
Name: a, dtype: object
                
            

We can also perform the transpose of the DataFrame using the `.T` attribute or using the 'transpose()' function:

                    
import pandas as pd

# Create a DataFrame
data = {'Name': ['John', 'Emma', 'Peter'],
        'Age': [30, 25, 35],
        'City': ['New York', 'San Francisco', 'Chicago']}
df = pd.DataFrame(data, index=['a', 'b', 'c'])

# Transpose the DataFrame
transposed_df = df.transpose()
                    
                

Type Conversion in Python

Type conversion, also known as type casting, is the process of changing the data type of a variable from one type to another. Python provides built-in functions for performing type conversion, allowing developers to seamlessly work with different data types as needed.

Key points about type conversion in Python:

Examples of type conversion:

                
# Implicit conversion
num_int = 5
num_float = 3.14
result = num_int + num_float # Implicitly converts num_int to float before addition

# Explicit conversion
str_num = "123"
int_num = int(str_num) # Converts string to integer using int() function
float_num = float(str_num) # Converts string to float using float() function

# Conversion between sequence types
my_list = [1, 2, 3]
my_tuple = tuple(my_list) # Converts list to tuple using tuple() function
my_set = set(my_list) # Converts list to set using set() function

# Numeric type conversion
float_result = float(num_int) # Converts integer to float using float() function
int_result = int(num_float) # Converts float to integer using int() function
                
            

Command Line Arguments in Python

Command line arguments provide a way to pass information to a Python script when it is executed from the command line. These arguments are accessible within the script and can be used to customize its behavior based on user input.

Key points about command line arguments:

Example:

                
import sys

# Accessing command line arguments
script_name = sys.argv[0]
first_argument = sys.argv[1] if len(sys.argv) > 1 else None
second_argument = sys.argv[2] if len(sys.argv) > 2 else None

print("Script Name:", script_name)
print("First Argument:", first_argument)
print("Second Argument:", second_argument)
                
            

When executing the script from the command line:

                
python script.py arg1 arg2
                
            

The output would be:

                
Script Name: script.py
First Argument: arg1
Second Argument: arg2
                
            

Simple program to add two number provided through command line:

                    
import sys

num1 = int(sys.argv[1])
num2 = int(sys.argv[2])

sum = num1 + num2

print("The sum is = ", str(sum))
                    
                

When executing the script from the command line:

                
python3 test.py 5 4
                
            

Output:

                
The sum is 9
                
            

Indentation in Python

Rules of Indentation:

It's essential to adhere to these rules for maintaining readable and error-free Python code.

                    
a = "something"
# Incorrect indentation below; it will result in an error
 b = "another"
                    
                

Operators

Arithmetic Operators

  • Addition (`+`): Adds two operands.
  •                             
    a = 10
    b = 5
    result = a + b
    print(result)  # Output will be 15
                            
                        
  • Subtraction (`-`): Subtracts the second operand from the first.
  •                             
    a = 10
    b = 5
    result = a - b
    print(result)  # Output will be 5
                            
                        
  • Multiplication (`*`): Multiplies two operands.
  •                             
    a = 10
    b = 5
    result = a * b
    print(result)  # Output will be 50
                            
                        
  • Division (`/`): Divides the first operand by the second.
  •                             
    a = 10
    b = 5
    result = a / b
    print(result)  # Output will be 2.0
                            
                        
  • Modulus (`%`): Returns the remainder of the division.
  •                             
    a = 10
    b = 3
    result = a % b
    print(result)  # Output will be 1
                            
                        
  • Exponentiation (`**`): Raises the first operand to the power of the second.
  •                             
    a = 2
    b = 3
    result = a ** b
    print(result)  # Output will be 8
                            
                        
  • Floor Division (`//`): Performs integer division and returns the floor value.
  •                             
    a = 10
    b = 3
    result = a // b
    print(result)  # Output will be 3
                            
                        

Comparison Operators

  • Equal (`==`): Returns True if both operands are equal.
  •                         
    a = 10
    b = 10
    result = a == b
    print(result)  # Output will be True
                        
                    
  • Not Equal (`!=`): Returns True if operands are not equal.
  •                         
    a = 10
    b = 5
    result = a != b
    print(result)  # Output will be True
                        
                    
  • Greater Than (`>`): Returns True if the left operand is greater than the right.
  •                         
    a = 10
    b = 5
    result = a > b
    print(result)  # Output will be True
                        
                    
  • Less Than (`<`): Returns True if the left operand is less than the right.
  •                                 
    a = 5
    b = 10
    result = a < b
    print(result)  # Output will be True
                                
                            
  • Greater Than or Equal To (`>=`): Returns True if the left operand is greater than or equal to the right.
  •                         
    a = 10
    b = 10
    result = a >= b
    print(result)  # Output will be True
            
        
  • Less Than or Equal To (`<=`): Returns True if the left operand is less than or equal to the right.
  •                                 
    a = 5
    b = 10
    result = a <= b
    print(result)  # Output will be True
            
        

Logical Operators

  • In Python, `&&`, `||`, and `!` are not used for logical operations like in some other programming languages like C or Java. Instead, Python uses `and`, `or`, and `not` for logical operations.

and

  • The `and` operator returns True if both operands are True, otherwise, it returns False.
                        
x = 5
y = 10
z = 15
result = (x < y) and (y < z)
print(result)  # Output will be True
        
    

or

  • The `or` operator returns True if at least one of the operands is True, otherwise, it returns False.
                        
x = 5
y = 10
z = 15
result = (x < y) or (x > z)
print(result)  # Output will be True
        
    

not

  • The `not` operator is used to negate the value of a boolean expression. It returns True if the expression is False, and False if the expression is True.
                        
x = 5
y = 10
result = not (x > y)
print(result)  # Output will be True
        
    

Bitwise Operators

  • Bitwise AND (`&`): Sets each bit to 1 if both bits are 1.
  •                         
    a = 10  # 1010 in binary
    b = 4   # 0100 in binary
    result = a & b
    print(result)  # Output will be 0
            
        
  • Bitwise OR (`|`): Sets each bit to 1 if one of the two bits is 1.
  •                         
    a = 10  # 1010 in binary
    b = 4   # 0100 in binary
    result = a | b
    print(result)  # Output will be 14
            
        
  • Bitwise XOR (`^`): Sets each bit to 1 if only one of the two bits is 1.
  •                         
    a = 10  # 1010 in binary
    b = 4   # 0100 in binary
    result = a ^ b
    print(result)  # Output will be 14
            
        
  • Bitwise NOT (`~`): Inverts all the bits.
  •                         
    a = 10  # 1010 in binary
    result = ~a
    print(result)  # Output will be -11
            
        
  • Bitwise Left Shift (`<<`): Shifts bits to the left by a specified number of positions.
  •                                 
    a = 10  # 1010 in binary
    result = a << 1
    print(result)  # Output will be 20
            
        
  • Bitwise Right Shift (`>>`): Shifts bits to the right by a specified number of positions.
  •                         
    a = 10  # 1010 in binary
    result = a >> 1
    print(result)  # Output will be 5
            
        

Assignment Operators

  • Assignment (`=`): Assigns a value to a variable.
  •                         
    a = 10
    print(a)  # Output will be 10
            
        
  • Add and Assign (`+=`): Adds a value to a variable and assigns the result to the variable.
  •                         
    a = 10
    a += 5
    print(a)  # Output will be 15
            
        
  • Subtract and Assign (`-=`): Subtracts a value from a variable and assigns the result to the variable.
  •                         
    a = 10
    a -= 5
    print(a)  # Output will be 5
            
        
  • Multiply and Assign (`*=`): Multiplies a variable by a value and assigns the result to the variable.
  •                         
    a = 10
    a *= 5
    print(a)  # Output will be 50
            
        
  • Divide and Assign (`/=`): Divides a variable by a value and assigns the result to the variable.
  •                         
    a = 10
    a /= 5
    print(a)  # Output will be 2.0
            
        
  • Modulus and Assign (`%=`): Takes modulus using a value and assigns the result to the variable.
  •                         
    a = 10
    a %= 3
    print(a)  # Output will be 1
            
        
  • Exponentiation and Assign (`**=`): Raises a variable to the power of a value and assigns the result to the variable.
  •                         
    a = 2
    a **= 3
    print(a)  # Output will be 8
            
        
  • Floor Division and Assign (`//=`): Performs floor division using a value and assigns the result to the variable.
  •                         
    a = 10
    a //= 3
    print(a)  # Output will be 3