Introduction To Computer Science
Introduction To Computer Science
Python Programming
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
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
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
or
Boolean Type
not >>>> a = not (5 > 3) >>>> print a >>>> False
Conditionals
Defined over Boolean variables If < condition > :
<Code>
else:
<Code>
Conditionals
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
while <condition> :
code
Program
Additional Challenge: Use the string data type so that output is on one line
545