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

Python Unit 1 & 2

Python is a high-level, interpreted scripting language created by Guido van Rossum, with its first version released in 1994 and significant changes introduced in version 3.0 in 2008. It is known for its portability, expressiveness, and support for object-oriented programming, along with a large standard library that facilitates rapid application development. The document also discusses various Integrated Development Environments (IDEs) and tools for Python programming, along with fundamental concepts such as data types, type conversion, expressions, and arithmetic operators.

Uploaded by

saketverma2005
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Unit 1 & 2

Python is a high-level, interpreted scripting language created by Guido van Rossum, with its first version released in 1994 and significant changes introduced in version 3.0 in 2008. It is known for its portability, expressiveness, and support for object-oriented programming, along with a large standard library that facilitates rapid application development. The document also discusses various Integrated Development Environments (IDEs) and tools for Python programming, along with fundamental concepts such as data types, type conversion, expressions, and arithmetic operators.

Uploaded by

saketverma2005
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

UNIT1

Python
Introduction Python is a high-level, interpreted scripting language developed in the late
1980s by Guido van Rossum at the National Research Institute for Mathematics and
Computer Science in the Netherlands.
The initial version was published at the alt.sources news group in 1991, and version 1.0
was released in 1994.
Python 2.0 was released in 2000, and the 2.x versions were the prevalent releases until
December 2008.
At that time, the development team made the decision to release version 3.0, which
contained significant changes that were not backward compatible with the 2.x versions.
Features of Python
Python is interpreted:
Many languages are compiled, meaning the source code you create needs to be translated
into machine code (the language of computer‟s processor, before it can be run).
Programs written in an interpreted language are passed straight to an interpreter that runs
them directly.
This makes for a quicker development cycle because you just type in your code and run
it, without the intermediate compilation step.
One potential downside to interpreted languages is execution speed. Programs that are
compiled into the native language of the computer processor tend to run more quickly
than interpreted programs.
Python is Free:
The Python interpreter is developed under an OSI-approved open-source license, making
it free to install, use, and distribute, even for commercial purposes.
Python is Portable:
Because Python code is interpreted and not compiled into native machine instructions,
code written for one platform will work on any other platform that has the Python
interpreter installed.
Expressive Language:
Python language is more expressive means that it is more understandable and readable
Object-Oriented Language:
Python supports object oriented language and concepts of classes and objects come into
existence.
GUI Programming Support:
Large Standard Library: Python has a large and broad library and provides rich set of
module and functions for rapid application development
Programming cycle for Python
1. Python‟s programming cycle is dramatically shorter than that of traditional
programming cycle.
2. In Python, there are no compile or link steps.
3. Python programs simply import modules at runtime and use the objects
they contain. Because of this, Python programs run immediately after changes are made.
4. In cases where dynamic module reloading can be used, it is even possible
to change and reload parts of a running program without stopping it at all.
5. Python‟s impact on the programming cycle is as follows:

Since Python is interpreted, there is a rapid turnaround after program changes. And
because Python‟s parser is embedded in Python-based
systems, it is easy to modify programs at runtime.

Python IDEs
Integrated Development Environments (IDEs) are coding tools that make writing,
debugging, and testing your code easier. Many provide helpful features like code
completion, syntax highlighting, debugging tools, variable explorers, visualization tools,
and many other features.
Notebook platforms provide similar benefits to IDEs but are packaged in a different
format. Notebooks allow you to write code, view outputs, and add commentary in the
form of markdown. This approach to coding makes the code more readable and the
analysis more like a writeup that you and others can follow the logic of.
IDEs and notebook platforms are both great tools for data scientists to quickly write code
and analysis for data projects. There are a lot of great tools available. In this article, we
will cover 6 of the more common and best of these tools specifically with functionality
that benefits projects in data science. These tools emphasize easily importing data,
viewing large tables and variables, and viewing visualizations in an easily accessible
way.
JupyterLab Notebook & Jupyter Notebook
JupyterLab and Jupyter Notebook are two of the most popular free notebook software
for data science. They are both web-based tools. Jupyter Notebook is the original web
notebook application and is very beginner friendly with a simple document-centric
interface.
JupyterLab is the next iteration of this software. It provides an interactive and modular
development environment, making setting up a personalized workflow easy. You can use
JupyterLab for workflows in data science, scientific computing, computational
journalism, and machine learning.
Jupyter supports over 40 programming languages, including Python and R, and other data
languages like Julia and Scala. It is also very easy to install with a simple pip command,
and you can also try it on your browser before you install it.
Pros
 Has support for over 40 programming languages.
 Provides a lot of customizability features to personalize your workflow.
