Python Basics for AI Part 1
Python Basics for AI Part 1
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 −
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.
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:
This creates a condition which results either True or False. Generally used with if and while statements.
Sample code
3. Assignment: =
This directly assigns a value or indirectly assigns a value or a literal of another variable.
Sample code
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.
>>> 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
Page 3 of 13
Precedence of operators
The following table lists all operators from highest precedence to lowest.
Operator Description
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.
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
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
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])
Page 7 of 13
Change the second item:
L1[1] = "blackcurrant"
print(L1)
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])
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
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)
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.
Python programming language provides following types of loops to handle looping requirements.
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)
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)
while True:
print(“Hello”)
• 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.
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:
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):
Page 13 of 13