• No results found

Lab 01: Python Programming 1

N/A
N/A
Protected

Academic year: 2020

Share "Lab 01: Python Programming 1"

Copied!
13
0
0

Loading.... (view fulltext now)

Full text

(1)

Semester 06 (Spring 2019)

Lab 01: Python Programming 1

Introduction to :

1. Java Versus Python (Side by Side Comparison)

2. Control Structures(if, if else, switch, for, while and do while) 3. Arrays(one, two and three dimensional)

1. Java Versus Python

1. Hello World

Java Python

public class HelloWorld{

public static void main(String[] args){ System.out.println("Hello world!");} }

print("Hello world!")

2. Statements

Java Python

Statements in Java always end with a semicolon (;). It is possible for a statement to run over more than one line, or to have multiple statements on a single line. Examples: this is a statement;

this is another statement; this is a long statement that extends over more than one line;

Python is line-oriented: statements end at the end of a line unless the line break is explicitly escaped with \. There is no way to put more than one statement on a single line. Examples:

this is a statement this is another statement this is a long statement that\ extends over more than one line

3. Use of Variables

Java Python

Java is statically typed: int someVariable; int someVariable = 42;

• A variable that has been declared to be of a particular type may not be assigned a value of a different type.

Python is dynamically typed: someVariable = 42

• A variable that has been assigned a value of a given type may later be assigned a value of a different type.

(2)

Java has two kinds of data types: primitive types and reference types.

• byte - 8-bit integers • short - 16-bit integers • int - 32-bit integers • long - 64-bit integers • float - 32-bit real numbers. • double - 32-bit real numbers. • boolean - (false and true). • char - a single character.

someVariable = 'Hello, world'

Python supports the following built-in data types:

• Plain integers (32-bit integers).

• Long integers (memory size of the machine) • Booleans (False and True).

• Real numbers. • Complex numbers.

4. Input From Console

Java Python

import java.util.Scanner; public class HelloWorld{

static public void main(String[] args){ Scanner input = new Scanner(System.in); System.out.println("Enter your Name"); String name = input.nextLine();

System.out.println("Enter your age"); int age = input.nextInt();

} }

