Python Lecture 2-Python-Basics
Python Lecture 2-Python-Basics
• Syntax
Rules of the programming language
a=5+4
print a
print (a) (syntactically correct)
• Semantics
Meaning or the logic of the program
Above the program adds two values and prints, if it were
to multiply then semantics is wrong.
• Debugging
Correcting the syntax and semantics
Python
• Variables
– Can hold any value
– a, x2, myname, ..
• Constant
– Hold a fixed value
– 5, 1.5, ‘hello’
Data (Object) Types
• int
– Integer valued numbers
• float
– Floating point numbers
• str
– Characters, string
• bool
– {true, false}
Data (Object) Types
• >>>> a=3
• >>>> type(a)
• >>>> <type, ‘int’>
• Indicates that the type is ‘int’
• >>>> float(a)
– will convert a into floating point
Operators
• >>>> 2+3
• >>>> 5
• >>>> 5 * 7
• >>>> 35
• >>>> 8/5
• >>>> 1.6
• >>>> 8%5
• >>>> 3
• >>>>2**3
• >>>>8
Operators
Operators
• Precedence order
• **
• *
• /
• + and -
• Use of brackets
• >>>>(5*6)+(4/2)
Assignment
• >>>> n = 2+3
• >>>> print (n)
• >>>> 5
• >>>> a = 2
• >>>> b =3
• >>>> c = a + b
• >>>> print (c)
• >>>> 5
Comparison Operators
• >, <, <=, >=, ==, !=
• Return ‘True’ or ‘False’
• >>>> a=4
• >>>> a == 4
• >>>> True
Conditionals
• Defined over Boolean variables
• if <condition> :
• <code>
• else :
• <code>
Indentation is important
Input
• >>>> n = input(‘Please input a number:’)
• Please input a number:5
• >>>> print (n)
• >>>> ‘5’
• >>>>n = int (input(‘Please input a number:’))
• Please input a number:5
• >>>>print (n)
• >>>> 5
Sample program
a=int(input('Please input a number:'))
print(a)
if (a==5):
print('a is equal to 5')
else:
print('a is not equal to 5')