CS105
LAB 6- Python 2


Objectives
  1. Practice writing programs to solve problems
  2. Review types, operators, and the math library
  3. See how if-else statements allow program to make decisions


Practice I : Calculate n factorial, n!

 

Write a python program that reads the value of an integer n from the user and computes and prints the factorial of that number


Types and Operators

Built in Numeric Types :

  1. int
  2. long
  3. float

Built in Operations and Functions

  1. +
  2. -
  3. *
  4. /
  5. **
  6. %
  7. abs()
  8. min()
  9. max()

Remember:

Different behaviour of operations according to the numeric type they handle. Example : 5/3 NOT EQUAL TO 5.0/3.0

  1. Does any operator work with "str"?


Math Library

Libraries are collections of functions. The math library provides with many useful functions and constants. Some of them are:

  1. sin(x)
  2. cos(x)
  3. sqrt(x)
  4. log(x)
  5. exp(x)
  6. ceil(x)
  7. floor(x)
  8. pi
  9. e

In order to use them we have to first import the math library:

>>> import math

Inside a module, the import statement goes at the top! Then you can use the functions from the library

>>> math.sin(1.2) %------------- be careful... it works with radians, 180 degrees is equivalent to pi radians

>>> math.e %------------------- e is the Euler's constant ~ 2.718


Practice II: Euclidean distance

A(x1,y1) and B(x2,y2) are points on the Euclidean plane.

Write a simple program that takes as input x1,y1,x2 and y2 from the user

and

outputs the Euclidean distance, d, between the two points. Use the square root function in the Math library.


Working with If

if <condition>:

<statements>

else <condition>:

<statements>

Example:

grade = input("Enter student's grade: ") 
if grade>90: 
    print "A" 
else:
    if grade > 80:
         print "B" 
    else:
         print "C"  

Note:

else:

if:

is equivalent to

elif:

 


Relational Operators
  1. <
  2. <=
  3. ==
  4. >=
  5. >
  6. !=

Remember the difference between "==" and "="


Practice III : Maximum of n inputs

 

Write a python program that begins by reading the value of an integer n from the user. Next, the program should read n integer values from the user, and it should conclude by printing the largest of these values . Hint: Use a variable to keep track of the largest value you have seen thus far, and update it as needed after each new value input by the user.


Practice IV : Leap years

 

A leap year (aka bissextile) is a year that has 366 days (++29th February). Write a python program that takes a year as an argument and outputs if it is a leap year or not. Use the following facts:

  1. All leap years are divisible by 4
  2. If a year is divisible by 100, it is **not** a leap year unless it is also divisible by 400.

Tip: Draw an image (or a flow chart) before you start writing your program.

 

CS105