name = input("Enter your Name") age = int(input("Enter your age")

price = float(input("Enter item price")

4. Comments

Java Python

Single Line

// This is an end of // line comment

// (on three lines).

Multiline /*

This is a multi-line comment.

*/

Single Line

# This is an end of # line comment # (on three lines).

Multiline """

This is a docstring or multi-line comment. """

5.Arithmatic Operators

Java Python

Operato r

Meaning Example

+ Add x + y

+2 - Subtract x - y

-2 * Multiply x * y

Operato r

Meaning Example

+ Add x + y

+2

- Subtract x - y

-2

(3)

/ Divide x / y

% Modulus x % y

(remainder of x/y)

/ Divide x / y

% Modulus x % y

(remainder of x/y)

// Floor division x // y

** Exponent x**y (x to the power y)

6. Comparison Operators

Java Python

Operato r

Meaning Exampl e > Greater that x > y < Less that x < y

== Equal to x == y

!= Not equal to x != y >= Greater than or

equal

x >= y <= Less than or equal

to x <= y

Operato r

Meaning Exampl e > Greater that x > y

< Less that x < y

== Equal to x == y

!= Not equal to x != y

>= Greater than or equal x >= y <= Less than or equal to x <= y

7. Logical Operators

Java Python

Operato r

Meaning Exampl e && True if both the

operands are true

x && y || True if either of the

operands is true

x || y ! True if operand is

false (complements the operand) ! x Operato r Meaning Exampl e and True if both the

operands are true

x and y or True if either of the

operands is true

x or y not True if operand is

false (complements the operand)

not x

8. Assignment Operators

Java Python

Operato r

Example Equivatent to

= x = 5 x = 5

+= x += 5 x = x + 5 -= x -= 5 x = x - 5 *= x *= 5 x = x * 5 /= x /= 5 x = x / 5 %= x %= 5 x = x % 5

Operato r

Example Equivatent to

= x = 5 x = 5

+= x += 5 x = x + 5

-= x -= 5 x = x - 5

*= x *= 5 x = x * 5

/= x /= 5 x = x / 5

(4)

- -

-- -

-&= x &= 5 x = x & 5 |= x |= 5 x = x | 5 ^= x ^= 5 x = x ^ 5 >>= x >>= 5 x = x >> 5 <<= x <<= 5 x = x << 5

//= x //= 5 x = x // 5

**= x **= 5 x = x ** 5

&= x &= 5 x = x & 5

|= x |= 5 x = x | 5

^= x ^= 5 x = x ^ 5

>>= x >>= 5 x = x >> 5 <<= x <<= 5 x = x << 5

9. Conditional Statements

Java Python

IF-Statement if (x < 0) {

something; }

IF-Else Statement if (x < 0) { something; } else {

somethingdifferent; }

IF-Else If Statement if (x < 0) {

something;

} elseif (x > 0) { somethingdifferent; } else {

yetanother thing; }

IF-Statement if x < 0:

something

IF-Else Statement if x < 0:

something else:

somethingdifferent

IF-elif Statement if x < 0:

something elifx > 0:

somethingdifferent else:

yetanother thing

10. Switch Statement

Java Python

switch(expression){

case 1: dosomething();break; case 2: dosomething();break; .

.

default: dosomething() }

Not availabe in python.

11. Loops

Java Python

For Loop

for(int i = 1; i < 10; i ++){ something;

For Loop

(5)

}

(i takes on values 1, 2, 3, 4, 5, 6, 7, 8, 9)

for (int i = 1; i < 10; i += 2){ System.out.print(i);

}

(i takes on values 1, 3, 5, 7, 9) While Loop

int x = 5

while (x > 0) {

System.out.print(x); x-=1;

}

Do-While int x = 5 do{

System.out.print(x); x-=1;

}while (x > 0)

something2

(i takes on values 1, 2, 3, 4, 5, 6, 7, 8, 9) for i in range(1, 10, 2):

print(i)

(i takes on values 1, 3, 5, 7, 9) While Loop

x = 5

while x > 0: print(x) x-=1

Do-While

Not availabe in python.

12. Arrays

Java Python

One Dimensional

int [] list = {32, 27, 64, 18}; System.out.println(list);

int [] list = new int[10]; for(int i=0;i<10;i++)

list[i]=i;

Two Dimensional

int [][]myArray = {{1,2},{3,4}};

int [][]myArray = new int[3][3];

One Dimensional

list = [32, 27, 64, 18] print(list)

list=[0 for i in range(10)] for i in range(10):

list[i]=i

Two Dimensional

myArray=[[1,2],[3,4]]

myArray=[[0 for j in range(3)] for i in range(3)]

13. String

Java Python

+

*

Concatenation

Repetition

s = 'Hello'

(6)

[i], [-i]

[m:n], [m:], [:n],

[m:n:step]

Obj.index(str )

Indexing from front or back, front index begins at 0, back index begins at -1 (or len-1)

Slicing from index m (inclusive) to n (exclusive) with an optional step size. Default m is 0, n is len-1.

Returns the index of string

s * 2 ⇒ 'HelloHello'

Char: H e l l o Index: 0 1 2 3 4 Index from right: -5 -4 -3 -2 -1

s[1] ⇒ 'e' s[-4] ⇒ 'e'

s[1:3] ⇒ 'el'

s[1:-2] ⇒

'el'

s[3:] ⇒ 'lo' s[:-2] ⇒

'Hel'

s[0:5:2] ⇒ 'Hlo'

s.index(“o”) ⇒ 4

String Operations:

Write a Java program that enters a 10-digit string as a typical U.S. telephone number. Extract the 3-digit area code, the 3-3-digit "exchange," and the remaining 4-3-digit number as separate strings, prints them, and then prints the complete telephone number in the usual form atting. A sample run might look like this:

Enter 10-digit telephonenumber: 1234567890 You entered 1234567890

The area code is 123 The exchange is 456 The number is 7890

The complete telephone number is (123)456-7890

phone = input("Enter telephone number") area = phone[0:3]

#print (area)

exchange = phone[3:6] #print (exchange)

number = phone[6:len(phone)] #print(number)

print("The complete phone number is :") print("(",area,")",exchange,"-",number)

(7)

Write a Python program that generates a random year between 1800 and 2050 and then reports whether it is a leap year. A leap year is an integer greater than 1584 that is either divisible by 400 or isdivisible by 4 but not 100. To generate an integer in the range 1800 to 2050, use

year = int(random.random()*250 + 1800

The random.random() method returns the a value betweenbetween 0 and 1. The transformation 1800 converts a number in the range the range l800 ≤ year< 2050.

import random

year = int(random.random()*250)+1800 print ("The year is :",year)

if((year % 400 == 0 or year%100 != 0) and year%4 == 0): print("That is a leap year..")

else:

print("That is not a leap year..")

3. Arrays

An example of simple array declared and initilized

list = [32, 27, 64, 18, 95, 14, 90, 70, 60, 37] print(list)

2D Array:

APython program to calculate the sum of each row, colum, left diagonal and right diagonalof a two-dimensional (2D) array of size MxM.for example:

R O W S

[0

] 1 2 3 4 5

[1

] 6 7 8 9 10

[2

] 11 12 13 14 15

[3

] 16 17 18 19 20

[4

] 21 22 23 24 25

[0 ]

[1 ]

[2 ]

[3 ]

[4 ] COLUMNS Sum of row 1: 15

(8)

Sum of row 4: 90 Sum of row 5: 115

Sum of Col 1: 55 Sum of Col 2: 60 Sum of Col 3: 65 Sum of Col 4: 70 Sum of Col 5: 75

Sum of Left Diagonal: 65 Sum of Right Diagonal: 65

import random ROWS = 5 COLUMNS = 5

matrix = [[0 for i in range(ROWS)] for j in range(COLUMNS)] #Randomly assigning values

for i in range(ROWS):

for j in range(COLUMNS):

matrix[i][j]= int(random.random()*25) #Print each row of matrix

for i in range(ROWS): print(matrix[i])

#Calculating the sum of each row for i in range(ROWS):

rowSum=0;

for j in range(COLUMNS): rowSum+=matrix[i][j]

print("Sum of Row ",(i+1)," : ",rowSum) #Calculating the sum of each column

for i in range(ROWS): colSum=0;

for j in range(COLUMNS): colSum+=matrix[j][i]

print("Sum of Column ",(i+1)," : ",colSum) #Calculating the sum of left diagonal

leftDiagonalSum=0; for i in range (ROWS):

leftDiagonalSum+=matrix[i][i];

print("Sum of left diagonal : ",leftDiagonalSum); #Calculating the sum of right diagonal

rightDiagonalSum=0; for i in range(ROWS):

rightDiagonalSum+=matrix[i][(ROW-1)-i]

print("Sum of left diagonal : ",rightDiagonalSum);

Exercises

(9)

Write a Python program that needs to ask the use for her or his address. The application takes as input this address, parses the address and replies to the user with house number, street number, area and city.

A sample run is given below for your convenience. User input is shown in bold:

Please enter your address: House D 13 Street 14 NHS Karachi House Number: D 13

Street Number: Street 14 Area: Naval Housing Scheme City: Karachi

Exercise 2 (Roman.py)

Write a program that converts a positive integer into the Roman number system. The Roman number system has digits I (1), V (5), X (10), L (50), C(100), D(500) and M(1000). Numbers up to 3999 are formed according to the following rules:

a) As in the decimal system, the thousands, hundreds, tens and ones are expressed separately. b) The numbers 1 to 9 are expressed as:

1 I 6 VI

2 II 7 VII

3 III 8 VIII

4 IV 9 IX

5 V

(An I preceding a V or X is subtracted from the value, and there cannot be more than three I’s in a row.) c) Tens and hundreds are done the same way, except that the letters X,L,C, andC,D,Mare used