Cons
 Requires you to download software.
Spyder
Spyder is a free and open-source environment developed for coding in Python. The tool
features some advanced editing, debugging, and profiling tools that make coding in
Python a lot easier and more efficient.
For example, the editor features autocomplete functionality, syntax highlighting,
horizontal and vertical splitting, and other coding efficiency tools. These all help make
the coding and debugging experience easier and more customizable. The tool also has
advanced features like a variable explorer, which allows you to see variables you have
created with your code, and an easy-to-use plots explorer to look at and save plots your
code has created.
Spyder also offers other plugins to extend the software‟s functionality, including a
notebook, a terminal, and testing software.
Pros
 Has a lot of advanced features and interface customization available.
 Completely free and open-source.
 Has additional plugins to expand the functionality of the tool.
Cons
 Only supports Python programming.
 It‟s a little advanced for newer programmers.
Google Colab
Google Colaboratory is Google‟s cloud-based notebook environment. Colab is
integrated with the Google suite of products and is easy to get started with if you have a
Google account. You can import data into Colab notebooks from your Google Drive
account and from other sources like Github.
Colab is also very popular in the Machine learning community and allows you to
leverage Google‟s cloud hardware, including GPUs and TPUs, to run machine learning
code regardless of how powerful your own computer is. You can also share Colab
notebooks with others, similar to a Google doc file, making it easy to share your work. It
also supports over 40 programming languages, including Python, R, and Scala.
Pros
 Has support for over 40 programming languages.
 Free and easy to set up with a google account.
 Gives you free access to Google hardware, so you don‟t have to rely on your own
machine‟s hardware for computationally demanding projects.
 Easy to share code and collaborate.
 Available online with no software installation.
Cons
 Losing an internet connection or leaving a session running for too long can cause you to
lose progress on work and need to rerun the notebook (which can take a while for ML
and AI model training notebooks).
 Hardware resources and power can be limited without a premium subscription.
How To Work with the Python Interactive Console
The Python interactive console (also called the Python interpreter or Python shell)
provides programmers with a quick way to execute commands and try out or test code
without creating a file.
Providing access to all of Python‟s built-in functions and any installed modules,
command history, and auto-completion, the interactive console offers the opportunity to
explore Python and the ability to paste code into programming files when you are ready.
Interacting with Python A program is a sequence of instructions that specifies how to
perform a Computation. The Computation might be mathematical or working with text.
To write and run Python program, we need to have Python interpreter installed in our
computer. IDLE (GUI integrated) is the standard, most popular Python development
environment.
IDLE is an acronym of Integrated Development and Learning Environment.

Running a Python Script from the Command Line


A Python script is a reusable set of code. It is essentially a Python program by specifying
the name of the script file to the interpreter.
Python scripts are just plain text, so you can edit them with any text editor.
Using whatever editor you‟ve chosen; create a script file called hello.py containing the
following:
Now save the file, keeping track of the directory or folder you choose to save into.
Now open the Command Prompt and type the command like follow--
C:\Users\user\Documents\test>python hello.py
Hello, World! You can give the file path if directory is not same--
C:\>python C:\Users\user\Documents\test\hello.py
Hello, World!
Interacting with Python through an IDE
IDLE (Integrated Development and Learning Environment):
Most Python installations contain a rudimentary IDE called IDLE.
Starting IDLE in Windows
Go to the Start menu and select All Programs or All Apps. There should be a program
icon labeled IDLE (Python 3.x 32-bit) or something similar.
IDLE will open in interactive mode that means you can directly type the python
instructions it will evaluate immediately.
For writing python script, follow the steps given bellow:
• Open a new file by clicking on File->New File
• Write your python code
• Save it as .py extension
• Click on Run->Run Module or press F5
• Output will be shown to the Python Shell
Python Comments
Python Comments Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
Comments start with a # symbol

