Introduction To Python
Introduction To Python
Python was invented in 1991 by a Dutch programmer named Guido van Rossum
Python is:
a high-level language
an interpreted language
High-level Languages
High level-languages provide a higher level of abstraction from machine language
Consequently, high-level languages are easier for humans to read and understand
Complied languages: translated entirely into machine code before execution (C,C++, Fortran,
etc.).
Interpreted languages: translated line by line during execution (Python, R, Java, Ruby,
etc.)
Why Python?
Python is considered a very “readable” language because the logic is often apparent and English-
like in the code itself
Variable names in Python can include letters, numbers, and underscores but cannot start with a
number.
Python has some reserved words (keywords) that cannot be used as variable names.
name = "John"
age = 25
height = 1.75
is_student = False
# Printing variables
print (“Name:", name)
print (“Age:", age)
print (“Height:", height)
print (“Is Student:", is_student)
Python is dynamically typed, meaning you don't need to explicitly declare the data type of a variable.
The interpreter infers the type based on the assigned value.
# Dynamic typing
variable1 = 10 # Integer
variable2 = "Hello" # String
variable3 = 3.14 # Float
variable4 = True # Boolean
# Checking types
print (type(variable1)) # <class 'int'>
print (type(variable2)) # <class 'str'>
print (type(variable3)) # <class 'float'>
print (type(variable4)) # <class 'bool'>
Data Type:
In Python, variables can belong to different data types. Here are some of the common variable types:
Integers (int):
Example: x = 5
Floats (float):
Example: y = 3.14
Strings (str):
Booleans (bool):
Lists (list):
Tuples (tuple):
Sets (set):
Dictionaries (dict):
NoneType (None):
Lists:
In Python, a list is a mutable (we are allowed to change it), ordered sequence of elements. Lists are one
of the most commonly used data structures, and they allow you to store and manipulate collections of
items. Elements within a list can be of any data type, and a list can contain elements of different types.
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "orange", "banana"]
mixed_list = [1, "hello", 3.14, True]
Accessing Elements:
You can access individual elements in a list using indexing. Indexing starts from 0 for the first element.
# Accessing elements
print (numbers[0]) # Output: 1
print (fruits[1]) # Output: "orange"
print (mixed_list[2]) # Output: 3.14
Slicing:
You can extract a portion of a list using slicing. The syntax is `list[start:stop:step]`.
# Slicing
subset = numbers[1:4] # Elements at index 1, 2, and 3
print (subset) # Output: [2, 3, 4]
Modifying Lists:
Lists are mutable, meaning you can change their contents after creation.
# Modifying elements
fruits[0] = "pear"
print (fruits) # Output: ["pear", "orange", "banana"]
# Adding elements
fruits.append("grape")
print (fruits) # Output: ["pear", "orange", "banana", "grape"]
# Removing elements
fruits.remove("orange")
print (fruits) # Output: ["pear", "banana", "grape"]
List Methods:
# Length of a list
length = len(numbers)
print (length) # Output: 5
# Sorting a list
numbers.sort()
print (numbers) # Output: [1, 2, 3, 4, 5]
# Reversing a list
numbers.reverse()
print (numbers) # Output: [5, 4, 3, 2, 1]
List Comprehensions:
Nested Lists:
# Nested lists
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print (matrix[1][2]) # Output: 6
Adding Elements:
numbers = [1, 2, 3, 4, 5]
numbers.insert(2, 100)
print (numbers) # Output: [1, 2, 100, 3, 4, 5]
Concatenating Lists:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print (combined_list) # Output: [1, 2, 3, 4, 5, 6]
Copying Lists:
original_list = [1, 2, 3]
copied_list = original_list.copy()
original_list = [1, 2, 3]
copied_list = [x for x in original_list]
Removing Elements:
numbers = [1, 2, 3, 4, 3, 5]
numbers.remove(3)
print (numbers) # Output: [1, 2, 4, 3, 5]
Pop: Removes and returns the element at a specified index. If no index is specified, it removes
the last element.
Tuple:
A tuple is an immutable, ordered collection of elements. Unlike lists, once a tuple is created, its contents
cannot be modified. Tuples are defined by enclosing a comma-separated sequence of elements within
parentheses ().
Creating Tuples:
# Creating a tuple
my_tuple = (1, 2, 3, 'hello', 3.14)
Tuples can contain elements of different types, including numbers, strings, and other tuples.
Accessing Elements:
# Accessing elements
print (my_tuple[0]) # Output: 1
print (my_tuple[3]) # Output: 'hello'
print (my_tuple[1:4]) # Output: (2, 3, 'hello')
Tuple Methods:
# Length of a tuple
length = len(my_tuple)
print (length) # Output: 5
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')
concatenated_tuple = tuple1 + tuple2
print (concatenated_tuple) # Output: (1, 2, 3, 'a', 'b', 'c')
Tuple Unpacking: Allows you to assign the elements of a tuple to individual variables.
my_tuple = (10, 20, 30)
a, b, c = my_tuple
print (a, b, c) # Output: 10 20 30
Immutable Nature: Tuples are immutable, meaning their elements cannot be modified once the
tuple is created.
Use Cases:
Tuples are often used when the order and structure of the elements are important and should remain
constant.
They are commonly used for returning multiple values from a function.
Dictionary
A dictionary is a mutable, unordered collection of key-value pairs. Each key in a dictionary must be
unique, and it is associated with a specific value. Dictionaries are defined by enclosing key-value pairs
within curly braces `{}`.
Creating Dictionaries:
# Creating a dictionary
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
Accessing Elements:
# Accessing values
print (my_dict['name']) # Output: 'John'
print (my_dict['age']) # Output: 25
Dictionary Methods:
length = len(my_dict)
print (length) # Output: 3
keys(), values(), items(): Returns lists of keys, values, and key-value pairs, respectively.
keys_list = my_dict.keys()
values_list = my_dict.values()
items_list = my_dict.items()
Modifying Dictionaries:
# Updating values
my_dict['age'] = 26
print (my_dict) # Output: {'name': 'John', 'age': 26, 'city': 'New York'}
Adding New Key-Value Pairs: Adding new key-value pairs to the dictionary.
Removing Key-Value Pairs: Removing key-value pairs using the `del` keyword or the `pop()`
method.
del my_dict['city']
print (my_dict)
# Output: {'name': 'John', 'age': 26, 'occupation': 'Engineer'}
popped_value = my_dict.pop('age')
print (popped_value) # Output: 26
print (my_dict) # Output: {'name': 'John', 'occupation': 'Engineer'}
Use pop() when you want to retrieve the value of the removed key.
Use del when you want to remove a key without caring about the value.
If there's a chance that the key might not exist, pop() allows you to specify a default value to
return in such cases.
Use Cases:
Dictionaries are useful for representing structured data with named fields.
They are commonly used for configuration settings, JSON-like data, and more.
Efficient for looking up values using unique keys.
Operations:
1. Arithmetic Operators: Arithmetic operators perform basic mathematical operations.
# Addition
result_addition = 5 + 3
print (f"Addition: {result_addition}") # Output: 8
# Subtraction
result_subtraction = 7 - 2
print (f"Subtraction: {result_subtraction}") # Output: 5
# Multiplication
result_multiplication = 4 * 6
print (f"Multiplication: {result_multiplication}") # Output: 24
# Division
result_division = 9 / 3
print (f"Division: {result_division}") # Output: 3.0 (float division)
# Floor Division
result_floor_division = 10 // 3
print (f"Floor Division: {result_floor_division}") # Output: 3 (integer
division)
# Modulus
result_modulus = 10 % 3
print (f"Modulus: {result_modulus}") # Output: 1 (remainder of the division)
# Exponentiation
result_exponentiation = 2 ** 3
print (f"Exponentiation: {result_exponentiation}") # Output: 8
2. Comparison Operators: Comparison operators compare two values and return a Boolean result
True or False.
# Equal
result_equal = (5 == 5)
print (f"Equal: {result_equal}") # Output: True
# Not Equal
result_not_equal = (5 != 3)
print (f"Not Equal: {result_not_equal}") # Output: True
# Greater Than
result_greater_than = (7 > 5)
print (f"Greater Than: {result_greater_than}") # Output: True
# Less Than
result_less_than = (3 < 5)
print (f"Less Than: {result_less_than}") # Output: True
# Logical AND
result_logical_and = (True and False)
print (f"Logical AND: {result_logical_and}") # Output: False
# Logical OR
result_logical_or = (True or False)
print (f"Logical OR: {result_logical_or}") # Output: True
# Logical NOT
result_logical_not = not True
print (f"Logical NOT: {result_logical_not}") # Output: False
x = -5
y = 10
# Logical AND
result_and = (x > 0) and (y < 20)
print (f"Logical AND: (x > 0) and (y < 20) -> {result_and}") # Output: True
# Logical OR
result_or = (x < 0) or (y > 15)
print (f"Logical OR: (x < 0) or (y > 15) -> {result_or}") # Output: False
# Assignment
x = 10
print (f"Assignment: x = {x}") # Output: x = 10
# Addition Assignment
x += 5
x = x+5
print (f"Addition Assignment: x += 5 -> x = {x}") # Output: x = 15
# Subtraction Assignment
y = 8
y -= 3
print (f"Subtraction Assignment: y -= 3 -> y = {y}") # Output: y = 5
# Multiplication Assignment
z = 4
z *= 2
print (f"Multiplication Assignment: z *= 2 -> z = {z}") # Output: z = 8
# Division Assignment
w = 20
w /= 4
print (f"Division Assignment: w /= 4 -> w = {w}") # Output: w = 5.0
# In Operator
my_list = ['apple', 'banana', 'orange']
result_in = ('banana' in my_list)
print (f"In Operator: 'banana' in {my_list} -> {result_in}") # Output: True
# Not In Operator
result_not_in = ('grape' not in my_list)
print (f"Not In Operator: 'grape' not in {my_list} -> {result_not_in}") #
Output: True
Order of Precedence:
Python follows the same precedence rules for its mathematical operators that mathematics does.
Parentheses have the highest precedence and can be used to force an expression to evaluate in the
order you want. Since expressions in parentheses are evaluated first:
The order of precedence in Python defines the sequence in which operators are evaluated in an
expression. Operators with higher precedence are evaluated first. If operators have the same
precedence, their evaluation order is determined by the associativity, which can be left-to-right or right-
to-left.
Here's a general overview of the order of precedence for some common operators in Python:
The input () function is used to take user input. It waits for the user to enter some data and returns the
entered value as a string.
In this example, the program prompts the user to enter their name, and the entered value is stored in
the name variable.
if statement:
The if statement is used for conditional execution. It executes a block of code only if a specified condition
is true.
In this example, the program checks if the entered age is greater than or equal to 18 and prints a
message accordingly.
In this example, the program checks the exam score and assigns a grade based on different ranges using
if, elif (else if), and else statements. The elif statements allow for multiple conditions to be checked
sequentially.
Practice:
Write a program that takes two numbers and an arithmetic operation (addition,
subtraction, multiplication, or division) as input. Perform the requested operation and
display the result.
Write a program that takes the temperature in Celsius as input and classifies it into
different categories: "Hot," "Moderate," or "Cold."
for loop:
The for loop is used to iterate over a sequence (such as a list, tuple, or string) or other iterable objects.
In this example, the for loop iterates over the list of fruits and prints a message for each fruit.
Practice:
Write a program that calculates the sum of numbers from 1 to a user-specified limit.
Write a program that calculates the factorial of a user-specified number.
while loop:
The while loop is used to repeatedly execute a block of code as long as a specified condition is true.
In this example, the while loop prints the value of count and increments it until count is no longer less
than or equal to 5.
These examples provide a basic understanding of how to use input (), if statements, for loops, and while
loops in Python. They are fundamental constructs that are frequently used in various Python programs.
Practice:
Use while to write a program that calculates the sum of numbers from 1 to a user-
specified limit.
Use while to write a program that calculates the factorial of a user-specified number.