Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

Introduction To Python

Python was invented in 1991 by Guido van Rossum and named after Monty Python. Python is a high-level, interpreted programming language that is popular for data analysis and machine learning due to its large library of specialized libraries and suitability for these tasks. Variables in Python can hold different data types like integers, floats, strings, booleans, lists, tuples, dictionaries and more.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Introduction To Python

Python was invented in 1991 by Guido van Rossum and named after Monty Python. Python is a high-level, interpreted programming language that is popular for data analysis and machine learning due to its large library of specialized libraries and suitability for these tasks. Variables in Python can hold different data types like integers, floats, strings, booleans, lists, tuples, dictionaries and more.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

What is Python?

 Python was invented in 1991 by a Dutch programmer named Guido van Rossum

 He named it after the television show “Monty Python’s Flying Circus”

 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

 There are two types of high-level languages

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

Example of Machine Language:

Why Python?
 Python is considered a very “readable” language because the logic is often apparent and English-
like in the code itself

 Because Python is an interpreted language, we need to install a Python interpreter when we


want to install the language

 Python is very popular for three reasons:

 It is relatively easy to understand


 It has a HUGE number of specialized libraries
 It is particularly well-suited to data analysis and machine learning
Variables:
In Python, variables are used to store and manage data. A variable is essentially a name given to a
memory location where you can store values. You can think of a variable as a container that holds
information. Here's a brief explanation with examples:

Variable Naming Rules:

 Variable names in Python can include letters, numbers, and underscores but cannot start with a
number.

 Variable names are case-sensitive, so `myVariable` and `myvariable` are different.

 Python has some reserved words (keywords) that cannot be used as variable names.

Example 1: Assigning Values to Variables

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)

Example 2: Variable Types

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):

 Whole numbers without any decimal point.

 Example: x = 5

 Floats (float):

 Numbers with decimal points or numbers written in scientific notation.

 Example: y = 3.14

 Strings (str):

 Sequences of characters, enclosed in single or double quotes.

 Example: name = "Alice"

 Booleans (bool):

 Represents truth values True or False.

 Example: is_student = True

 Lists (list):

 Ordered and mutable sequences of values, typically of the same type.

 Example: numbers = [1, 2, 3, 4, 5]

 Tuples (tuple):

 Ordered and immutable sequences of values.

 Example: coordinates = (3, 4)

 Sets (set):

 Unordered collections of unique values.

 Example: unique_numbers = {1, 2, 3, 4, 5}

 Dictionaries (dict):

 Unordered collections of key-value pairs.

 Example: person = {'name': 'Bob', 'age': 30, 'city': 'New York'}

 NoneType (None):

 Represents the absence of a value or a null value.


 Example: result = 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]

every_second = numbers[::2] # Every second element


print (every_second) # Output: [1, 3, 5]

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:

Lists come with several built-in methods for common operations.

# 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]

# Count occurrences of an element


count_2 = numbers.count(2)
print (count_2) # Output: 1

List Comprehensions:

List comprehensions provide a concise way to create lists.

# List comprehension to create a list of squares


squares = [x**2 for x in numbers]
print (squares) # Output: [25, 16, 9, 4, 1]

Nested Lists:

Lists can contain other lists, forming nested structures.

# Nested lists
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print (matrix[1][2]) # Output: 6

Adding Elements:

 Append: Adds an element to the end of the list.

fruits = ["apple", "orange", "banana"]


fruits.append("grape")
print (fruits) # Output: ["apple", "orange", "banana", "grape"]
 Insert: Inserts an element at a specific position in the list.

numbers = [1, 2, 3, 4, 5]
numbers.insert(2, 100)
print (numbers) # Output: [1, 2, 100, 3, 4, 5]

Concatenating Lists:

It allows us to combine two or more 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:

 Copy: It creates a shallow copy of the list.

original_list = [1, 2, 3]
copied_list = original_list.copy()

 List comprehension for copying: Another way to create a copy.

original_list = [1, 2, 3]
copied_list = [x for x in original_list]

