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

Machine-learning-Python-unit1Machine_Learning-MBA-unit-3

The document provides an introduction to Python, detailing its history, advantages, and basic programming concepts such as data types, variables, and control statements. It explains how to write and run Python programs, including examples of arithmetic, relational, and logical expressions, as well as conditional statements like if, else, and nested if. Additionally, it covers the syntax and rules for defining variables and constants in Python.

Uploaded by

sou
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)
3 views20 pages

Machine-learning-Python-unit1Machine_Learning-MBA-unit-3

The document provides an introduction to Python, detailing its history, advantages, and basic programming concepts such as data types, variables, and control statements. It explains how to write and run Python programs, including examples of arithmetic, relational, and logical expressions, as well as conditional statements like if, else, and nested if. Additionally, it covers the syntax and rules for defining variables and constants in Python.

Uploaded by

sou
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/ 20

UNIT – I

Introduction to Python

Python is a widely used general-purpose, high level programming language. It was initially
designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It
was mainly developed for emphasis on code readability, and its syntax allows programmers
to express concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate systems more
efficiently.
There are two major Python versions- Python 2 and Python 3.

• On 16 October 2000, Python 2.0 was released with many new features.
• On 3rd December 2008, Python 3.0 was released with more testing and includes new
features.

Beginning with Python programming:

1) Writing first program:

# Script Begins

Statement1

1
Statement

Statement

# Script Ends
Why to use Python/Advantages :

The following are the primary factors to use python in day-to-day life:

1. Python is object-oriented
Writing the programme in natural way not as procedural way
Eg: seeing student as a class and define operations over an object of that class
typle
2. It’s free (open source)
Downloading python and installing python is free and easy
3. It’s Powerful
 Built-in types and tools
 Library utilities
 Third party utilities (e.g. Numeric, NumPy, sciPy)
 Automatic memory management
4. It’s Portable
 Python runs virtually every major platform used today
 As long as you have a compatible python interpreter installed, python
programs will run in exactly the same manner, irrespective of platform.
5. It’s easy to use and learn
 No intermediate compile
 Python Programs are compiled automatically to an intermediate form called
byte code, which the interpreter then reads.
 This gives python the development speed of an interpreter without the
performance loss inherent in purely interpreted languages.
 Structure and syntax are pretty intuitive and easy to grasp.
6. Interpreted Language
Python is processed at runtime by python Interpreter
7. Interactive Programming Language
Users can interact with the python interpreter directly for writing the programs
2
8. Straight forward syntax
The formation of python syntax is simple and straight forward which also makes it
popular.

Working with Python

Running Python in interactive mode:

Without passing python script file to the interpreter, directly execute code to Python prompt.
Once you’re inside the python interpreter, then you can start.

>>> print("hello world")

hello world

# Relevant output is displayed on subsequent lines without the >>> symbol

>>> x=[0,1,2]

# Quantities stored in memory are not displayed by default.

>>> x

#If a quantity is stored in memory, typing its name will display it.

[0, 1, 2]

>>> 2+3

The chevron at the beginning of the 1st line, i.e., the symbol >>> is a prompt the python
interpreter uses to indicate that it is ready. If the programmer types 2+6, the interpreter

3
replies 8.

Data types in Python:

The data stored in memory can be of many types. For example, a student roll number is
stored as a numeric value and his or her address is stored as alphanumeric characters. Python
has various standard data types that are used to define the operations possible on them and
the storage method for each of them.

Int:

Int, or integer, is a whole number, positive or negative, without decimals, of unlimited


length.

>>> print(24656354687654+2)
24656354687656
>>> print(20)
20
>>> a=10
>>> print(a)
10
# To verify the type of any object in Python, use the type() function:

>>> type(10)
<class 'int'>
>>> a=11
>>> print(type(a))
<class 'int'>
Float:

Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.

Float can also be scientific numbers with an "e" to indicate the power of 10.

>>> y=2.8
>>> y
2.8
4
>>> y=2.8
>>> print(type(y))
<class 'float'>
>>> type(.4)
<class 'float'>
>>> 2.

2.0
Example:
x = 35e3
y = 12E4
z = -87.7e100

print(type(x))
print(type(y))
print(type(z))