Comments can be placed at the end of a line

To add a multiline comment you could insert a # for each line


Elements of Python
A Python program is a sequence of Definitions and Commands (Statements). Commands
manipulate Objects. Each Object is associated with a Type.
Python Statement:
An statement is a syntactic unit of a program that expresses some action to be carried out.
A statement may have internal components (e.g., expressions). Statements are the
instructions that a Python interpreter can execute.
Expression:
Expression in a Python language is a combination of one or more objects, operators, and
functions that the Python interprets and computes to produce another value.
In programming, data type is an important concept.
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

None Type: NoneType


Type Conversion in Python
Python defines type conversion functions to directly convert one data type to another
which is useful in day-to-day and competitive programming.
There are two types of Conversion
Type Conversion in Python:
1. Implicit Type Conversion
2. Explicit Type Conversion
Let‟s discuss them in detail.
Implicit Type Conversion
In Implicit type conversion of data types in Python, the Python interpreter automatically
converts one data type to another without any user involvement. The reason for the float
value not being converted into an integer instead is due to type promotion that allows
performing operations by converting data into a wider-sized data type without any loss
of information. This is a simple case of Implicit type conversion in python.
Explicit Type Conversion
In Explicit Type Conversion in Python, the data type is manually changed by the user as
per their requirement. With explicit type conversion, there is a risk of data loss since we
are forcing an expression to be changed in some specific data type Various forms of
explicit type conversion are explained below:
1. int(a, base): This function converts any data type to integer. „Base‟ specifies the base
in which string is if the data type is a string.
2. float(): This function is used to convert any data type to a floating-point number.
3. ord() : This function is used to convert a character to integer.
4. hex() : This function is to convert integer to hexadecimal string.
5. oct() : This function is to convert integer to octal string.
6. tuple() : This function is used to convert to a tuple.
7. set() : This function returns the type after converting to set.
8. list() : This function is used to convert any data type to a list type.
9. dict() : This function is used to convert a tuple of order (key,value) into a dictionary.
10. str() : Used to convert integer into a string.
11. complex(real,imag) : This function converts real numbers to complex(real,imag)
number.
12. chr(number): This function converts number to its corresponding ASCII character.
Expressions in Python
An expression is a combination of operators and operands that is interpreted to produce
some other value. In any programming language, an expression is evaluated as per the
precedence of its operators. So that if there is more than one operator in an expression,
their priority decides which operation will be performed first? We have many different
types of expressions in Python. Let‟s describe all types along with some exemplar codes
:
1. Constant Expressions: These are the expressions that have constant values only.
2. Arithmetic Expressions: An arithmetic expression is a combination of numeric values,
operators, and sometimes parenthesis. The result of this type of expression is also a
numeric value. The operators used in these expressions are arithmetic operators like
addition, subtraction, etc. Here are some arithmetic operators in Python:
Operators Syntax Functioning

+ x+y Addition

– x–y Subtraction

* x*y Multiplication

/ x/y Division

// x // y Quotient

% x%y Remainder

** x ** y Exponentiation
3. Integral Expressions: These are the kind of expressions that produce only integer
results after all computations and type conversions.
4. Floating Expressions: These are the kind of expressions which produce floating point
numbers as result after all computations and type conversions.
5. Relational Expressions: In these types of expressions, arithmetic expressions are
written on both sides of relational operator (> , < , >= , <=). Those arithmetic
expressions are evaluated first, and then compared as per relational operator and
produce a boolean output in the end. These expressions are also called Boolean
expressions.
6. Logical Expressions: These are kinds of expressions that result in
either True or False. It basically specifies one or more conditions. For example, (10 ==
9) is a condition if 10 is equal to 9. As we know it is not correct, so it will return False.
Studying logical expressions, we also come across some logical operators which can be
seen in logical expressions most often. Here are some logical operators in Python:

