Introduction to Computer Science CSL 102
Python Programming
Syntax, Semantics, Debugging
Syntax
The rules to write the program a=5+3 print a print(a)
Semantics
What does the program actually accomplish? The program prints the result of adding 5 and 3
Debugging
Correcting the syntax and semantics
Python
A high level language (vs low level)
C, C++, Java
Interpreted (vs compiled)
Interpret
Program Output
Interpreted Language
Compiled Language
Program
Compile
Machine Code
Execute
Output
Modes of Operation
Interactive Mode
[ Terminal@] python >>>>print 5 5
Script mode
Create myfile.py
a=5 print a
[ Terminal@] python myfile.py
5
Variables and Constants
Variables
Can hold any value Example: a, b, x2, y4, myvar
Constant
Has a fixed value 5, 6, Hello, 5.4
Data Types
int
Integer valued numbers Floating point numbers (decimal numbers) Characters, Strings {True, False}
float str
bool
>>>> a=3 >>>> type(a) >>>> <type, int> Loosely typed language
Operators
>>>> 2+3 >>>> 5 >>>> 5 * 7 >>>> 35 >>>> 8/5 >>>> 1 >>>> 8%5 >>>>> 3
Precedence
>>>> 5*8+4/2=42 Precedence order:
/, *, +,
Use of Brackets
>>>> (5*8)+(4/2)
Assignment
>>>> n = 2+3 >>>> print n >>>> 5 >>>> a = 2 >>>> b =3 >>>> c = a + b >>>> print c >>>> 5 >>>> print Hello World >>>> Hello World
Program
Write a program to print the number of hours, minutes and seconds in the year 2012.
Input Function
>>>> n = input(Please input a number:) >>>> Please input a number: 5 >>>> print n is, n >>>> n is 5
Comments
The commented lines are ignored. Very important for readability Example Code:
>>>#Program to find square of a number >>>> n = input(Enter a number:) >>>> Enter a number:2 >>>> print n*n >>>> 4
Boolean Type
>>>> a = (5 > 3) >>>> print a >>>> True Boolean Operators and
>>>> a = (5 > 3) and (5 > 6) >>>> print a >>>>False
>>>> a = (5 > 3) or (5 > 6) >>>> print a >>>>True
or
Boolean Type
not >>>> a = not (5 > 3) >>>> print a >>>> False
Conditionals
Defined over Boolean variables If < condition > :
<Code>
else:
<Code>
Indentation is the key
Conditionals
Example Program (script mode)
a = input(Input a number:) if (a == 3) :
print a is equal to 3
else:
print a is not equal to 3
Program
Write a program which takes as input an year and prints the number of hours, minutes and seconds in it (Remember to correctly handle the case for a leap year).
While Loop
while <condition> :
code
Executes the loop as long as condition is satisfied n=1 while n <= 5:
print n n=n+1
Prints the first five positive integers
Infinite While Loop
while <condition> :
code
What if condition is never satisfied? n=1 while n <= 5:
print n n=n1
Will never terminate!
Program
Write a program which
Example: n = 545 Output:
5 4 5
Inputs a number n Extracts out the digits of the number n
Additional Challenge: Use the string data type so that output is on one line
545