Introduction to Python - WordPress.com · Python for Machine Learning Website: K. Anvesh, Dept. of...

22
Python for Machine Learning Website: www.anveshitse.wordpress.com K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering Introduction to Python Keywords Keywords are special words which are reserved and have a specific meaning. Python has a set of keywords that cannot be used as variables in programs. All keywords in Python are case sensitive. So, you must be careful while using them in your code. We’ve just captured here a snapshot of the possible Python keywords Keywords in Python You can find the keywords of Python in the prompt and can find the description and usage procedure of the keyword in the prompt itself. To do so, you can follow the below steps. 1. Open the python command prompt window, 2. Type as >>>help() 3. In that choose keywords and type as >>> keywords 4. Now you can select any one of the keyword and find the description and syntax of the selected “keyword”

Transcript of Introduction to Python - WordPress.com · Python for Machine Learning Website: K. Anvesh, Dept. of...

Page 1: Introduction to Python - WordPress.com · Python for Machine Learning Website: K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering In the above example x,

Python for Machine Learning

Website: www.anveshitse.wordpress.com K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering

Introduction to Python

Keywords

Keywords are special words which are reserved and have a specific meaning. Python has a set of keywords that

cannot be used as variables in programs.

All keywords in Python are case sensitive. So, you must be careful while using them in your code. We’ve just

captured here a snapshot of the possible Python keywords

Keywords in Python

You can find the keywords of Python in the prompt and can find the description and usage procedure of

the keyword in the prompt itself.

To do so, you can follow the below steps.

1. Open the python command prompt window,

2. Type as >>>help()

3. In that choose keywords and type as >>> keywords

4. Now you can select any one of the keyword and find the description and syntax of the selected

“keyword”

Page 2: Introduction to Python - WordPress.com · Python for Machine Learning Website: K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering In the above example x,

Python for Machine Learning

Website: www.anveshitse.wordpress.com K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering

Note: You should be aware is the above list may change. The language could get away with some of the old

keywords and bring in new ones in future releases.

Identifiers

Python Identifiers are user-defined names to represent a variable, function, class, module or any other object. If you

assign some name to a programmable entity in Python, then it is nothing but technically called an identifier.

Python language lays down a set of rules for programmers to create meaningful identifiers.

Identifiers are the names used to identify things in your code. Python will regard any word that has not been

commented out, delimited by quotation marks, or escaped in some other way as an identifier of some kind.

An identifier is just a name label, so it could refer to more or less anything including commands, so it helps to keep

things readable and understandable if you choose sensible names. You need to be careful to avoid choosing names

that are already being used in your current Python session to identify your new variables. Choosing the same name

as something else can make the original item with that name inaccessible.

This could be particularly bad if the name you choose is an essential part of the Python language,

but luckily Python does not allow you to name variables after any essential parts of the language.

Guidelines For Creating Identifiers In Python.

1. To form an identifier, use a sequence of letters either in lowercase (a to z) or uppercase (A to Z). However, you can

also mix up digits (0 to 9) or an underscore (_) while writing an identifier.

Page 3: Introduction to Python - WordPress.com · Python for Machine Learning Website: K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering In the above example x,

Python for Machine Learning

Website: www.anveshitse.wordpress.com K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering

For example – Names like shapeClass, shape_1, and upload_shape_to_db are all valid identifiers.

2. You can’t use digits to begin an identifier name. It’ll lead to the syntax error.

For example – The name, 0Shape is incorrect, but shape1 is a valid identifier.

3. Whenever the expression changes, Python associates a new object (a chunk of memory) to the variable for

referencing that value. And the old one goes to the garbage collector.

Example.

>>> test = 10

>>> id(test)

1716585200

>>> test = 11

>>> id(test)

1716585232

>>>

4. Also, for optimization, Python builds a cache and reuses some of the immutable objects, such as small integers

and strings.

5. An object is just a region of memory which can hold the following.

The actual object values.

A type designator to reflect the object type.

The reference counter which determines when it’s OK to reclaim the object.

6. It’s the object which has a type, not the variable. However, a variable can hold objects of different types as and

when required.

Example.

>>> test = 10

>>> type(test)

<class 'int'>

>>> test = 'techbeamers'

>>> type(test)

<class 'str'>

>>> test = {'Python', 'C', 'C++'}

