0% found this document useful (0 votes)
4 views

Python Basics for AI Part 1

This document provides an overview of Python programming, including its characteristics, execution modes, and fundamental concepts such as tokens, keywords, identifiers, literals, and data types. It covers operators, error types, expressions, built-in functions, and data structures like lists and dictionaries. Additionally, it explains decision-making in Python and includes examples for better understanding.

Uploaded by

sunny.shah6498
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Basics for AI Part 1

This document provides an overview of Python programming, including its characteristics, execution modes, and fundamental concepts such as tokens, keywords, identifiers, literals, and data types. It covers operators, error types, expressions, built-in functions, and data structures like lists and dictionaries. Additionally, it explains decision-making in Python and includes examples for better understanding.

Uploaded by

sunny.shah6498
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Notes for AI students in python 3.

x
Python Programming
Python is an open source, object oriented and interpreted high level language developed by Guido van Rossum in
1991. It is case sensitive language.

Characteristics of Python
Following are important characteristics of Python Programming −

1. It supports functional and structured programming methods as well as OOP.


2. It can be used as a scripting language or can be compiled to byte-code for building large applications.
3. It provides very high-level dynamic data types and supports dynamic type checking.

Execution modes - interactive mode and script mode


Interactive/ shell mode Script/program mode
1. execution takes place 1.debugging takes place
2. a single line of python code can be executed 2. multiple lines of python code can be executed at a
go
3. the code cannot be saved for later use 3. the code can be saved for later use
4. used for learning various use of methods and 4. used for program development
functions

okens - smallest individual unit of a python program.

Keyword - Reserved word that are case sensitive and has a special meaning. They can’t be used as an identifier.
There are 36 keywords.

['False', 'None', 'True', ' peg_parser ', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del',
'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise',
'return', 'try', 'while', 'with', 'yield']

Note: memorize all the keywords and learn the use of keywords highlighted

Identifiers - Meaningful names given to any variable/reference/object, constant, function or module etc.
Python is a case-sensitive language and it has some rules and regulations to name an identifier. Here are some rules
to name an identifier:-
• As stated above, Python is case-sensitive. So case matters in naming identifiers. And hence geeks and Geeks are
two different identifiers.
• Identifier starts with a capital letter (A-Z) , a small letter (a-z) or an underscore( _ ). It can’t start with any other
character.
• Except for letters and underscore, digits can also be a part of identifier but can’t be the first character of it.
• Any other special characters or whitespaces are strictly prohibited in an identifier.
• An identifier can’t be a keyword.

Literals - A fixed or a constant value.


Page 1 of 13
Examples: 34, 89.67, “mms”, None, True, False, ‘a’, 2+3j, [1,2,3], (3,4,5), {1:”mms”,2::dps”}
Variable/ references/ objects - Technically in python it is called a reference that points to a memory that stores
a value.

Example:

Roll=12

Roll 12
String- The text enclosed in quotes (single/double/triple).
Comment- Comments are non-executable statement beginning with # sign. A multiline comment can be
represented either of 2 ways:

Python is an object oriented


and an interpreted language.

#Python is an object oriented ‘’’Python is an object oriented


#and an interpreted language. and an interpreted language.’’’

Operator – performs some action on data


1. Arithmetic: +(addition operator) , -(subtraction operator) , * (multiplication operator), / (division operator), %
(remainder operator), **(exponential operator) , // (floor division operator)
Sample code

>>> 5+2 >>> 5//2


7 2
>>> 5-2 >>> 5%2
3 1
>>> 5*2 >>> 5**2
10 25
>>> 5/2
2.5

2. Relational/comparison: < , > , <= , >= , = =, !=

This creates a condition which results either True or False. Generally used with if and while statements.

Sample code

>>> 5>2 >>> 5<=2


True False
>>> 5<2 >>> 5==2
False False
>>> 5>=2 >>> 5!=2
True True
Note: == actually checks the values.

3. Assignment: =
This directly assigns a value or indirectly assigns a value or a literal of another variable.
Sample code

>>> x=10 >>> x=(1,2,3)


