0% found this document useful (0 votes)
3 views11 pages

unit-1 python

The document provides an introduction to programming languages, focusing on Python, which is a high-level, versatile language known for its ease of use and extensive libraries. It covers Python's history, installation, data types, and key features such as dynamic typing, lists, tuples, sets, and dictionaries. Additionally, it explains how to create, manipulate, and iterate over these data structures in Python.

Uploaded by

pragati8333
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
3 views11 pages

unit-1 python

The document provides an introduction to programming languages, focusing on Python, which is a high-level, versatile language known for its ease of use and extensive libraries. It covers Python's history, installation, data types, and key features such as dynamic typing, lists, tuples, sets, and dictionaries. Additionally, it explains how to create, manipulate, and iterate over these data structures in Python.

Uploaded by

pragati8333
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 11

Introduction to Programming Languages

Definition: Programming languages are formal languages used to communicate instructions to a


computer. They allow us to write programs that perform specific tasks.

Examples: C, C++, Java, Python, etc.

Python as a Programming Language

Definition: Python is a high-level, interpreted, and versatile programming language.

1. Easy to learn and use.

2. Open-source with a vast community.

3. Supports multiple programming paradigms (procedural, object-oriented, and


functional).

4. Extensive standard libraries.

Applications: Web development, data analysis, AI, scientific computing, etc.

History of Python-Developed by Guido van Rossum in 1991.Inspired by ABC, a teaching language.

Python 2 released in 2000; Python 3 in 2008 with major changes.

Python Versions

Python 2.x: Deprecated but used in legacy projects.

Python 3.x: Actively maintained and recommended for new projects.

Python Installation

1. Download: Visit the Python website.

2. Install: Follow on-screen instructions for your operating system.

Environmental Variables

Definition: Variables that determine the behaviour of the operating system.

Enable access to Python from the command line.

Environmental Variables in Windows

1. Access: Control Panel > System > Advanced System Settings > Environment Variables.

2. Add Python Path: Add the path to the Python executable to the Path variable.

Executing Python from the Command Line

Open the command prompt.

Type python or python3 (depending on your installation).

Example:

python --version

Invoking Python IDLE


IDLE: Integrated Development and Learning Environment for Python.

Run Python code interactively.

Access via Start Menu or command idle.

Getting Help

Use the help() function.

Example:

help(print)

Dynamic Typing

Definition: Python variables can change types during execution.

x = 10

x = "Hello" # Changes type to string

Python Reserved Words

Definition: Keywords reserved by Python for specific purposes.

Examples: if, else, while, def, class, etc.

Naming Conventions

Rules:

Use meaningful names.

Begin with a letter or underscore.

Avoid Python keywords.

student_name = "John"

_age = 21

Character Set

Includes letters, digits, special symbols, and whitespaces.

Comments

Definition: Lines ignored by the Python interpreter.

Types:

Single-line: # This is a comment

Multi-line: '''This is a multi-line comment'''

Identifiers

Definition: Names for variables, functions, classes, etc.

Rules:
Start with a letter or _.

No spaces or special characters.

Data Types

Numeric: int, float, complex

Text: str

Boolean: bool

Sequence: list, tuple

Mapping: dict

Example:

x = 10 # int

y = 3.14 # float

z = "Hello" # str

Operators

Arithmetic: +, -, *, /

Comparison: ==, !=, >, <

Logical: and, or, not

Type Conversions

Convert between types using functions like int(), float(), str().

Example:

x = "123"

print(int(x) + 1)

String Methods

Common Methods:

o lower(), upper(), strip(), split().

Example:

name = " John Doe "

print(name.strip())

Output Formatting with format

name = "John"

age = 25
print("My name is {} and I am {} years old".format(name, age))

Mutable vs Immutable Objects

Mutable: Can be changed (e.g., list).

Immutable: Cannot be changed (e.g., str, tuple).

Python Lists

In Python, a list is a built-in dynamic sized array (automatically grows and shrinks) that is
used to store an ordered collection of items. We can store all types of items (including
another list) in a list. A list may contain mixed type of items, this is possible because a list
mainly stores references at contiguous locations and actual items maybe stored at different
locations.

Creating a List

Here are some common methods to create a list:

Using Square Brackets

# List of integers

a = [1, 2, 3, 4, 5]

# List of strings

b = ['apple', 'banana', 'cherry']

# Mixed data types

c = [1, 'hello', 3.14, True]

print(a)

print(b)

print(c)

Output

[1, 2, 3, 4, 5]

['apple', 'banana', 'cherry']

[1, 'hello', 3.14, True]

Using the list() Constructor

We can also create a list by passing an iterable (like a string, tuple, or another list) to
the list() function.

# From a tuple

a = list((1, 2, 3, 'apple', 4.5))


print(a)

Adding Elements into List

We can add elements to a list using the following methods:

 append(): Adds an element at the end of the list.

 extend(): Adds multiple elements to the end of the list.

 insert(): Adds an element at a specific position.

Python

Removing Elements from List

We can remove elements from a list using:

 remove(): Removes the first occurrence of an element.

 pop(): Removes the element at a specific index or the last element if no index is specified.

 del statement: Deletes an element at a specified index.

Python

Iterating Over Lists

We can iterate the Lists easily by using a for loop or other iteration methods. Iterating over
lists is useful when we want to do some operation on each item or access specific items
based on certain conditions. Let’s take an example to iterate over the list using for loop.

Using for Loop

a = ['apple', 'banana', 'cherry']

# Iterating over the list

for item in a:

print(item)

Tuples in Python

Python Tuple is a collection of objects separated by commas. A tuple is similar to a Python


list in terms of indexing, nested objects, and repetition but the main difference between
both is Python tuple is immutable, unlike the Python list which is mutable.