>>> type(test)

<class 'set'>

>>>

Page 4: Introduction to Python - WordPress.com · Python for Machine Learning Website: K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering In the above example x,

Python for Machine Learning

Website: www.anveshitse.wordpress.com K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering

Variables

A variable is a memory location where a programmer can store a value. Example :

roll_no, amount, name etc.

Value is either string, numeric etc. Example : "Sara", 120, 25.36 Variables are created when first assigned.

Variables must be assigned before being referenced. The value stored in a variable can be accessed or updated later. No declaration required

The type (string, int, float etc.) of the variable is determined by Python

The interpreter allocates memory on the basis of the data type of a variable.

Variable name rules:

Must begin with a letter (a - z, A - B) or underscore (_) Other characters can be letters, numbers or _

Case Sensitive Can be any (reasonable) length

There are some reserved words which you cannot use as a variable name because Python uses them for other things.

Python Assignment statements:

The assignment statement creates new variables and gives them values.

Basic assignment statement in Python is :

Syntax

<variable> = <expr>

Where the equal sign (=) is used to assign value (right side) to a variable name (left side). See the following statements :

1. >>> Item_name = "Computer" #A String

2. >>> Item_qty = 10 #An Integer 3. >>> Item_value = 1000.23 #A floating point 4. >>> print(Item_name)

5. Computer 6. >>> print(Item_qty)

7. 10 8. >>> print(Item_value)

9. 1000.23

Page 5: Introduction to Python - WordPress.com · Python for Machine Learning Website: K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering In the above example x,

Python for Machine Learning

Website: www.anveshitse.wordpress.com K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering

One thing is important, assignment statement read right to left only.

Example :

a = 12 is correct, but 12 = a does not make sense to Python, which creates a syntax error. Check it in Python Shell.

view plaincopy to clipboardprint?

1. >>> a = 12 2. >>> 12 = a

3. SyntaxError: can't assign to literal

4. >>>

Multiple Assignment:

The basic assignment statement works for a single variable and a single

expression.

You can also assign a single value to more than one variables simultaneously.

Syntax

var1=var2=var3...varn= = <expr>

Example :

x = y = z = 1

Now check the individual value in Python Shell.

1. >>> x = y = z = 1 2. >>> print(x)

3. 1

4. >>> print(y) 5. 1 6. >>> print(z)

7. 1 8. >>>

Here is an another assignment statement where the variables assign many values at the same time. Syntax

<var>, <var>, ..., <var> = <expr>, <expr>, ..., <expr> Example :

x, y, z = 1, 2, "abcd"

Page 6: Introduction to Python - WordPress.com · Python for Machine Learning Website: K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering In the above example x,

Python for Machine Learning

Website: www.anveshitse.wordpress.com K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering

In the above example x, y and z simultaneously get the new values 1, 2 and "abcd". view plaincopy to clipboardprint?

1. >>> x,y,z = 1,2,"abcd"

2. >>> print(x) 3. 1

4. >>> print(y) 5. 2

6. >>> print(z) 7. abcd

You can reuse variable names by simply assigning a new value to them :

1. >>> x = 100 2. >>> print(x)

3. 100 4. >>> x = "Python"

5. >>> print(x) 6. Python

7. >>>

Swap variables: Python swap values in a single line and this applies to all objects in python. Syntax

var1, var2 = var2, var1

Example :

1. >>> x = 10

2. >>> y = 20 3. >>> print(x)

4. 10

5. >>> print(y) 6. 20

7. >>> x, y = y, x

8. >>> print(x) 9. 20

10. >>> print(y) 11. 10

12. >>>

Page 7: Introduction to Python - WordPress.com · Python for Machine Learning Website: K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering In the above example x,

Python for Machine Learning

Website: www.anveshitse.wordpress.com K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering

Local and global variables in python:

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

Example :

1. var1 = "Python"

2. def func1():

3. var1 = "PHP" 4. print("In side func1() var1 = ",var1)

5.

6. def func2(): 7. print("In side func2() var1 = ",var1)

8. func1()

9. func2()

In side func1() var1 = PHP

In side func2() var1 = Python

You can use a global variable in other functions by declaring it as global keyword :

Example :

1. def func1():

2. global var1 3. var1 = "PHP"

