0% found this document useful (0 votes)
23 views10 pages

TCS 151-SM04

Uploaded by

Manik Rajput
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)
23 views10 pages

TCS 151-SM04

Uploaded by

Manik Rajput
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
You are on page 1/ 10

UNIT-1 Introduction to Python

Overview of Programming Language:

What is Language?

Language is a mode of communication that is used to share ideas, opinions with each other.
For example, if we want to teach someone, we need a language that is understandable by both
communicators.

What is a Programming Language?

A programming language is a computer language that is used by programmers (developers)


to communicate with computers. It is a set of instructions written in any specific language
( C, C++, Java, Python) to perform a specific task.

A programming language is mainly used to develop desktop applications, websites, and


mobile applications.

Types of programming language

1. Low-level programming language


Low-level language is machine-dependent (0s and 1s) programming language. The processor
runs low- level programs directly without the need of a compiler or interpreter, so the
programs written in low-level language can be run very fast.

Low-level language is further divided into two parts –

i. Machine Language
Machine language is a type of low-level programming language. It is also called as machine
code or object code. Machine language is easier to read because it is normally displayed in
binary or hexadecimal form (base 16) form. It does not require a translator to convert the
programs because computers directly understand the machine language programs.
The advantage of machine language is that it helps the programmer to execute the programs
faster than the high-level programming language.

ii. Assembly Language

Assembly language (ASM) is also a type of low-level programming language that is designed
for specific processors. It represents the set of instructions in a symbolic and human-
understandable form. It uses an assembler to convert the assembly language to machine
language.

The advantage of assembly language is that it requires less memory and less execution time
to execute a program.
2. High-level programming language

High-level programming language (HLL) is designed for developing user-friendly software


programs and websites. This programming language requires a compiler or interpreter to
translate the program into machine language (execute the program).

The main advantage of a high-level language is that it is easy to read, write, and maintain.

High-level programming language includes Python, Java, JavaScript, PHP, C#, C++,
Objective C, Cobol, Perl, Pascal, LISP, FORTRAN, and Swift programming language.

A high-level language is further divided into three parts -

i. Procedural Oriented programming language

Procedural Oriented Programming (POP) language is derived from structured programming


and based upon the procedure call concept. It divides a program into small procedures
called routines or functions.

Procedural Oriented programming language is used by a software programmer to create a


program that can be accomplished by using a programming editor like IDE, Adobe
Dreamweaver, or Microsoft Visual Studio.

The advantage of POP language is that it helps programmers to easily track the program flow
and code can be reused in different parts of the program.

Example: C, FORTRAN, Basic, Pascal, etc.

ii. Object-Oriented Programming language

Object-Oriented Programming (OOP) language is based upon the objects. In


this programming language, programs are divided into small parts called objects. It is used to
implement real-world entities like inheritance, polymorphism, abstraction, etc in the program
to makes the program resusable, efficient, and easy-to-use.

The main advantage of object-oriented programming is that OOP is faster and easier to
execute, maintain, modify, as well as debug.

Example: C++, Java, Python, C#, etc.

iii. Natural language

Natural language is a part of human languages such as English, Russian, German, and
Japanese. It is used by machines to understand, manipulate, and interpret human's language.
It is used by developers to perform tasks such as translation, automatic summarization,
Named Entity Recognition (NER), relationship extraction, and topic segmentation.

The main advantage of natural language is that it helps users to ask questions in any subject
and directly respond within seconds.
3. Middle-level programming language

Middle-level programming language lies between the low-level programming language and
high-level programming language. It is also known as the intermediate programming
language and pseudo-language.

A middle-level programming language's advantages are that it supports the features of high-
level programming, it is a user-friendly language, and closely related to machine language
and human language.

Example: C, C++, language

