Stanford Python Camp D – 4

Share:

D-4: Using loop commands with Python operators

Assignment 4 – A. Simple Squares

Write a program to print squares and square roots of all numbers from 1 to 81 using the “while loop.” On each line print a number, its square, and its square root. Sample output:

x=1, square=1, sqrt=1
x = 2, square = 3, sqrt = 1.4142135623730951

Assignment 4 – A code
Assignment 4 – A outcome

Assignment 4 – B. Multiplication

Write a program that executes the multiplication of two numbers entered by the user using only the addition operation. For example, if the user enters 3 and 4, the program computes the multiplication of these numbers by adding the number 4 three times (i.e., 3 * 4 = 4 + 4 + 4).

Assignment 4 – B code
Assignment 4 – B outcome

Assignment 4 – C. Stars

Write a program that prints a diagram of the function 2n, as follows.

*
**
****
********
****************
********************************
****************************************************************
********************************
****************
********
****
**
*

Write the program using two sets of loops – one for the top part of the output and another for the bottom part of the loop. You can use two ‘*’ characters – once in each loop.

Assignment 4 – C code
Assignment 4 – C outcome

Assignment 4 – D. Fibonacci Number

Write a program to compute the Nth Fibonacci number. Fibonacci numbers are defined as follows:

fo = 0
f1 = 1
fk = fk-1 + fk-2

where fi is the ith Fibonacci number.

Hint:
If N is 0, your program should output 0
If N is 1, your program should output 1.
If N is greater than 1, then write a loop to calculate the Nth Fibonacci number as follows:

Create two variables and initialize fibA = 0 and fibB = 1.
Write a loop that iterates from 1 to N using the for loop and range function. Inside the loop:

  • Calculate fib = fibA + fibB
  • Update fibB = fibA
  • Update fibB = fib
Assignment 4 – D code
Assignment 4 – D outcome

Stay In Touch.

  • kimhannah2005@gmail.com