4. print("In side func1() var1 = ",var1)

5.

6. def func2():

7. print("In side func2() var1 = ",var1) 8. func1() 9. func2()

Output :

In side func1() var1 = PHP

In side func2() var1 = PHP

Page 8: Introduction to Python - WordPress.com · Python for Machine Learning Website: K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering In the above example x,

Python for Machine Learning

Website: www.anveshitse.wordpress.com K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering

Do follow the reference books for more information and programs.

Website: www.anveshitse.wordpress.com

Indentation:

Python uses whitespace (spaces and tabs) to define program blocks whereas other languages like C, C++ use braces ({}) to indicate blocks of codes for class, functions or flow control. The number of whitespaces (spaces and tabs) in the indentation is not fixed, but all statements within the block must be the indented same amount. In the following program, the block statements

have no indentation.

• Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements.

• The enforcement of indentation in Python makes the code look neat and clean. This results into Python programs that look similar and consistent

• Most of the programming languages like C, C++, Java use braces { } to define a block of code. Python uses indentation.

• A code block (body of a function, loop etc.) starts with indentation and ends

with the first unindented line. The amount of indentation is up to you, but it must be consistent throughout that block.

• Generally four whitespaces are used for indentation and is preferred over tabs. Here is an example.

Operators

Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the operator operates on is called the operand.

For example:

>>> 2+3

5

Different Types of Operators in Python

• Arithmetic Operators

• Comparison (Relational) Operators

• Logical (Boolean) Operators

• Bitwise Operators

• Assignment Operators

Page 9: Introduction to Python - WordPress.com · Python for Machine Learning Website: K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering In the above example x,

Python for Machine Learning

Website: www.anveshitse.wordpress.com K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering

• Special Operators

i. Indentity Operators

ii. Membership Operators

Page 10: Introduction to Python - WordPress.com · Python for Machine Learning Website: K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering In the above example x,

Python for Machine Learning

Website: www.anveshitse.wordpress.com K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering

Arithmetic Operators

Comparison (Relational) Operators

Page 11: Introduction to Python - WordPress.com · Python for Machine Learning Website: K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering In the above example x,

Python for Machine Learning

Website: www.anveshitse.wordpress.com K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering

Logical Operators

Assignment Operators

Page 12: Introduction to Python - WordPress.com · Python for Machine Learning Website: K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering In the above example x,

Python for Machine Learning

Website: www.anveshitse.wordpress.com K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering

Identity Operators

Membership Operators

Order of Operators

For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a useful way to remember the

rules.

Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want

Exponentiation has the next highest precedence

Multiplication and Division have the same precedence, which is higher than Addition and Subtraction

Operators with the same precedence are evaluated from left to right (except exponentiation)

Page 13: Introduction to Python - WordPress.com · Python for Machine Learning Website: K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering In the above example x,

Python for Machine Learning

Website: www.anveshitse.wordpress.com K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering

Loops in python

In general, statements are executed sequentially: The first statement in a function is executed first, followed by

the second, and so on. There may be a situation when you need to execute a block of code several number of

times.

Programming languages provide various control structures that allow for more complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple times. The following diagram

illustrates a loop statement −

Python programming language provides following types of loops to handle looping requirements.

Sr.No. 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.

A while loop statement in Python programming language repeatedly executes a target

statement as long as a given condition is true.

The syntax of a while loop in Python programming language is −

while expression: statement(s)

Here, statement(s) may be a single statement or a block of statements. The condition may

be any expression, and true is any non-zero value. The loop iterates while the condition is true.

When the condition becomes false, program control passes to the line immediately following the

Page 14: Introduction to Python - WordPress.com · Python for Machine Learning Website: K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering In the above example x,

Python for Machine Learning

Website: www.anveshitse.wordpress.com K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering

loop.

In Python, all the statements indented by the same number of character spaces after a

programming construct are considered to be part of a single block of code. Python uses

indentation as its method of grouping statements.

Flow Diagram

Here, key point of the while loop is that the loop might not ever run. When the condition is

tested and the result is false, the loop body will be skipped and the first statement after the

while loop will be executed.

Example: -

The Infinite Loop

A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when

using while loops because of the possibility that this condition never resolves to a FALSE value.

This results in a loop that never ends. Such a loop is called an infinite loop.