History of Python
Python, a high-level programming language, was created by Guido van Rossum and first
released in 1991. Its development began in the late 1980s at Centrum Wiskunde &
Informatica (CWI) in the Netherlands, where van Rossum worked. The initial goal of Python
was to create a language that was easy to read and use, yet powerful enough for complex
tasks.
Here's a brief history of Python:
Creation (Late 1980s - Early 1990s):
Guido van Rossum started working on Python in December 1989.
The first version, Python 0.9.0, was released in February 1991.
Python's design philosophy emphasized code readability and simplicity.
Python 1.0 (1994):
Python 1.0 was released in January 1994.
It included features like lambda, map, filter, and reduce functions.
Python started gaining popularity among developers for its clean syntax and ease of learning.
Python 2.x Series (2000s):
Python 2.0 was released in 2000 with features like garbage collection and Unicode support.
The Python 2.x series saw numerous updates and improvements, becoming widely adopted in
the software industry.
However, Python 2.x faced criticism due to certain design flaws, particularly related to
Unicode handling and division behavior.
Python 3.0 (2008):
Python 3.0, also known as Python 3000 or "Py3k," was a significant milestone in Python's
history.
It aimed to rectify the design flaws of Python 2.x while maintaining backward compatibility
where feasible.
Python 3.0 introduced syntax changes and removed outdated features, making the language
more consistent and robust.
Python 3.x Series (2008 - Present):
Python 3.x series has been the focus of development since 2008.
Major releases within the Python 3.x series, such as Python 3.5, 3.6, 3.7, 3.8, and 3.9, brought
new features, optimizations, and improvements.
Python 3.x adoption has been steadily increasing, and Python 2.x officially reached its end of
life in January 2020.
Features of Python Programming:
Python is a versatile and powerful programming language known for its simplicity,
readability, and flexibility. It offers a wide range of features that make it popular among
developers across various domains. Here are some key features of Python:
Simple and Readable Syntax: Python's syntax is designed to be straightforward and easy to
understand, resembling pseudo-code in many ways. Its indentation-based block structure
enhances readability and reduces the need for explicit delimiters like braces.
High-level Language: Python abstracts low-level details, allowing developers to focus more
on solving problems rather than dealing with system-level programming intricacies.
Interpreted Language: Python is an interpreted language, which means that code written in
Python is directly executed without the need for compilation. This facilitates rapid
development and prototyping.
Rich Standard Library: Python comes with a comprehensive standard library that provides
modules and packages for a wide range of tasks, including file I/O, networking, data
manipulation, web development, and more. This extensive library reduces the need for third-
party dependencies in many cases.
Platform Independence: Python is platform-independent, meaning code written in Python
can run on various operating systems like Windows, macOS, and Linux without
modification.
Object-Oriented Programming (OOP): Python supports object-oriented programming
paradigms, allowing developers to create and use classes, objects, and inheritance for code
organization and reuse.
Extensive Ecosystem: Python has a vast ecosystem of third-party libraries and frameworks
that extend its capabilities for specific domains and tasks. For example, libraries like NumPy,
Pandas, Matplotlib, and scikit-learn are widely used in data science and machine learning.
Dynamically Typed: Python is dynamically typed, which means you don't have to declare
the data type of variables explicitly. The interpreter infers the data type based on the value
assigned to the variable.
Community Support: Python has a large and active community of developers who
contribute to its growth and development. The Python community is known for its
inclusivity, helpfulness, and commitment to open-source principles.

Basic Syntax
Python syntax refers to the set of rules that defines the combinations of symbols that are
considered to be correctly structured programs in the Python language. These rules make
sure that programs written in Python should be structured and formatted, ensuring that the
Python interpreter can understand and execute them correctly.

print("Hello, World!")
Hello, World!

Python Interactive Shell


1. Start the Python interpreter by simply typing python (or python3 on some systems) in
the terminal or command prompt. We can then run Python commands interactively.
2. To exit, we can type exit () or press Ctrl + D.
Running & execution of a script with prompt in python
To create a Python script with prompts for user input and execute it, you can follow these
steps:
Create the Python script: Write your Python code in a .py file using a text editor or an IDE.
Use the input() function: Inside your script, use the input() function to prompt the user for
input.
Execute the script: Run the Python script using the Python interpreter in your terminal or
command prompt.
Here's a simple example:
# script.py

# Prompt the user for their name


name = input("Enter your name: ")

# Print a greeting message


print("Hello, " + name + "! Welcome to the script.")

To execute the script, follow these steps:


1. Save the script code in a file named script.py.
2. Open a terminal or command prompt.
3. Navigate to the directory where script.py is located using the cd command.
4. Run the script by typing python script.py and pressing Enter.
5. You should see the prompt Enter your name: in the terminal. Type your name and
press Enter.
6. The script will print a greeting message with the name you entered.

Application Areas of Python