Assignment statement
An Assignment statement is a statement that is used to set a value to the variable name in a
program.
Assignment statement allows a variable to hold different types of values during its program
lifespan. Another way of understanding an assignment statement is, it stores a value in
the memory location which is denoted by a variable name.
Syntax
The symbol used in an assignment statement is called as an operator. The symbol is ‘=’.
Note: The Assignment Operator should never be used for Equality purpose which is double
equal sign „==‟.
The Basic Syntax of Assignment Statement in a programming language is :
variable = expression ;
where,
variable = variable name
expression = it could be either a direct value or a math expression/formula or a function call
Python Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication and division.
There are 7 arithmetic operators in Python :
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Modulus
6. Exponentiation
7. Floor division
1. Addition Operator : In Python, + is the addition operator. It is used to add 2 values.
2. 2. Subtraction Operator : In Python, – is the subtraction operator. It is used to subtract
the second value from the first value.
3. 3. Multiplication Operator : In Python, * is the multiplication operator. It is used to
find the product of 2 values.
4. 4. Division Operator : In Python, / is the division operator. It is used to find the
quotient when first operand is divided by the second.
5. 5. Modulus Operator : In Python, % is the modulus operator. It is used to find the
remainder when first operand is divided by the second.
6. 6. Exponentiation Operator : In Python, ** is the exponentiation operator. It is used
to raise the first operand to power of second.
7. 7. Floor division : In Python, // is used to conduct the floor division. It is used to find
the floor of the quotient when first operand is divided by the second.
What is operator precedence in Python
Operator precedence in Python simply refers to the order of operations. Operators are
used to perform operations on variables and values. Python always evaluates the left
operand before the right- even in function arguments. If you‟re reading about Python,
you sure have heard about BODMAS somewhere in your journey so far (mathematics,
school). In Python, however, we come across BEDMAS. The acronym stands for the
following words, which tell us which operator comes first:
 B= Bracket
 E = Exponentiation
 D = Division
 M = Multiplication
 A = Addition
 S = Subtraction
Through the acronym, we can see that the bracket/parenthesis operator comes before the
exponentiation operation in Python, according to the order of operations.
The same logic applies to each of the following operators, down to the subtraction
operator.
Example
To fully grasp BEDMAS and the order of preference of the operators, let‟s take a look at
the example below:
X = (5 + 3) * 2 ** 2
print(X)
From this program, we can see that there are three operators:
 Bracket (B)
 Exponentiation (E)
 Multiplication (M)
According to operator precedence, Python first deals with the numbers in the bracket
operator (B): (5 + 3) = 8.
We then proceed to the exponentiation operator (E): 2 ** 2 = 4.
Finally, the results of both the bracket (8) and exponentiation (4) operators are then
executed using the multiplication operator (M): 8 * 4 = 32.
In short, Python followed the order of operators outlined in BEDMAS.
Understanding Boolean Logic in Python
Booleans are simple and easy to use concepts that exist in every programming
language. A boolean represents an idea of “true” or “false.” While writing an algorithm
or any program, there are often situations where we want to execute different code in
different situations. Booleans help our code to do just that easy and effective. More
often, a boolean value is returned as a result of some kind of comparison operations.
There are two Boolean keywords: True and False
Comparison Operators
Comparison operators are used to compare values. It returns either True or False after
computing the condition.
> Greater than – True if left operand is greater than the right x>y
< Less than – True if left operand is less than the right\\\ x < y
== Equal to – True if both operands are equal x == y
!= Not equal to – True if operands are not equal x != y
>= Greater than or equal to – True if left operand is greater than or equal to the right
x >= y
<= Less than or equal to – True if left operand is less than or equal to the right
UNIT2
What are Conditional Statements in Python?
Conditional Statement in Python perform different computations or actions depending on
whether a specific Boolean constraint evaluates to true or false. Conditional statements
are handled by IF statements in Python.
In this tutorial, we will see how to apply conditional statements in Python.
What is Python If Statement?
Python if Statement is used for decision-making operations. It contains a body of code
which runs only when the condition given in the if statement is true. If the condition is
false, then the optional else statement runs which contains some code for the else
condition.
When you want to justify one condition while the other condition is not true, then you use
Python if else statement.
Python if Statement Syntax:
if expression
Statement
else
Statement
In python, decision making is performed by the following statements.

