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

Python Programming Language Overview

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views11 pages

Python Programming Language Overview

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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 [Link] 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([Link]())

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

[Link]("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 [Link]() 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 [Link]():

print(value)

# Iterate over key-value pairs

for key, value in [Link]():

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

Common questions

Powered by AI

List comprehensions in Python execute over an entire list at once, which can lead to substantial memory usage when processing large datasets as it constructs a new list in memory . While list comprehensions are generally faster than traditional loops due to optimization, they may not be suitable for very large data sets where memory overhead is a concern. Conversely, generator expressions evaluate lazily, yielding items one at a time as they are requested, which significantly reduces memory usage and allows handling of large data streams efficiently without storing entire lists in memory . However, this lazy evaluation can also introduce slight execution speed delays as items are produced on-demand instead of being fully precomputed .

A Python programmer might choose a set over a list or tuple when the primary operations involve checking for membership, removing duplicates, and when order is not important since sets are unordered collections . Sets are highly efficient for membership tests due to their implementation using hash tables, leading to average-case time complexities of O(1) for operations like add() and check for item existence, whereas in lists these operations are O(n) due to linear search . If elements need to be unique and order is not a concern, sets are more efficient than lists or tuples. However, if order or element access by index is required, lists or tuples are preferred despite their potential for slower membership tests .

Mutable objects in Python, such as lists, can be changed after their creation; they allow elements to be added, removed, or altered using methods like append() and remove(). Immutable objects, like tuples and strings, cannot be changed once created; this means any operation that modifies them results in a new object being created instead of altering the existing one . The implications for programming involve efficiency and safety: mutable objects can lead to unexpected side effects if changed unexpectedly, whereas immutable objects are safer to use in multi-threaded environments because they don't change state .

Dictionaries and sets in Python handle operations differently due to their underlying implementations. Dictionaries store data in key-value pairs and allow efficient retrieval of values through keys, with average time complexity of O(1) for retrieval . Sets, which are based on hash tables, provide operations like union and intersection that efficiently combine or compare elements between sets. The union operation in sets is completed using the | operator or union() method, with a time complexity of O(len(s1) + len(s2)). Intersection (using & or intersection()) can compare elements with a time complexity of O(min(len(s1), len(s2))). These operations leverage hash table efficiencies, unlike lists or tuples where such capabilities would require manual iterations, impacting efficiency .

Python lists offer dynamic resizing and the ability to store items of different types, providing flexibility in usage . This comes with a performance cost; lists consume more memory as they store references to objects and can adjust size dynamically. Operations on lists, like appending, may have a higher performance overhead due to the need for dynamic resizing, averaging to amortized O(1) for appends . Tuples are immutable and typically use less memory than lists because they are fixed in size and typically have a slightly faster lookup time as they need fewer indirections, though this difference is negligible in many applications . However, their immutability can also be a drawback when frequent modifications are necessary, forcing recreations of the tuple .

Python's philosophy of 'Readability counts' is evident in its consistent and clear syntax which emphasizes readability and reduces the complexity of code . This includes the use of whitespace indentation to define code blocks instead of brackets or semicolons, making the code look cleaner and reducing syntax errors . Naming conventions encourage descriptive variable names, which contributes to understandable code . The language's vast standard library, with intuitive modules and functions, also supports readability by providing simple and readable solutions to complex problems . Thus, these elements collectively ensure that Python code is easy to read and understand, aligning with the language's design principles.

Python's standard libraries play a crucial role in enhancing the language's versatility by providing pre-built modules and packages for a wide range of tasks such as web development, data analysis, scientific computing, and more . This extensive standard library, including modules like os for operating system interactions, datetime for date and time operations, and re for regular expressions, significantly reduces the need for third-party dependencies and custom implementations, making it easier for programmers to write code in diverse application domains. The libraries are well-documented and maintained, facilitating ease of use and helping programmers to focus on solving high-level problems without delving into low-level coding .

Environment variables in Python are key-value pairs that influence the behavior of the operating system and applications, including Python itself . They enable Python programs to be executed from the command line across different systems by setting up the necessary paths and configuration. For instance, adding Python's executable path to the PATH environment variable allows users to invoke Python from any directory, facilitating seamless execution . On Windows, environment variables are accessed through the Control Panel under System settings, and similar configurations exist for UNIX-based systems, making it adaptable to different OS environments .

A developer might choose to use a frozen set over a standard set when immutability is required, such as when storing sets within other sets or needing a consistent hashing record . This choice enhances software safety by ensuring that the data remains consistent and unchanged throughout its lifecycle, which is critical in concurrent or distributed systems where mutable structures might lead to data races or inconsistencies . However, while frozen sets prevent modification, they inherently limit performance for operations that involve changes, necessitating reconstruction of the entire structure to simulate changes, which might be costly compared to mutable sets that allow direct modification .

Dynamic typing in Python allows variables to change types at runtime, enhancing program flexibility by allowing functions to process a variety of data types without explicit declarations . This can save development time and make the code more adaptable. However, this flexibility can lead to runtime errors if type mismatches occur, which would typically be caught at compile time in statically typed languages. The trade-offs include greater development speed but with a higher risk of runtime errors, whereas statically typed languages like Java provide more type safety but require more upfront type definitions .

You might also like