Python is a versatile programming language that finds applications across various domains.
Some of the prominent application areas of Python include:
Web Development: Python is widely used for web development due to frameworks like
Django and Flask. These frameworks enable developers to create powerful and scalable web
applications and APIs.
Data Science and Machine Learning: Python's extensive libraries such as NumPy, Pandas,
Matplotlib, and scikit-learn make it a popular choice for data analysis, machine learning, and
artificial intelligence projects. Libraries like TensorFlow and PyTorch are also widely used
for deep learning tasks.
Scientific Computing: Python is utilized in scientific computing and computational sciences
due to its simplicity and extensive libraries for numerical computations, simulations, and
visualization.
Automation and Scripting: Python's simplicity and readability make it an excellent choice
for automating repetitive tasks, such as system administration, file manipulation, and data
processing.
Desktop GUI Applications: Python can be used to develop desktop graphical user interface
(GUI) applications using libraries like Tkinter, PyQt, and wxPython. These libraries provide
tools for creating interactive and cross-platform desktop applications.
Game Development: Python is employed in game development for prototyping, scripting,
and building game engines. Libraries like Pygame offer tools for creating 2D games, while
other frameworks like Panda3D support the development of 3D games.
Network Programming: Python's built-in libraries, such as socket, and third-party libraries
like Twisted, enable developers to create network applications, implement networking
protocols, and build servers and clients for various network services.
DevOps and System Administration: Python is widely used in DevOps practices and
system administration tasks. Tools like Ansible, Fabric, and SaltStack leverage Python for
automation, configuration management, and deployment tasks.
Education and Learning: Python's simplicity and readability make it an ideal language for
teaching programming concepts to beginners. Many educational institutions and coding
bootcamps use Python as an introductory language for teaching programming.
Financial and Quantitative Analysis: Python is extensively used in the finance industry for
quantitative analysis, algorithmic trading, risk management, and financial modeling. Libraries
like QuantLib and Pandas are commonly employed for financial data analysis and modeling.

Understanding use of Input and Print Function


The input() and print() functions are fundamental tools in Python for interacting with the user
and displaying output, respectively.
input() Function:
The input() function is used to take input from the user. It reads a line of input from the user
and returns it as a string. You can optionally provide a prompt to display to the user while
waiting for input.
Here's a simple example:

name = input("Enter your name: ")


print("Hello,", name)

When you run this code, it will prompt the user to enter their name. Once they enter their
name and press Enter, it will print a greeting message with the entered name.

print() Function:
The print() function is used to display output to the console. It can accept zero or more
arguments separated by commas. Each argument is converted to a string and displayed on the
console. By default, print() ends with a newline character (\n), but you can change this
behaviour using the end parameter.

Here are some examples of using print():


# Printing a string
print("Hello, world!")

# Printing multiple values separated by commas


x = 10
y = 20
print("The value of x is", x, "and the value of y is", y)
Type Casting
Type casting, also known as type conversion or type coercion, is a fundamental concept in
programming languages that allows you to convert one data type into another. It's a common
operation in many programming tasks where you need to manipulate data of different types.
Here's a detailed look at type casting in programming languages:

1. Implicit Type Casting:


Implicit type casting, also known as implicit type conversion, occurs automatically by the
programming language without any explicit instructions from the programmer. It's performed
when values of one data type are used in a context where a different data type is expected.
Implicit type casting typically happens when the target data type has a wider range or higher
precision than the source data type.
For example, in Python:
num_int = 10
num_float = 3.5

result = num_int + num_float # Implicitly converts num_int to float


print(result) # Output: 13.5

2. Explicit Type Casting:


Explicit type casting, also known as explicit type conversion, involves the programmer
explicitly instructing the programming language to convert a value from one data type to
another using specific functions or syntax provided by the language. Explicit type casting is
useful when you want to control the conversion process or when the target data type has a
narrower range or lower precision than the source data type.
For example, in Python:
num_str = "123"
num_int = int(num_str) # Explicitly converts string to integer
print(num_int) # Output: 123

Number System
A number system, also known as a numeral system, is a mathematical notation for
representing numbers. Different number systems are used in various fields of mathematics,
computer science, and everyday life. Here are some common number systems:
1. Decimal Number System (Base-10):
The decimal number system is the most common number system used by humans. It is base-
10, meaning it uses 10 symbols (0-9) to represent numbers. Each position in a decimal
number represents a power of 10. For example, in the number 354, the digit 4 represents
4×1004×100, the digit 5 represents 5×1015×101, and the digit 3 represents 3×1023×102.
2. Binary Number System (Base-2):
The binary number system is widely used in computer science and digital electronics. It is
base-2, meaning it uses only two symbols (0 and 1) to represent numbers. Each position in a
binary number represents a power of 2. For example, in the binary number 1010, the digit 0
represents 0×200×20, the second 1 represents 1×211×21, the third 0 represents 0×220×22,
and the first 1 represents 1×231×23.
3. Octal Number System (Base-8):
The octal number system is base-8, meaning it uses eight symbols (0-7) to represent numbers.
Each position in an octal number represents a power of 8.
4. Hexadecimal Number System (Base-16):
The hexadecimal number system is base-16, meaning it uses sixteen symbols (0-9 and A-F)
to represent numbers. It is commonly used in computer science, especially for representing
binary data in a more compact and human-readable form. Each position in a hexadecimal
number represents a power of 16.