>>> x=True >>> x=[2,3,4]
>>> x=7.8 >>> x={1:"abc",2:"cde"}
>>> x=3+8j
4. Augmented assignment operator: += , -= , *= , /=, %= , **= , //=
This actually combines 2 statements like:
Page 2 of 13
x+=5 means x=x+5
i.e. first 5 is added to x and then the result is assigned to x.

Sample code

>>> x=10
>>> x+=5
>>> print(x)
>>> 15
5. Logical: and , or , not
and, or actually combines multiple conditions while not gives the complement
like x>5 and y<10 means
i.e. if value of x is 7 and y is 20 then x>5 will give True and y<10 will give False. And the True and False will give
False. Generally used with if and while statements.

6. Identity operators: is , is not


Sample code

>>> x=10
>>> y=10
>>> x is y
>>> True
Note: is actually checks the memory id.

7. Membership: in , not in
in operator actually checks the presence of a part in a string/list/tuple/dictionary. Generally used with for and if
statements
Sample code

>>> x="abcdef" >>> d={1:"abc",2:"cde",3:"mnk"}


>>> "bc" in x >>> 2 in d
True True
>>> x=[1,2,3,4,5] >>> 5 in d
>>> 3 in x False
True

Page 3 of 13
Precedence of operators
The following table lists all operators from highest precedence to lowest.

Operator Description

** Exponentiation (raise to the power)

+- unary plus and minus

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction

<= < > >= Comparison operators

<> == != Equality operators

= %= /= //= -= += *= **= Assignment operators

is is not Identity operators

in not in Membership operators

not or and Logical operators

Data types in python: In python type of reference or a variable is stated as a class


1. bool: It is a data structure of type boolean used to store either value True or False. By default it stores False. It is
immutable.
Example to create a boolean type reference
By assigning a value
X=True
By declaring
X=bool()

2. int: It is a data structure of type numeric used to store a whole number. By default it stores 0. It is immutable.
Example to create a integer type reference
By assigning a value
X=45
By declaring
X=int()
Similarly for the rest

3. float: It is a data structure of type numeric used to store a number with a fractional part. By default it stores 0.0.
It is immutable.

4. Complex: It is a data structure of type numeric used to store a number having real and imaginary part (a+bj) . It is
immutable.

5. String: It is a data structure of type sequence used to store a collection of characters enclosed in single, double
or triple quotes. It is immutable, ordered and indexed. Can store duplicate values.

6. List: It is a data structure of type sequence used to store a list of comma separated values of any data type
between square [ ] brackets. It is mutable, ordered and indexed. Can store duplicate values.

7. Tuple: It is a data structure of type sequence used to store a list of comma separated values of any data type
between parentheses ( ). It is immutable, ordered and indexed. Can store duplicate values.

8. Set: It is a data structure used to store a list of comma separated values of any data type between curly braces {}
Page 4 of 13
. It is immutable, unordered and unindexed. Cannot store duplicate values.
9. Dictionary: It is a data structure of type mapping used to store a collection of comma-separated key:value pairs ,
within curly braces {}. It is mutable and unordered. Can store duplicate values while the keys are immutable and
unique.

Errors and its types


Syntax errors: These errors occur during runtime but suspends execution temporarily giving the error till it is
removed.
Examples
• Invalid syntax
• Indentation mismatch

Runtime errors: Also known as exceptions. They occur during execution of the program and terminates in between
exiting back to the shell giving a traceback.

Some examples
1. ZeroDivisionError:Raised when division or modulo by zero takes place for all numeric type
2. IndexError:Raised when an index is not found in a sequence.
3. NameError: Raised when an identifier is not found in the local or global namespace.
4. IndentationError: Raised when indentation is not specified properly

Logical errors: These errors are identified by the wrong output or an unexpected output. Example: to find the area
of a circle:
x=int(input(“Enter radius: “))
area=22/7*r+r
print(“area = “,area)
because of the wrong formula, the output is incorrect. This would be called a logical error

Expressions, it’s evaluation per precedence