Statemen
Description
t

The if statement is used to test a specific condition. If the


If Statement
condition is true, a block of code (if-block) will be executed.
The if-else statement is similar to if statement except the fact
If - else that, it also provides the block of the code for the false case of
Statement the condition to be checked. If the condition provided in the if
statement is false, then the else statement will be executed.
Nested if Nested if statements enable us to use if ? else statement inside an
Statement outer if statement.
number = 10

# check if number is greater than 0


if number > 0:
print('Number is positive.')

print('The if statement is easy')

Example 1 : Program to print the largest of the three numbers.

1. a = int(input("Enter a? "));
2. b = int(input("Enter b? "));
3. c = int(input("Enter c? "));
4. if a>b and a>c:
5. print("a is largest");
6. if b>a and b>c:
7. print("b is largest");
8. if c>a and c>b:
9. print("c is largest");

Example 2 : Program to print the largest of the three numbers.

#!/usr/bin/env python3

gender = input("Gender? ")


gender = gender.lower()
if gender == "male":
print("Your cat is male")
elif gender == "female":
print("Your cat is female")
else:
print("Invalid input")

age = int(input("Age of your cat? "))


if age < 5:
print("Your cat is young.")
else:
print("Your cat is adult.")

Python Loops
The following loops are available in Python to fulfil the looping needs. Python offers 3
choices for running the loops. The basic functionality of all the techniques is the same,
although the syntax and the amount of time required for checking the condition differ.
We can run a single statement or set of statements repeatedly using a loop command.
The following sorts of loops are available in the Python programming language.

Sr.No. Name of the loop Loop Type & Description


1 While loop Repeats a statement or group of statements while a given condition
is TRUE. It tests the condition before executing the loop body.

Flowchart of Python while Loop

# program to display numbers from 1 to 5

# initialize the variable


i=1
n=5

# while loop from i = 1 to 5


while i <= n:
print(i)
i=i+1
2 For loop This type of loop executes a code block multiple times and
abbreviates the code that manages the loop variable.

Flowchart of Python for Loop

# use of range() to define a range of values


values = range(4)

# iterate from i = 0 to i = 3
for i in values:
print(i)

Python for loop with else


digits = [0, 1, 5]

for i in digits:
print(i)
else:
print("No items left.")

Example 2: Python while Loop


# program to calculate the sum of numbers
# until the user enters zero

total = 0

number = int(input('Enter a number: '))

# add numbers until number is zero


while number != 0:
total += number # total = total + number

# take integer input again


number = int(input('Enter a number: '))

print('total =', total)

Example 3: Python while Loop

counter = 0

while counter < 3:


# loop ends because of break
# the else part is not executed
if counter == 1:
break

print('Inside loop')
counter = counter + 1
else:
print('Inside else')

3 Nested loops We can iterate a loop inside another loop.


Loop Control Statements
Statements used to control loops and change the course of iteration are called control
statements. All the objects produced within the local scope of the loop are deleted when
execution is completed.
Python provides the following control statements. We will discuss them later in detail.
Let us quickly go over the definitions of these loop control statements.
Sr.No. Name of the control statement Description
1 Break statement This command terminates the loop's execution and transfers
the program's control to the statement next to the loop.
2 Continue statement This command skips the current iteration of the loop. The
statements following the continue statement are not executed once the Python interpreter
reaches the continue statement.
3 Pass statement The pass statement is used when a statement is syntactically
necessary, but no code is to be executed.
Example 1 : Program to print the largest of the three numbers.

# Python program to illustrate


# while loop
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")

You might also like