Removing Elements:

 Remove: Removes the first occurrence of a specified element.

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.

fruits = ["apple", "orange", "banana"]


removed_fruit = fruits.pop(1)
print (removed_fruit) # Output: "orange"
print (fruits) # Output: ["apple", "banana"]

 Clearing a List: Removes all elements from the list.


numbers = [1, 2, 3, 4, 5]
numbers.clear()
print (numbers) # Output: []

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:

Tuples support indexing and slicing, similar to lists.

# 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:

 len(): Returns the number of elements in a tuple.

# Length of a tuple
length = len(my_tuple)
print (length) # Output: 5

 Concatenating Tuples (+):

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.

# Attempting to modify a tuple (will raise an error)


my_tuple[0] = 100
# Raises TypeError: 'tuple' object does not support item assignment

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'}

Keys and values can be of any data type.

Accessing Elements:

You can access values in a dictionary using keys.

# Accessing values
print (my_dict['name']) # Output: 'John'
print (my_dict['age']) # Output: 25

Dictionary Methods:

 len(): Returns the number of key-value pairs in the dictionary.


# Length of a dictionary

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()

print (keys_list)# Output: dict_keys(['name', 'age', 'city'])


print (values_list) # Output: dict_values(['John', 25, 'New York'])
print (items_list)
# Output: dict_items([('name', 'John'), ('age', 25), ('city', 'New York')])

Modifying Dictionaries:

 Updating Values: Modifying values for existing keys.

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

# Adding new key-value pairs


my_dict['occupation'] = 'Engineer'
print (my_dict)
# Output: {'name': 'John', 'age': 26, 'city': 'New York', 'occupation':
'Engineer'}

 Removing Key-Value Pairs: Removing key-value pairs using the `del` keyword or the `pop()`
method.

# Removing key-value pairs

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.

# Arithmetic Operators Example

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

# Comparison Operators Example

# 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

# Greater Than or Equal To


result_greater_than_equal = (8 >= 8)
print (f"Greater Than or Equal To: {result_greater_than_equal}") # Output:
True

# Less Than or Equal To


result_less_than_equal = (4 <= 5)
print (f"Less Than or Equal To: {result_less_than_equal}") # Output: True

3. Logical Operators: Logical operators perform logical operations on Boolean values.

# Logical Operators Example

# 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

# Logical AND and OR Example

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

4. Assignment Operators: Assignment operators are used to assign values to variables.

# Assignment Operators Example

# 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

5. Membership Operators: Membership operators test for membership in a sequence.

# Membership Operators Example

# 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:

1. Parentheses (): Highest precedence.


2. Exponentiation **: Right-to-left associativity.
3. Positive +, Negative - (Unary Operators): Right-to-left associativity.
4. Multiplication *, Division /, Floor Division //, Modulus %: Left-to-right associativity.
5. Addition +, Subtraction -: Left-to-right associativity.
6. Comparison Operators (<, <=, >, >=, ==, !=): Left-to-right associativity.
7. Logical NOT: Right-to-left associativity.
8. Logical AND: Left-to-right associativity.
9. Logical OR: Left-to-right associativity.
input () function:

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.

# Example using input ()


name = input ("Enter your name: ")
print (“Hello, " + name + "!")

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.

# Example using if statement


age = int(input ("Enter your age: "))

if age >= 18:


print (“You are an adult.")
else:
print (“You are a minor.")

In this example, the program checks if the entered age is greater than or equal to 18 and prints a
message accordingly.

score = int(input ("Enter your exam score: "))

if score >= 90:


print ("Grade: A")
elif score >= 80:
print ("Grade: B")
elif score >= 70:
print ("Grade: C")
elif score >= 60:
print ("Grade: D")
else:
print ("Grade: F")

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.

# Example using for loop


fruits = ["apple", "banana", "orange"]

for fruit in fruits:


print (f"I like {fruit}s.")

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.

# Example using while loop


count = 1
while count <= 5:
print (f"Count: {count}")
count += 1

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.

You might also like