0% found this document useful (0 votes)
8 views13 pages

AI_Python_Lab1

The document outlines the objectives and content of a Python programming lab course at Cairo University, focusing on basic operations, comparison operators, decision making, loops, and functions. It includes instructions for setting up the Python environment, using IDLE, and provides examples of variables, strings, input handling, and control structures. Additionally, it features student tasks to practice programming skills, such as calculating temperature conversions and determining student grades.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
8 views13 pages

AI_Python_Lab1

The document outlines the objectives and content of a Python programming lab course at Cairo University, focusing on basic operations, comparison operators, decision making, loops, and functions. It includes instructions for setting up the Python environment, using IDLE, and provides examples of variables, strings, input handling, and control structures. Additionally, it features student tasks to practice programming skills, such as calculating temperature conversions and determining student grades.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 13

Cairo University

Faculty of Computers & Information

Artificial Intelligence course


Lab#1

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

Variables: Numbers and Strings

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)

● float (floating point real values)

● complex (complex numbers)

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 −

str = 'Hello World!'

print (str) # Prints complete string


print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string
● print (str[:-1]) # Prints string starting from first character till before the last
character

This will produce the following result −

Hello World!

llo

llo World!

Hello World!Hello World!

Hello World!TEST

Hello World

Multiple Assignment

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


For example −

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”

Reading Input from Console


To read input from console in python, use raw_input function which takes the
prompt message as a parameter and returns input string then you can cast it to the
needed type Example:
n=input('enter number')
n= int(n)
print(n+3)

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)

Comparison operators and Decision making


● Equality ==
● Not equal !=, <>
● Greater than, greater than or equal >, >=
● Less than, less than or equal <, <=
● Logical operations: and, or, not
age >= 18 and age <= 35
age >= 18 or age <= 35
not age > 80

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

>>> 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

for count in range(9):


print ('The count is:', count)
count = count + 1

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

def functionname( parameters ):


"function_docstring"
function_suite
return [expression]
Example
def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme("I'm first call to user defined function!")

● All parameters (arguments) in the Python language are passed by reference. It


means if you change what a parameter refers to within a function, the change also
reflects back in the calling function. Which is the case in the first function.
However in the second function The parameter mylist is local to the function
changeme. Changing mylist within the function does not affect mylist. The
function accomplishes nothing and finally this would produce the following result

def changeme1( mylist ):


"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print ("Values inside the function: ", mylist)
return

# Now you can call changeme function


mylist = [10,20,30];
changeme1( mylist );
print ("Values outside the function: ", mylist)

def changeme2( mylist ):


"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist
print ("Values inside the function: ", mylist)
return

# Now you can call changeme function


mylist = [10,20,30];
changeme2( mylist );
print ("Values outside the function: ", mylist)

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

printme( str = "My string")

Example

def printinfo( name, age ):


"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )

Default arguments
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )
printinfo( name="miki" )

Variable length Arguments

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

def functionname([formal_args,] *var_args_tuple ):

"function_docstring"

function_suite

return [expression]

Example

def printinfo( arg1, *vartuple ):


"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;

# Now you can call printinfo function


printinfo( 10 )
printinfo( 70, 60, 50 )

Global vs. Local variables


Variables that are defined inside a function body have a local scope, and those defined
outside have a global scope.This means that local variables can be accessed only inside
the function in which they are declared, whereas global variables can be accessed
throughout the program body by all functions.

Example

total = 0; # This is global variable.


# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print ("Inside the function local total : ", total)
return total;

# Now you can call sum function


sum( 10, 20 );
print ("Outside the function global total : ", total)

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

You might also like