AI_Python_Lab1
AI_Python_Lab1
Lab objective:
– Python Environment setup
– Introduce some basic operations
– Comparison operators and Decision making
– Loops
– Functions
Introduction
Why python?
● Easy to learn
● Focused on code readability
● Express ideas in fewer lines of code (compared to Java and C++)
● Object-oriented
● Powerful, scalable
● Lots of libraries
Python versus C
Python is similar to C syntax with some exceptions such as
● missing operators: ++, --
● no {} for blocks; uses whitespace
● different keywords
● lots of extra features
● no type declarations
Python IDLE
IDLE is the standard Python development environment. Its name is an acronym of
"Integrated DeveLopment Environment". It works well on both Unix and Windows
platforms.
It has a Python shell window, which gives you access to the Python interactive mode. It
also has a file editor that lets you create and edit existing Python source files.
Environment Setup
● Download python from the following link then install
https://www.python.org/ftp/python/3.5.0/python-3.5.0.exe
● Launch python IDLE
● Run some basic commands
➔ You can type Python code directly into this shell, at the '>>>' prompt.
Whenever you enter a complete code fragment, it will be executed. For
instance, typing:
>>> print
("hello world")
and pressing ENTER, will cause the following to be displayed:
Hello world
➔ You can open new file and type your code inside by clicking on File->new
File in IDLE menu bar then typing your code and saving the file with “.py”
extension. You can check the code syntax and run the new file from the
menu bar (run->check Module, run->run Module)
Let the students try the following commands on IDLE
Python is completely object oriented, and not "statically typed". You do not need to
declare variables before using them, or declare their type. Every variable in Python is an
object.
Numbers
Python supports four different numerical types (no type declaration)
● int (signed integers)
● long (long integers, they can also be represented in octal and hexadecimal)
Examples
myInt=7
myFloat = 7.0
myFloat = float (7) #casting int to float
Python Strings
● Strings in Python are identified as a contiguous set of characters represented in
single or double quotation marks.
● Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes
starting at 0 in the beginning of the string and -1 at the end.
● The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator. For example −
Hello World!
llo
llo World!
Hello World!TEST
Hello World
Multiple Assignment
a=b=c=1
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.”Mohamed”
Student Practice
Write a python program that reads temperature in Fahrenheit and transfer it to
Celsius then print.
Transfer equation:
CeliusTemp = (FahrenhietTemp-32.0) *(100.0/180.0)
Python If Statement
Syntax
if test expression:
statement(s)
else:
statement(s)
● Any expression that is not equal zero or null is considered true in python.
Example
>>> if 0:
print "0"
>>> if 2:
print "2"
● No {} for blocks; white spaces are used for defining the blocks for better
readability. you can write the inner block all on one line if you like separated by
semi colon, The following three versions of an "if" statement are all valid and do
exactly the same thing. However, the first version is the most readable.
>>> if 1 + 1 == 2:
... print "foo"
... print "bar"
... x = 42
>>> if 1 + 1 == 2:
... print "foo"; print "bar"; x = 42
Python nested If
Syntax
if test expression:
statement(s)
elif test expression::
statement(s)
else:
statement(s)
Example
if temperature< 20:
print ("cold")
elif temperature>20 and temperature<30:
print ("good")
else:
print ("hot")
Loops
While loop
Syntax
while expression:
statement(s)
Example
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
For loop
Syntax
for iterating_var in sequence:
statement(s)
Example
Students Task 1
Write a python program that takes 10 students marks as an input then display the
student grade (i.e. Fail, accepted, good, V.good, Excellent)
Solution
for count in range(10):
mark = input ('Enter student mark:')
mark = int(mark)
if mark< 50:
print ("Failed")
elif mark>50 and mark<65:
print ("D")
elif mark>=65 and mark<75:
print ("C")
elif mark>=75 and mark<85:
print ("B")
elif mark>=85:
print ("A")
else:
print ("Wrong mark")
count = count + 1
Functions
Syntax
Keyword Arguments
Keyword arguments are related to the function calls. When you use keyword arguments
in a function call, the caller identifies the arguments by the parameter name. This allows
you to skip arguments or place them out of order because the Python interpreter is able
to use the keywords provided to match the values with parameters. You can also make
keyword calls to the printme() function in the following ways
Example
Default arguments
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return;
variable-length arguments are used to process a function for more arguments than you
specified while defining the function. These arguments are not named in the function
definition, unlike required and default arguments.
Syntax
"function_docstring"
function_suite
return [expression]
Example
Example
Students Task 2
Write a python function that takes an integer an argument then calculates its
factorial returns it
Solution
def calculateFactorial (num):
factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
Students Task 3
Write a python function that finds the prime numbers from 2 to 100
Solution
def findPrime ():
i=2
while(i < 100):
j=2
while(j <= (i/j)):
if not(i%j): break j
=j+1
if (j > i/j) : print (i, " is prime")
i=i
References http://web.mit.edu/6.s189/www/materials.html
http://www.tutorialspoint.com/python/python_basic_syntax.htm