1 Exponential valid for integers and decimal values
2**3 8
2**3**2 512
2 Multiplication
2*3 8
2.4*4.5
“mira”*3 or 3*”mira” “miramiramira”
3 Division
4 Floor division Gives the nearest smaller integer
>>> 25//3
8
5 Remainder or modulous x%y= x – (x//y) * y
>>> 25%3 remainder=numerator –
1 quotient*denominator

6 Addition
2+3
2.5+3
2.5+3.5
“mira”+”model”

Page 5 of 13
7 3+5*5**2**2-8/4
3+5*5**4-8/4
3+5*625-8/4
3+3125-8/4
3+3125-2.0
3+3125-2.0
3128-2.0
3126.0

Built-in Functions

print and input functions: print() is used to display or give output to the user, while input() is to accept values from
the user

print(“hello”) hello
>>> print('hello') hello
>>> print('''hello mira hello mira
how are how are
you''') you
>>> print("he'll'o") he'll'o
>>> print("he'''ll'''o") he'''ll'''o
>>> print('he"ll"o') he"ll"o
>>> print('''he"ll"o he"ll"o 'mira' how are you
'mira' how are you''')
>>> input() '3'
3

>>> x=input()
mira
>>> x=input("Enter a Enter a number
number")
78

Optional parameters of print


end and sep are optional parameters of Python. The end parameter basically prints after all the output objects
present in one output statement have been returned. the sep parameter differentiates between the objects.
Code Output Remarks
>>>print(“hello”,”how”,”are”,”you”,sep=”@”) hello@how@are@you
>>>print(“hello”,”how”,”are”,”you”,end=”@”) hello how are you@
>>> print("hello",end="@");print("how") hello@how
>>>print("hello",”how”,”are”,”you”) hello how are you , gives a space by
default
>>>print("hello",”how”,”are”,”you”,sep=””) hellohowareyou Using sep=”” space
gerated by , is
suppressed

Python Lists
List is a python data structure that represents a heterogeneous collection or a sequence of items which is ordered
and mutable. Allows duplicate members. In Python, lists are written with square brackets.
Creating a List
L1 = ["apple", "banana", "cherry"]
print(L1)

Access Items
Page 6 of 13
You access the list items by referring to the index number:
Example
Print the second item of the list:
print(L1[1]) or print(L1[-2])

Change Item Value


To change the value of a specific item, refer to the index number:
Example

Page 7 of 13
Change the second item:
L1[1] = "blackcurrant"
print(L1)

Check if Item Exists


To determine if a specified item is present in a list use the in keyword:

Example
Check if "apple" is present in the list:
L = ["apple", "banana", "cherry"]
if "apple" in L:
print("Yes, 'apple' is in the fruits list")

List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
L = ["apple", "banana", "cherry"]
print(len(L))

Traversing a List You can loop through the list items by using a for loop:
Example
Print all items in the list, one by one:
L = ["apple", "banana", "cherry"]
method 1
for x in L:
print(x)

method 2
for i in range(len(L)):
print(L[i])

Add Items in a list


To add an item to the end of the list, use the append() method:
Example
Using the append() method to append an item:
L = ["apple", "banana", "cherry"]
L.append("orange")
print(L)

To add an item at the specified index, use the insert() method:


Example
Insert an item as the second position:
L = ["apple", "banana", "cherry"]
L.insert(1, "orange")
print(L)

Remove an Item from a list There are several methods to remove items from a list:
Example
The remove() method removes the specified item:
L = ["apple", "banana", "cherry"]
L.remove("banana")
print(L)

Page 8 of 13
Example
The pop() method removes the specified index, (or the last item if index is not specified):
L = ["apple", "banana", "cherry"]
L.pop()
print(L)

Dictionary
Dictionary is an unordered collection of items(key-value pairs). Each key is separated from its value by a colon (:),
the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without
any items is written with just two curly braces, like this: {}.

Create a dictionary
D = { "brand": "Ford", "model": "Mustang", "year": 1964 }
print(D)

Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:
Example
Get the value of the "model" key:
x = D["model"]

Change Values
You can change the value of a specific item by referring to its key name:
Example
Change the "year" to 2018:
D["year"] = 2018

Traverse through a Dictionary


You can loop through a dictionary by using a for loop.
When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return
the values as well.
Example
Print all key names in the dictionary, one by one:
for x in D:
print(x)

Page 9 of 13
Print all values in the dictionary, one by one:
for x in D:
print(D[x])

Adding an item to the dictionary is done by using a new index key and assigning a value to it:
D["color"] = "red"
print(D)

Removing Items
There are several methods to remove items from a dictionary:
Example
The pop() method removes the item with the specified key name:
D.pop("model")
print(D)

Example
The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead):
D.popitem()
print(D)

Decision making and Iteration in Python


Python programming language assumes any non-zero and non-null values as TRUE, and if it is either
zero or null, then it is assumed as FALSE value.

If ..elif..else
Python programming language provides following types of decision making statements.

Loops
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.
Here, statement(s) may be a single statement or a block of statements with uniform indent. 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
loop.

Syntax
while expression:
statement(s)

Page 10 of 13
Infinite loop Loop stepping Loop stepping downward
while True: upward i=10
print(“Hello”) i=1 sum=0
sum=0 while i>=1:
while i<=5: sum+=i
sum+=i i-=3
i+=1 print(“Total is ”,sum)
print(“Total is ”,sum)
Loop with else
i=1
while i<=5: The else of while gets executed only when the break
x=int(input(“enter x”)) is not executed. In other words when the loop gets
if x%5==0: terminated normally.
break
sum+=x
i+=1
else:
print(“Thank you”,i)
print(“Total is ”,sum,i)

Sample output when x


is entered as 2,4,5
Total is 6,2

Sample output when x


is entered as
2,4,6,7,6,9
Thank you 6
Total is 34 6
2 for loop
Executes a sequence of statements multiple times and abbreviates the code that manages the
loop variable.

Syntax
for iterating_var in sequence:
statements(s)

Page 11 of 13
for i in “india”: for i in range(5): for i in range(1,5):
print(i) print(i) print(i)

for i in range(1,5,2): for i in range(5,1,-1): for i in range(5,1,-2):


print(i) print(i) print(i)

for i in range(1,6): Sample output x= 2,4,7,9,12


x=int(input(“enter x”)) Thank you 5
if x%5==0: Total is 34 5
break
sum+=x x=
else: 2,4,7,5
print(“Thank you”,i) Total
print(“Total is ”,sum,i) is 13 3

The Infinite Loop


A loop becomes infinite loop if a condition never becomes FALSE. You must be cautious 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. Example:

while True:

print(“Hello”)

Using else Statement with Loops


Python supports having 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 range function in detail


The value we put in the range function determines how many times we will loop. The way range works is it
produces a list of numbers from zero to the value minus one. For instance, range(5) produces five values: 0, 1, 2, 3,
and 4.

If we want the list of values to start at a value other than 0, we can do that by specifying the starting value. The
statement range(1,5) will produce the list 1, 2, 3, 4. This brings up one quirk of the range function—it stops one
short of where we think it should. If we wanted the list to contain the numbers 1 through 5 (including 5), then we
would have to do range(1,6).

Another thing we can do is to get the list of values to go up by more than one at a time. To do this, we can specify
an optional step as the third argument. The statement range(1,10,2) will step through the list by twos, producing 1,
3, 5, 7, 9.

To get the list of values to go backwards, we can use a step of -1. For instance, range(5,1,-1) will produce the values
5, 4, 3, 2, in that order. (Note that the range function stops one short of the ending value 1). Here are a few more
examples:

Statement Values generated

range(10) 0,1,2,3,4,5,6,7,8,9
Page 12 of 13
range(1,10) 1,2,3,4,5,6,7,8,9

range(3,7) 3,4,5,6

range(2,15,3) 2,5,8,11,14

range(9,2,-1) 9,8,7,6,5,4,3

Here is an example program that counts down from 5 and then prints a message.

for i in range(5,0,-1):

print(i, end=' ')


print('Blast off!!')
54321
Blast off!!!

The end=' ' just keeps everything on the same line.

Page 13 of 13

You might also like