An infinite loop might be useful in client/server programming where the server needs to run

continuously so that client programs can communicate with it as and when required.

Example:

var = 1 while var == 1 : # This constructs an infinite loop num = input("Enter a number :") print "You entered: ", num print "Good bye!"

Using else Statement with Loops

Page 15: Introduction to Python - WordPress.com · Python for Machine Learning Website: K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering In the above example x,

Python for Machine Learning

Website: www.anveshitse.wordpress.com K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering

Python supports to have an else statement associated with a loop statement.

If the else statement is used with a for loop, the else statement is executed when the

loop has exhausted iterating the list.

If the else statement is used with a while loop, the else statement is executed when the

condition becomes false.

The following example illustrates the combination of an else statement with a while statement

that prints a number as long as it is less than 5, otherwise else statement gets executed.

Example:

count = 0 while count < 5: print count, " is less than 5" count = count + 1 else: print count, " is not less than 5"

Single Statement Suites

Similar to the if statement syntax, if your while clause consists only of a single statement, it

may be placed on the same line as the while header.

Example:

flag = 1 while (flag): print 'Given flag is really true!' print "Good bye!"

Note: It is better not try above example because it goes into infinite loop and

you need to press CTRL+C keys to exit.

2 for loop

Executes a sequence of statements multiple times and abbreviates the code that manages the loop

variable.

It has the ability to iterate over the items of any sequence, such as a list or a string

Syntax: for iterating_var in sequence: statements(s)

Concept If a sequence contains an expression list, it is evaluated first. Then, the first item in the

sequence is assigned to the iterating variable iterating_var. Next, the statements block is

executed. Each item in the list is assigned to iterating_var, and the statement(s) block is

executed until the entire sequence is exhausted.

Example:

for it in 'Python': # First Example

Page 16: Introduction to Python - WordPress.com · Python for Machine Learning Website: K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering In the above example x,

Python for Machine Learning

Website: www.anveshitse.wordpress.com K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering

print ('Current index char is :', it) students = ['abc', 'xyz', 'pqr'] for candidate in students: # Second Example print ('Current Candidate :', candidate) print "Good bye!"

Iterating by Sequence Index

An alternative way of iterating through each item is by index offset into the sequence itself

Using else Statement with Loops

Python supports to have an else statement associated with a loop statement

If the else statement is used with a for loop, the else statement is executed when

the loop has exhausted iterating the list.

If the else statement is used with a while loop, the else statement is executed

when the condition becomes false.

The following example illustrates the combination of an else statement with a for

statement that searches for prime numbers from 10 through 20.

for num in range(10,20): #to iterate between 10 to 20 for i in range(2,num): #to iterate on the factors of the number if num%i == 0: #to determine the first factor j=num/i #to calculate the second factor print (“%d equals %d * %d” % (num,i,j)) break #to move to the next number, the #first FOR else: # else part of the loop print (num, “is a prime number”

3 nested loops

You can use one or more loop inside any another while, for or do..while loop.

Python programming language allows to use one loop inside another loop. Following section shows few

examples to illustrate the concept.

Syntax: 1. for iterating_var in sequence: for iterating_var in sequence: statements(s) statements(s)

2. while expression:

Page 17: Introduction to Python - WordPress.com · Python for Machine Learning Website: K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering In the above example x,

Python for Machine Learning

Website: www.anveshitse.wordpress.com K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering

while expression: statement(s) statement(s)

Note: A final note on loop nesting is that you can put any type of loop inside of any other

type of loop. For example a for loop can be inside a while loop or vice versa.

Cross Product Example:

Loop Control Statements Loop control statements change execution from its normal sequence. When execution leaves a scope, all

automatic objects that were created in that scope are destroyed.

Python supports the following control statements. Click the following links to check their detail.

Let us go through the loop control statements briefly

Sr.No. Control Statement & Description

Page 18: Introduction to Python - WordPress.com · Python for Machine Learning Website: K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering In the above example x,

Python for Machine Learning

Website: www.anveshitse.wordpress.com K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering

1 break statement

Terminates the loop statement and transfers execution to the statement immediately following the loop.

It terminates the current loop and resumes execution at the next statement, just like the traditional break

statement in C.

The most common use for break is when some external condition is triggered requiring a hasty exit from a