Operators in Python
In Python, operators are special symbols or keywords that perform operations on operands.
Operands are the values or variables that the operator acts upon. Python supports various
types of operators, including arithmetic operators, comparison operators, logical operators,
assignment operators, bitwise operators, and more. Let's discuss each category:
1. Arithmetic Operators:
Arithmetic operators are used to perform mathematical operations such as addition,
subtraction, multiplication, division, modulus, and exponentiation.
Addition: +
Subtraction: -
Multiplication: *
Division: /
Modulus (Remainder): %
Exponentiation: **
Floor Division (Integer Division): //
2. Comparison Operators:
Comparison operators are used to compare the values of two operands. They return Boolean
values (True or False) based on the comparison.
Equal to: ==
Not equal to: !=
Greater than: >
Less than: <
Greater than or equal to: >=
Less than or equal to: <=

3. Logical Operators:
Logical operators are used to combine conditional statements. They return True or False
based on the logical condition.
Logical AND: and
Logical OR: or
Logical NOT: not

4. Assignment Operators:
Assignment operators are used to assign values to variables.
Assignment: =
Addition assignment: +=
Subtraction assignment: -=
Multiplication assignment: *=
Division assignment: /=
Modulus assignment: %=
Exponentiation assignment: **=
Floor division assignment: //=
5. Bitwise Operators:
Bitwise operators perform operations on binary representations of integers.
Bitwise AND: &
Bitwise OR: |
Bitwise XOR: ^
Bitwise NOT: ~
Left shift: <<
Right shift: >>

6. Membership Operators:
Membership operators are used to test if a sequence (such as a string, list, tuple) contains a
specific value.
in: Evaluates to True if the value is found in the sequence.
not in: Evaluates to True if the value is not found in the sequence.

7. Identity Operators:
Identity operators are used to compare the memory locations of two objects.
is: Evaluates to True if both variables point to the same object.
is not: Evaluates to True if both variables point to different objects.

Expression in Python

In Python, an expression is a combination of values, variables, operators, and function calls


that evaluates to a single value. Expressions can be simple or complex, and they are the
building blocks of Python programs. Here are some examples of expressions:

1. Arithmetic Expressions:
Arithmetic expressions involve arithmetic operations such as addition, subtraction,
multiplication, division, modulus, and exponentiation.
result = 5 + 3 * (2 - 1)

2. String Expressions:
String expressions involve string concatenation using the + operator or repetition using the *
operator.
greeting = "Hello, " + "world!"

3. Comparison Expressions:
Comparison expressions evaluate to a Boolean value (True or False) based on the comparison
of two values.
is_greater = 10 > 5

4. Logical Expressions:
Logical expressions involve logical operations such as AND (and), OR (or), and NOT (not).
is_valid = (age > 18) and (name != "admin")

5. Membership and Identity Expressions:


Membership expressions test if a value is present in a sequence, while identity expressions
test if two objects refer to the same memory location.
is_in_list = 10 in [1, 2, 3, 4, 5]
is_same_object = obj1 is obj2

6. Function Call Expressions:


Function call expressions involve calling functions with arguments and returning values.
result = max(3, 7, 1, 9)

7. Conditional Expressions (Ternary Operator):


The conditional expression, also known as the ternary operator, evaluates to one of two
values based on a Boolean condition.
result = "Even" if num % 2 == 0 else "Odd"

8. List Comprehensions:
List comprehensions provide a concise way to create lists based on existing lists or other
iterable objects.
squared_numbers = [x ** 2 for x in range(1, 6)]

9. Dictionary Comprehensions:
Similar to list comprehensions, dictionary comprehensions create dictionaries based on
existing dictionaries or iterable objects.
squared_dict = {x: x ** 2 for x in range(1, 6)}

10. Generator Expressions:


Generator expressions are similar to list comprehensions but create generator objects, which
are memory-efficient iterators.
squared_gen = (x ** 2 for x in range(1, 6))

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy