1 of 39

Introduction to Python Programming Part-I

Dr. Harpreet Singh,

Head PG Department of Bioinformatics

Hans Raj Mahila Maha Vidyalaya Jalandhar

2 of 39

3 of 39

Programming basics

  • code or source code: The sequence of instructions in a program.
  • syntax: The set of legal structures and commands that can be used in a particular programming language.
  • output: The messages printed to the user by a program.
  • console: The text box onto which output is printed.
    • Some source code editors pop up the console as an external window,

and others contain their own console window.

3

4 of 39

Compiling and interpreting

  • Many languages require you to compile (translate) your program into a form that the machine understands.

compile execute

  • Python is instead directly interpreted into machine instructions.

interpret

output

source code

Hello.java

byte code

Hello.class

output

source code

Hello.py

4

5 of 39

The Python Interpreter

  • Python is an interpreted

language

  • The interpreter provides an interactive environment to play with the language
  • Results of expressions are printed on the screen

>>> 3 + 7

10

>>> 3 < 15

True

>>> 'print me'

'print me'

>>> print 'print me' print me

>>>

6 of 39

Expressions

6

  • expression: A data value or set of operations to compute a value.

Examples:

1 + 4 * 3

42

  • Arithmetic operators we will use:

+ - * /

%

**

addition, subtraction/negation, multiplication, division modulus, a.k.a. remainder

exponentiation

  • precedence: Order in which operations are computed.
    • * / % ** have a higher precedence than + -

1 + 3 * 4 is 13

    • Parentheses can be used to force a certain order of evaluation.

(1 + 3) * 4 is 16

7 of 39

Integer division

7

  • When we divide integers with / , the quotient is also an integer.

3

52

4 ) 14

27

) 1425

12

135

2

75

54

21

  • More examples:
    • 35 / 5 is 7
    • 84 / 10 is 8
    • 156 / 100 is 1

  • The % operator computes the remainder from a division of integers.

3 4 ) 14

12

2

43 5 ) 218

20

18

15

3

8 of 39

Real numbers

8

  • Python can also manipulate real numbers.
    • Examples: 6.022 -15.9997 42.0 2.143e17

  • The operators + - * / % ** ( ) all work for real numbers.
    • The / produces an exact answer: 15.0 / 2.0 is 7.5
    • The same rules of precedence also apply to real numbers: Evaluate ( ) before * / % before + -

  • When integers and reals are mixed, the result is a real number.
    • Example: 1 / 2.0 is 0.5
    • The conversion occurs on a per-operator basis.

7 / 3 *

1.2

+

3 / 2

2 *

1.2

+

3 / 2

2.4

+

3 / 2

2.4

+

1

3.4

9 of 39

Math commands

8

  • Python has useful commands (or called functions) for performing calculations.
  • To use many of these commands, you must write the following at the top of your Python program:

from math import *

Command name

Description

abs(value)

absolute value

ceil(value)

rounds up

cos(value)

cosine, in radians

floor(value)

rounds down

log(value)

logarithm, base e

log10(value)

logarithm, base 10

max(value1, value2)

larger of two values

min(value1, value2)

smaller of two values

round(value)

nearest whole number

sin(value)

sine, in radians

sqrt(value)

square root

Constant

Description

e

2.7182818...

pi

3.1415926...

10 of 39

Numbers: Floating Point

  • int(x) converts x to an integer
  • float(x) converts x to a floating point
  • The interpreter shows

a lot of digits

>>> 1.23232

1.2323200000000001

>>> print 1.23232

1.23232

>>> 1.3E7

13000000.0

>>> int(2.0) 2

>>> float(2)

2.0

11 of 39

Variables

x 5 gpa 3.14

  • A variable that has been given a value can be used in expressions.

x + 4 is 9

  • Exercise: Evaluate the quadratic equation for a given a, b, and c.

10

  • variable: A named piece of memory that can store a value.
    • Usage:
      • Compute an expression's result,
      • store that result into a variable,
      • and use that variable later in the program.

  • assignment statement: Stores a value into a variable.
    • Syntax:

name = value

  • Examples:

x = 5

gpa = 3.14

12 of 39

Example

>>> x = 7

>>> x 7

>>> x+7

14

>>> x = 'hello'

>>> x

'hello'

>>>

13 of 39

print

  • print : Produces text output on the console.
  • Syntax:

print "Message" print Expression

    • Prints the given text message or expression value on the console, and

moves the cursor down to the next line.

print Item1, Item2, ..., ItemN

    • Prints several messages and/or expressions on the same line.

  • Examples:

print "Hello, world!" age = 45

print "You have", 65 - age, "years until retirement"

Output:

Hello, world!

You have 20 years until retirement

12

14 of 39

Example: print Statement

>>> print 'hello' hello

>>> print 'hello', 'there'

hello there

  • Elements separated by commas print with a space between them
  • A comma at the end of the statement (print ‘hello’,) will not print a newline character

15 of 39

input

  • input : Reads a number from user input.
    • You can assign (store) the result of input into a variable.
    • Example:

age = input("How old are you? ")

print "Your age is", age

print "You have", 65 - age, "years until retirement"

Output:

How old are you? 53

Your age is 53

You have 12 years until retirement

14

  • Exercise: Write a Python program that prompts the user for his/her amount of money, then reports how many Nintendo Wiis the person can afford, and how much more money he/she will need to afford an additional Wii.

16 of 39

Input: Example

print "What's your name?" name = raw_input("> ")

print "What year were you born?" birthyear = int(raw_input("> "))

print "Hi “, name, “!”, “You are “, 2016 – birthyear

% python input.py What's your name?

> Michael

What year were you born?

>1980

Hi Michael! You are 31

17 of 39

Repetition (loops) and Selection (if/else)

18 of 39

The for loop

18

  • for loop: Repeats a set of statements over a group of values.
    • Syntax:

for variableName in groupOfValues:

statements

      • We indent the statements to be repeated with tabs or spaces.
      • variableName gives a name to each value, so you can refer to it in the statements.
      • groupOfValues can be a range of integers, specified with the range function.

    • Example:

for x in range(1, 6):

print x, "squared is", x * x

Output:

1 squared

is

1

2 squared

is

4

3 squared

is

9

4 squared

is

16

5 squared

is

25

19 of 39

range

19

  • The range function specifies a range of integers:
  • range(start, stop)

- the integers between start (inclusive) and stop (exclusive)

  • It can also accept a third value specifying the change between values.
    • range(start, stop, step) - the integers between start (inclusive)

and stop (exclusive) by step

  • Example:

for x in range(5, 0, -1): print x

print "Blastoff!"

Output:

5

4

3

2

1

Blastoff!

  • Exercise: How would we print the "99 Bottles of Beer" song?

20 of 39

Cumulative loops

20

  • Some loops incrementally compute a value that is initialized outside the loop. This is sometimes called a cumulative sum.

sum = 0

for i in range(1, 11):

sum = sum + (i * i)

print "sum of first 10 squares is", sum

Output:

sum of first 10 squares is 385

  • Exercise: Write a Python program that computes the factorial of an integer.

21 of 39

if

21

  • if statement: Executes a group of statements only if a certain condition is true. Otherwise, the statements are skipped.
    • Syntax:

if condition:

statements

  • Example:

gpa = 3.4

if gpa > 2.0:

print "Your application is accepted."

22 of 39

if/else

2

  • if/else statement: Executes one block of statements if a certain condition is True, and a second block of statements if it is False.
    • Syntax:

if condition:

statements

else:

statements

  • Example:

gpa = 1.4

if gpa > 2.0:

print "Welcome to Mars University!"

else:

print "Your application is denied."

  • Multiple conditions can be chained with elif ("else if"):

if condition:

statements elif condition: statements

else:

statements

1

23 of 39

Example of If Statements

import math

x = 30

if x <= 15 : y = x + 15

elif x <= 30 :

y = x + 30

else :