instead of I, V, X,respectively.

Your program should take an input, such as 1978, and convert it to Roman numerals, MCMLXXVIII.

Exercise 3 (BMICalculator.py)

Write a program that calculates students percentage and categorizes it into a grade (A,B,C,D,F) on the basis of his/her marks:

Total marks (500)

Grad e

Above 450 A

450-400 B

399-350 C

349-300 D

(10)

Prompt the user to enter marks out of 500, the program should calculate the percentage and assign the grade.

[SAMPLE RUN]

Enter your total marks out of 500: 400 Percentage= 80%

Grade= B

Exercise 4 (Arithmatic.py)

Write a python program to compute quotient and remainder of a number without using division ('/') operator and modulo ('%') operator.

Exercise 5 (BloodType.py)

Blood types are important for blood transfusion. The blood types must be matched since if not matched properly, the recipient’s blood can form clots and these can lead to heart attacks, embolisms and strokes.

The following table summarize blood groups compatibility: Donor Recipien

t

O

-O +

A

-A +

B

-B +

AB

-AB +

O- x

O+ x x

A- x x

A+ x x x x

B- x x

B+ x x x x

AB- x x x x

AB+ x x x x x x x x

(11)

[Sample Run]

Enter Blood type: O+ Can Receive from: O-, O+