Output:

<class 'float'>
<class 'float'>
<class 'float'>

Boolean:

Objects of Boolean type may have one of two values, True or False:

>>> type(True)

<class 'bool'>

>>> type(False)

<class 'bool'>

String:

1. Strings in Python are identified as a contiguous set of characters represented in the


quotation marks. Python allows for either pairs of single or double quotes.

• 'hello' is the same as "hello".


5
• Strings can be output to screen using the print function. For example: print("hello").

>>> print("mrcet college")

mrcet college

>>> type("mrcet college")

<class 'str'>

>>> print('mrcet college')

mrcet college

>>> " "

''

If you want to include either type of quote character within the string, the simplest way is to
delimit the string with the other type. If a string is to contain a single quote, delimit it with
double quotes and vice versa:

>>> print("mrcet is an autonomous (') college")

mrcet is an autonomous (') college

>>> print('mrcet is an autonomous (") college')

mrcet is an autonomous (") college

Variables and Constants:

Variables are nothing but reserved memory locations to store values. This means that when
you create a variable you reserve some space in memory. Variables changes it value during
the execution of a programme. Constants will not changes its value during the execution of
the programme.

Based on the data type of a variable, the interpreter allocates memory and decides what can
be stored in the reserved memory. Therefore, by assigning different data types to variables,
you can store integers, decimals or characters in these variables.

Rules for Python variables:

• A variable name must start with a letter or the underscore character

6
• A variable name cannot start with a number

• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )

• Variable names are case-sensitive (age, Age and AGE are three different variables)

Assigning Values to Variables:

Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to
assign values to variables.

The operand to the left of the = operator is the name of the variable and the operand to the
right of the = operator is the value stored in the variable.

For example −

a= 100 # An integer assignment

b = 1000.0 # A floating point

c = "John" # A string

print (a)

print (b)

print (c)

This produces the following result −

100

1000.0

John

Multiple Assignment:

Python allows you to assign a single value to several variables simultaneously.

For example :

a=b=c=1

7
Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables.

For example −

a,b,c = 1,2,"mrcet“

Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively,
and one string object with the value "john" is assigned to the variable c.

Output Variables:

The Python print statement is often used to output variables.

Variables do not need to be declared with any particular type and can even change type after
they have been set.

x=5 # x is of type int


x = "mrcet " # x is now of type str
print(x)

Output: mrcet

To combine both text and a variable, Python uses the “+” character:

Example

x = "awesome"
print("Python is " + x)

Output

Python is awesome

You can also use the + character to add a variable to another variable:

Example

x = "Python is "
y = "awesome"
z=x+y
print(z)

Output:

8
Python is awesome

Expressions:

An expression is a combination of values, variables, and operators. They are Arithmetic


Expression, Relational Expression and Logical Expressions.

Arithmetic Expressions are formed by using Arithmetic operators, Relational Expression is


formed by Relational operators and Logical expression is formed by using Logical operators
as listed below
Operators: In Python you can implement the following operations using the corresponding
tokens.

Operator Token Type

add + Arithmetic

subtract - Arithmetic

multiply * Arithmetic

Integer Division / Arithmetic

remainder % Arithmetic

and & Logical

or \ Logical

Less than < Relational

Greater than > Relational

Less than or equal to <= Relational

9
Greater than or equal to >= Relational

Check equality == Relational

Check not equal != Relational

10
Examples of Arithmetic Expression
Y=x + 17

c=x+y
The above expression will evaluate the expression on right and assign the result to the variable
on left

Examples of Relational Expression

a>=5
The above expression is true when the value stored in a is greater than or equal to 5

Examples of logical Expression


a >=5 & b >= 10
The above expression is true when the value stored in a is greater than or equal to 5 and the
value stored in b is greater than 10.

Precedence of Operators:

Operator precedence affects how an expression is evaluated.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first multiplies 3*2 and then adds into 7.

Example 1:

>>> 3+4*2

11

Multiplication gets evaluated before the addition operation

>>> (10+10)*2

40

Parentheses () overriding the precedence of the arithmetic operators

Example 2:
a = 20
11
b = 10
c = 15
d=5
e=0

e = (a + b) * c / d #( 30 * 15 ) / 5
print("Value of (a + b) * c / d is ", e)

e = ((a + b) * c) / d # (30 * 15 ) / 5
print("Value of ((a + b) * c) / d is ", e)

e = (a + b) * (c / d); # (30) * (15/5)

12
print("Value of (a + b) * (c / d) is ", e)

e = a + (b * c) / d; # 20 + (150/5)
print("Value of a + (b * c) / d is ", e)

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/opprec.py
Value of (a + b) * c / d is 90.0
Value of ((a + b) * c) / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0

To read value to a variable through key board


a= float (input(“Input Value”))
b= int(input(‘Input Value”))

c =string(input(“Input Value”))

k=a+b

print(k)

13
Control statements in Python
Conditional (Branching Statement -if):

The if statement contains a logical expression using which data is compared and a decision
is made based on the result of the comparison.
Syntax:
if expression:
statement(s)
If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if
statement is executed. If boolean expression evaluates to FALSE, then the first set of
code after the end of the if statement(s) is executed.

if Statement Flowchart:

Fig: Operation of if statement

Example: Python if Statement

# Example programme to print value of a if it is greater than 2

a=3
if a > 2:
print(a, "is greater")
print("done")

a = -1
if a < 0:
14
print(a, "a is smaller")
print("Finish")

Output:

C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/if1.py
3 is greater
done
-1 a is smaller
Finish

If-Else structure :

An else statement can be combined with an if statement. An else statement contains the
block of code (false block) that executes if the conditional expression in the if statement
resolves to 0 or a FALSE value.

The else statement is an optional statement and there could be at most only one else
Statement following if.

Syntax of if - else :

if test expression:
Body of if stmts
else:
Body of else stmts
If - else Flowchart :

15
Fig: Operation of if – else statement

Example of if - else:
# Programe to illustrate if .. else statement
a = int (input(‘Enter the number’))
if a>5:
print (“a is greater than 5”)
else:

print("a is smaller than or equal to 5")

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ifelse.py
enter the number 2
a is smaller than or equal to 5
----------------------------------------

Nested if : (If-elif-else):

The elif statement allows us to check multiple expressions for TRUE and execute a
block of code as soon as one of the conditions evaluates to TRUE. Similar to the else,
the elif statement is optional. However, unlike else, for which there can be at most one
statement, there can be an arbitrary number of elif statements following an if.

Syntax of if – elif - else :

If test expression:
16
Body of if stmts
elif test expression:
Body of elif stmts
else:
Body of else stmts

Flowchart of if – elif - else:

Fig: Operation of if – elif - else statement

Example of if - elif – else:

a=int(input('enter the number'))


b=int(input('enter the number'))
c=int(input('enter the number'))
if a>b:
print("a is greater")
elif b>c:
print("b is greater")
else:
print("c is greater")

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ifelse.py
enter the number5
enter the number2
enter the number9
a is greater
17
>>>
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ifelse.py
enter the number2
enter the number5
enter the number9
c is greater
-----------------------------
# Programme to illustrate the use of nested if..else structure
# Initialize a variable and and printing it as “true value” if it is 200,150 or 100 and “false
expression value otherwise”
var = 100 # initialize a variable
if var == 200:
print("1 - Got a true expression value")
print(var)
elif var == 150:
print("2 - Got a true expression value")
print(var)
elif var == 100:
print("3 - Got a true expression value")
print(var)
else:
print("4 - Got a false expression value")
print(var)
print("Good bye!")

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ifelif.py

3 - Got a true expression value

100

Good bye!

Problem: 1
To read the following details
Item Code
Descriptio
n
Quantity
Prize
18
Amount

And then compute the GST as follows


a. GST=2% of Amount for Amount < 5000
b. GST=3% of Amount for Amount>=5000
And then print a cash bill containing all details
Problem: 2
Modify the problem number 1 using if else statement modifies the problem in such a way
that the GST calculating in three levels.
a. GST=2% of Amount for Amount < 5000
b. GST=3% of Amount for Amount >5000 and <=10000
c. GST=4% of Amount for Amount >10000 and <=25000
d. GST=5% of Amount for Amount >25000

19

You might also like