y = x print ‘y = ‘,

print math.sin(y)

In file ifstatement.py

>>> import ifstatement y = 0.999911860107

>>>

In interpreter

24 of 39

while

23

  • while loop: Executes a group of statements as long as a condition is True.
    • good for indefinite loops (repeat an unknown number of times)
  • Syntax:

while condition:

statements

  • Example:

number = 1

while number < 200: print number, number = number * 2

    • Output:

1 2 4 8 16 32 64 128

25 of 39

While Loops

x = 1

while x < 10 : print x

x = x + 1

>>> import whileloop 1

2

3

4

5

6

7

8

9

>>>

  • In whileloop.py
  • In interpreter

26 of 39

Logic

  • Exercise: Write code to display and count the factors of a number.

25

  • Many logical expressions use relational operators:
  • Logical expressions can be combined with logical operators:

Operator

Example

Result

and

9 != 6 and 2 < 3

True

or

2 == 3 or -1 < 5

True

not

not 7 > 0

False

Operator

Meaning

Example

Result

==

equals

1 + 1 == 2

True

!=

does not equal

3.2 != 2.5

True

<

less than

10 < 5

False

>

greater than

10 > 5

True

<=

less than or equal to

126 <= 100

False

>=

greater than or equal to

5.0 >= 5.0

True

27 of 39

Loop Control Statements

break

Jumps out of the closest enclosing loop

continue

Jumps to the top of the closest enclosing loop

pass

Does nothing, empty statement placeholder

28 of 39

More Examples For Loops

  • Similar to perl for loops, iterating through a list of values

for x in [1,7,13,2]: print x

forloop2.py

for x in range(5) : print x

forloop1.py

%python forloop1.py

% python forloop2.py

0

1

2

3

4

1

7

13

2

range(N) generates a list of numbers [0,1, …, n-1]

29 of 39

More Data Types: Objects

30 of 39

Everything is an object

  • Everything means everything, including functions and classes (more on this later!)
  • Data type is a property of the object and not of the variable

>>> x = 7

>>> x 7

>>> x = 'hello'

>>> x

'hello'

>>>

31 of 39

Numbers: Integers

  • Integer – the equivalent of a C long
  • Long Integer – an unbounded integer value.

>>> 132224

132224

>>> 132323 **

2

17509376329L

>>>

32 of 39

Numbers: Floating Point

  • int(x) converts x to an integer
  • float(x) converts x to a floating point
  • The interpreter shows

a lot of digits

>>> 1.23232

1.2323200000000001

>>> print 1.23232

1.23232

>>> 1.3E7

13000000.0

>>> int(2.0) 2

>>> float(2)

2.0

33 of 39

Numbers: Complex

  • Built into Python
  • Same operations are supported as integer and float

>>> x = 3 + 2j

>>> y = -1j

>>> x + y

(3+1j)

>>> x * y (2-3j)

34 of 39

String Literals

+ is overloaded to do concatenation

>>> x = 'hello'

>>> x = x + ' there'

>>> x

'hello there'

35 of 39

String Literals

  • Can use single or double quotes, and three double quotes for a multi-line string

>>> 'I am a string' 'I am a string'

>>> "So am I!"

'So am I!'

36 of 39

Substrings and Methods

>>> s = '012345'

>>> s[3]

'3'

>>> s[1:4] '123'

>>> s[2:]

'2345'

>>> s[:4] '0123'

>>> s[-2]

'4'

  • len(String) – returns the number of characters in the String
  • str(Object) – returns a String representation of the Object

>>> len(x) 6

>>>

str(10.3)

'10.3'

37 of 39

String Formatting

  • Similar to C’s printf
  • <formatted string> % <elements to insert>
  • Can usually just use %s for everything, it will convert the object to its String representation.

>>> "One, %d, three" % 2 'One, 2, three'

>>> "%d, two, %s" % (1,3)

'1, two, 3'

>>> "%s two %s" % (1, 'three') '1 two three'

>>>

38 of 39

References

39 of 39

Thanks