Can Donate to: O+, A+, B+, AB+

Do you want to continue for another value (y/n)? y Enter Blood type: A+

Can Receive from: O-, O+, A-, A+ Can Donate to: A+, AB+

Do you want to continue for another value (y/n)? n

Exercise 6 (Occurrances.py)

Write a program to take an array and find the number of occurrences each number had. The output should be something like this:

NumberOccurrences

0 0 2 2 2 3 3 3 4 4

21 21 21 21 21 29 29 29 29 29 37 37 37 37 37 42 42 42 42 42 50 50

NOTE:Sort the array elements first and then calculate the frequency of each element. Use for-loop to calcute the frequency of each element.

Exercise 7 (Histogram.py)

Given the following array, display its data graphically by plotting each numeric value as a bar of dollars ($) as shown in the diagram.

array = [10, 19, 5, 1, 7, 14, 0, 7, 5]

Element Value Histogram

0 10 $$$$$$$$$$

1 19 $$$$$$$$$$$$$$$$$$$

2 5 $$$$$

3 1 $

4 7 $$$$$$$

5 14 $$$$$$$$$$$$$$

(12)

7 7 $$$$$$$

8 5 $$$$$

Exercise 8 (Transpose.py)

Suppose you have the following matrix:

2 0 4 2 6 3 9 9 1 0 4 1 7 1 2 3 7 4 2 2 2 7 1 6 1 5 8 7 4 1

Design then implement a Java program that will produce its transpose and print it along with the original one.

HINT:

The transpose of matrix A = [aij] is the mxn matrix AT defined by AT = [aji] So, the transpose of the matrix above is:

2 9 7 2 1 0 9 1 2 5 4 1 2 2 8 2 0 3 7 7 6 4 7 1 4 3 1 4 6 1

Exercise 9 (MatricesMultiplication.py)

Suppose you have the following matrices:

(13)

Exercise 10 (Scores.py)

Write a program that calculates the total score for students in a class. Suppose the scores are stored in a three-dimensional array named scores. The first index in scores refers to a student, the second refers to an exam, and the third refers to the part of the exam. Suppose there are 7 students, 5 exams, and each exam has two parts--the multiple-choice part and the programming part. So, scores[i][j][0] represents the score on the multiple-choice part for the i’s student on the j’s exam. Your program displays the total score for each student.

References

Related documents

The dependent variable is non-smoking behavior, while the independent variables are intention not to smoke, access to cigarettes, attitudes toward smoking, knowledge of tobacco

• Building energy modelling • Very low carbon retrofit • First-principles design • Technical assurance • Microgeneration specification tools • Planning compliance

The search terms utilised included; animal assisted therapy, animal assisted intervention, dogs, assistance dogs, assistance animal, pets, pet therapy, dog therapy, autism,

No person shall enter into any contract or agreement, employment or engagement to raise funds or conduct any fund raising activities for any charitable organization required to

Department of Elementary and Secondary Education., (1991), Missouri Industrial Technology Education Guide, Missouri: University of Missouri-Columbia.. Foundations of

A separate annual educational program will be provided to focus awareness of risk exposures and current risk prevention activities. Other in-service and training programs should

Specially, we are interested in the limit of fixed point sets for a convergent sequence of multivalued mappings, that is, how they are related, in the limit, to the fixed point set of

Poisson and NB regressions were applied to determine the relation- ship between fatalities, injuries and accidents and traffic variables, number of intersections for each stretch,