loop. The break statement can be used in both while and for loops.

If you are using nested loops, the break statement stops the execution of the innermost loop and start

executing the next line of code after the block.

Example :

2 continue statement

Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

It returns the control to the beginning of the while loop.. The continuestatement rejects all the remaining

statements in the current iteration of the loop and moves the control back to the top of the loop.

The continue statement can be used in both while and for loops.

Example :

Page 19: Introduction to Python - WordPress.com · Python for Machine Learning Website: K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering In the above example x,

Python for Machine Learning

Website: www.anveshitse.wordpress.com K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering

3 pass statement

The pass statement in Python is used when a statement is required syntactically but you do not want any

command or code to execute.

It is used when a statement is required syntactically but you do not want any command or code to execute.

The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places

where your code will eventually go, but has not been written yet

Page 20: Introduction to Python - WordPress.com · Python for Machine Learning Website: K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering In the above example x,

Python for Machine Learning

Website: www.anveshitse.wordpress.com K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering

Conditional Statements

Control Flow: In all most all programming languages the control flow statements are classified

as Selection Statements, Loop Statements, or Iterative Statement, and Jump Statements. Under

the Selection statements in Python we have if, elif and else statement. Under the loop statements

we have for and while statements. Under the Jump statements we have break, continue and

pass statements..

If statement - The if statement is used for conditional execution. An if statement is followed

by a Boolean expression, which is evaluated to either True or False. If Boolean expression is

evaluated to True, the block which contains one or more statements will be executed. Otherwise,

the block followed by the “else” statement is executed. The general form of if statement will be

as follow in Python:

if boolena_expression: statement(s) # block of statements inside if else: statement(s) # block of statements inside else

Example program: Write a Program whether a given Number if even or Odd.

Evenodd.py

#read the number from keyboard

n=input("enter any number :")

if(n%2==0): #test the number

print ("It is Even")

else:

print ("It is Odd")

Output:

enter any number :13

It is Odd

>>>

===========================

enter any number :12

It is Even

>>>

if –elif-else statements This combination of statements is used, whenever; one among multiple alternatives needs to be

selected. It selects exactly one block of statements if and only if, one of the Boolean expressions

is evaluated to True, otherwise block inside the “else” statement will be executed, if present.

General form of if-elif-else will be as follow:

if (boolean_expression):

Block of statements

elif(boolean_expression):

Page 21: Introduction to Python - WordPress.com · Python for Machine Learning Website: K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering In the above example x,

Python for Machine Learning

Website: www.anveshitse.wordpress.com K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering

Block of statements

elif(boolean_expression):

else:

Block of statements

Write a Python program to check the whether a given character is Vowel or Consonant.

Vowel.py output

#vowel or Consonant

ch='i'

if ch=='a' or ch=='A':

print "Vowel"

elif ch=='e' or ch=='E':

print "Vowel"

elif ch=='i' or ch=='I':

print "Vowel"

elif ch=='o' or ch=='O':

print "Vowel"

elif ch=='u' or ch=='U':

print "Vowel"

else:

print "Consonant"

Output:

Vowel

Write a Python program to find the grade of a Student for the marks secured in 5 subjects.

#read marks for 5 subjects

total=0

s1=input("Enter marks for s1:")

s2=input("Enter marks for s2:")

s3=input("Enter marks for s3:")

s4=input("Enter marks for s4:")

s5=input("Enter marks for s5:")

#find the total

total=(s1+s2+s3+s4+s5)

print "The Total is :",total

#find the avg

avg=total/5

if avg>90 and avg<100:

print "Grade is A+"

elif avg>80 and avg <90:

print "Grade is A"

elif avg>70 and avg <80:

print "Grade is B+"

elif avg>60 and avg <70:

Page 22: Introduction to Python - WordPress.com · Python for Machine Learning Website: K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering In the above example x,

Python for Machine Learning

Website: www.anveshitse.wordpress.com K. Anvesh, Dept. of Information Technology Vardhaman College of Engineering

print "Grade is B"

elif avg>50 and avg <60:

print "Grade is C"

else:

print "Grade is D"

Output:

Enter marks for s1:78

Enter marks for s2:90

Enter marks for s3:96

Enter marks for s4:98

Enter marks for s5:93

The Total is : 455

Grade is A+