# Note : In case of list, we use square # brackets []. Here we use round brackets ()

t = (10, 20, 30)


print(t)

print(type(t))

What is Immutable in Tuples?

Unlike Python lists, tuples are immutable. Some Characteristics of Tuples in Python.

Like Lists, tuples are ordered and we can access their elements using their index values

We cannot update items to a tuple once it is created.

Tuples cannot be appended or extended.

We cannot remove items from a tuple once it is created.

t = (1, 2, 3, 4, 5)

# tuples are indexed

print(t[1])

print(t[4])

# tuples contain duplicate elements

t = (1, 2, 3, 4, 2, 3)

print(t)

# updating an element

t[1] = 100

print(t)

Different Operations Related to Tuples

Below are the different operations related to tuples in Python:

Traversing

Concatenation

Nesting

Repetition

Slicing

Deleting

Finding the length

Multiple Data Types with tuples

Conversion of lists to tuples

Tuples in a Loop

Different Ways of Creating a Tuple


Using round brackets

Without Brackets

Tuple Constructor

Empty Tuple

Single Element Tuple

Using Tuple Packing

Sets in Python

A Set in Python programming is an unordered collection data type that is iterable and has no
duplicate elements. While sets are mutable, meaning you can add or remove elements after
their creation, the individual elements within the set must be immutable and cannot be
changed directly.

Set are represented by { } (values enclosed in curly braces)

The major advantage of using a set, as opposed to a list, is that it has a highly optimized
method for checking whether a specific element is contained in the set. This is based on a
data structure known as a hash table. Since sets are unordered, we cannot access items
using indexes as we do in lists.

var = {"Geeks", "for", "Geeks"}

type(var)

# typecasting list to set

myset = set(["a", "b", "c"])

print(myset)

# Adding element to the set

myset.add("d")

print(myset)

{'c', 'b', 'a'}


{'d', 'c', 'b', 'a'}

Python Frozen Sets

Frozen sets in Python are immutable objects that only support methods and operators that
produce a result without affecting the frozen set or sets to which they are applied. It can be
done with frozenset() method in Python.

While elements of a set can be modified at any time, elements of the frozen set remain the
same after creation.

If no parameters are passed, it returns an empty frozenset.

# Python program to demonstrate differences


# between normal and frozen set

# Same as {"a", "b","c"}

normal_set = set(["a", "b","c"])

print("Normal Set")

print(normal_set)

# A frozen set

frozen_set = frozenset(["e", "f", "g"])

print("\nFrozen Set")

print(frozen_set)

Methods for Sets

Adding elements to Python Sets

Insertion in the set is done through the set.add() function, where an appropriate record
value is created to store in the hash table. Same as checking for an item, i.e., O(1) on
average. However, in worst case it can become O(n).

Union operation on Python Sets-Two sets can be merged using union() function or |
operator. Both Hash Table values are accessed and traversed with merge operation perform
on them to combine the elements, at the same time duplicates are removed. The Time
Complexity of this is O(len(s1) + len(s2)) where s1 and s2 are two sets whose union needs to
be done.

Intersection operation on Python Sets- This can be done through intersection() or &
operator. Common Elements are selected. They are similar to iteration over the Hash lists
and combining the same values on both the Table. Time Complexity of this is O(min(len(s1),
len(s2)) where s1 and s2 are two sets whose union needs to be done.

Operators for Sets

Sets and frozen sets support the following operators:

Operators Notes

key in s containment check


Operators Notes

key not in s non-containment check

s1 == s2 s1 is equivalent to s2

s1 != s2 s1 is not equivalent to s2

s1 <= s2 s1 is subset of s2

s1 < s2 s1 is proper subset of s2

s1 >= s2 s1 is superset of s2

s1 > s2 s1 is proper superset of s2

s1 | s2 the union of s1 and s2

s1 & s2 the intersection of s1 and s2

s1 – s2 the set of elements in s1 but not s2

s1 ˆ s2 the set of elements in precisely one of s1 or s2

Dictionaries in Python

A Python dictionary is a data structure that stores the value in key: value pairs. Values in a
dictionary can be of any data type and can be duplicated, whereas keys can’t be repeated
and must be immutable.
Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier to
find values.

Python dictionaries are essential for efficient data mapping and manipulation in
programming. To deepen your understanding of dictionaries and explore advanced
techniques in data handling, consider enrolling in our Complete Machine Learning & Data
Science Program. This course covers everything from basic dictionary operations to
advanced data processing methods, empowering you to become proficient in Python
programming and data analysis.

Create a Dictionary

In Python, a dictionary can be created by placing a sequence of elements within


curly {} braces, separated by a ‘comma’.

# create dictionary using { }

d1 = {1: 'Geeks', 2: 'For', 3: 'Geeks'}

print(d1)

# create dictionary using dict() constructor

d2 = dict(a = "Geeks", b = "for", c = "Geeks")

print(d2)

Accessing Dictionary Items

We can access a value from a dictionary by using the key within square brackets
or get() method.

Adding and Updating Dictionary Items

We can add new key-value pairs or update existing keys by using assignment.

Removing Dictionary Items

We can remove items from dictionary using the following methods:

del: Removes an item by key.

pop(): Removes an item by key and returns its value.

clear(): Empties the dictionary.

popitem(): Removes and returns the last key-value pair.

Iterating Through a Dictionary

We can iterate over keys [using keys() method] , values [using values() method] or both
[using item() method] with a for loop.

d = {1: 'Geeks', 2: 'For', 'age':22}

# Iterate over keys


for key in d:

print(key)

# Iterate over values

for value in d.values():

print(value)

# Iterate over key-value pairs

for key, value in d.items():

print(f"{key}: {value}")

You might also like