16
UNIT-1 WHAT IS COMPUTER SCIENCE? Computer Science is the study of computers and computational systems. Computer scientists deal mostly with software and software systems; this includes their theory, design, development, and application. Principal areas of study within Computer Science include artificial intelligence, computer systems and networks, security, database systems, human computer interaction, vision and graphics, numerical analysis, programming languages, software engineering, bioinformatics and theory of computing. Although knowing how to program is essential to the study of computer science, it is only one element of the field. Computer scientists design and analyze algorithms to solve programs and study the performance of computer hardware and software. The problems that computer scientists encounter range from the abstract-- determining what problems can be solved with computers and the complexity of the algorithms that solve them to the tangible designing applications that perform well on handheld devices, that are easy to use, and that uphold security measures. COMPUTER ALGORITHMS An algorithm is a well-defined procedure that allows a computer to solve a problem. Another way to describe an algorithm is a sequence of unambiguous instructions Every time you ask your computer to carry out the same algorithm, it will do it in exactly the same manner with the exact same result. A very simple example of an algorithm would be to find the largest number in an unsorted list of numbers. If you were given a list of five different numbers, you would have this figured out in no time, no computer needed. Now, how about five million different numbers? Clearly, you are going to need a computer to do this, and a computer needs an algorithm. Below is what the algorithm could look like. Let's say the input consists of a list of numbers, and this list is called L. The number L1 would be the first number in the list, L2 the second number, etc. And we know the list is not sorted - otherwise, the answer would be really easy. So, the input to the algorithm is a list of numbers, and the output should be the largest number in the list. The algorithm would look something like this: Step 1: Let Largest = L1 This means you start by assuming that the first number is the largest number. Step 2: For each item in the list: This means you will go through the list of numbers one by one. Step 3: If the item > Largest:

UNIT-1 · UNIT-1 WHAT IS COMPUTER SCIENCE? Computer Science is the study of computers and computational systems. Computer scientists deal mostly with software and software systems;

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: UNIT-1 · UNIT-1 WHAT IS COMPUTER SCIENCE? Computer Science is the study of computers and computational systems. Computer scientists deal mostly with software and software systems;

UNIT-1

WHAT IS COMPUTER SCIENCE?

Computer Science is the study of computers and computational systems. Computer scientists deal mostly with software and software systems; this includes their theory, design, development, and application. Principal areas of study within Computer Science include artificial intelligence, computer

systems and networks, security, database systems, human computer interaction, vision and

graphics, numerical analysis, programming languages, software engineering, bioinformatics

and theory of computing.

Although knowing how to program is essential to the study of computer science, it is only

one element of the field. Computer scientists design and analyze algorithms to solve

programs and study the performance of computer hardware and software. The problems

that computer scientists encounter range from the abstract-- determining what problems can

be solved with computers and the complexity of the algorithms that solve them – to the

tangible – designing applications that perform well on handheld devices, that are easy to

use, and that uphold security measures.

COMPUTER ALGORITHMS

An algorithm is a well-defined procedure that allows a computer to solve a problem. Another way to

describe an algorithm is a sequence of unambiguous instructions

Every time you ask your computer to carry out the same algorithm, it will do it in exactly the same

manner with the exact same result.

A very simple example of an algorithm would be to find the largest number in an unsorted list of numbers. If you were given a list of five different numbers, you would have this figured out in no time, no computer needed. Now, how about five million different numbers? Clearly, you are going to need a computer to do this, and a computer needs an algorithm.

Below is what the algorithm could look like. Let's say the input consists of a list of numbers, and this list is called L. The number L1 would be the first number in the list, L2 the second number, etc. And we know the list is not sorted - otherwise, the answer would be really easy. So, the input to the algorithm is a list of numbers, and the output should be the largest number in the list.

The algorithm would look something like this:

Step 1: Let Largest = L1

This means you start by assuming that the first number is the largest number.

Step 2: For each item in the list:

This means you will go through the list of numbers one by one.

Step 3: If the item > Largest:

Page 2: UNIT-1 · UNIT-1 WHAT IS COMPUTER SCIENCE? Computer Science is the study of computers and computational systems. Computer scientists deal mostly with software and software systems;

If you find a new largest number, move to step four. If not, go back to step two, which means you move on to the next number in the list.

Step 4: Then Largest = the item

This replaces the old largest number with the new largest number you just found. Once this is completed, return to step two until there are no more numbers left in the list.

Step 5: Return Largest

This produces the desired result.

Notice that the algorithm is described as a series of logical steps in a language that is easily understood. For a computer to actually use these instructions, they need to be written in a language that a computer can understand, known as a programming language.

. PYTHON PROGRAMMING LANGUAGE

Python is an interpreted, high-level, general-purpose programming language. Created by Guido

van Rossum and first released in 1991, Python is dynamically typed and garbage-collected. It

supports multiple programming paradigms, including procedural, object-oriented, and functional

programming. Python is often described as a "batteries included" language due to its

comprehensive standard library.

Python 2.0, released 2000, introduced features like list comprehensions and a garbage

collection system capable of collecting reference cycles. Python 3.0, released 2008, was a major

revision of the language that is not completely backward-compatible, and much Python 2 code does

not run unmodified on Python 3.

The language's core philosophy is summarized in the document

● Beautiful is better than ugly ● Explicit is better than implicit ● Simple is better than complex ● Complex is better than complicated ● Readability counts

Syntax and semantics

Python is meant to be an easily readable language. Its formatting is visually uncluttered, and

it often uses English keywords where other languages use punctuation. Unlike many other

languages, it does not use curly brackets to delimit blocks, and semicolons after statements are

optional. It has fewer syntactic exceptions and special cases than C.

Indentation Python uses whitespace indentation, rather than curly brackets or keywords, to

delimit blocks. An increase in indentation comes after certain statements; a decrease in indentation

signifies the end of the current block.[61] Thus, the program's visual structure accurately represents

the program's semantic structure.[1] This feature is also sometimes termed the off-side rule.

Page 3: UNIT-1 · UNIT-1 WHAT IS COMPUTER SCIENCE? Computer Science is the study of computers and computational systems. Computer scientists deal mostly with software and software systems;

Statements and control flow

● The if statement, which conditionally executes a block of code, along with else and elif (a

contraction of else-if). ● The for statement, which iterates over an iterable object, capturing each element to a local

variable for use by the attached block. ● The while statement, which executes a block of code as long as its condition is true.

● The class statement, which executes a block of code and attaches its local namespace to

a class, for use in object-oriented programming. ● The def statement, which defines a function or method.

● The print statement was changed to the print() function in Python 3.[64]

LITERALS

Types of literals supported by python are

1.String Literals

2.Numeric Literals

3.Boolean Literals

4.Special Literals

5.Literal collection

String Literals:

String literals can be formed by enclosing a text in the quotes. We can use both single as

well as double quotes for a String.

Eg: "Aman" , '12345'

Types of Strings:

There are two types of Strings supported in Python:

a).Single line String- Strings that are terminated within a single line are known as Single

line Strings.

Eg: >>> text1='hello'

b).Multi line String- A piece of text that is spread along multiple lines is known as Multiple

line String.

Page 4: UNIT-1 · UNIT-1 WHAT IS COMPUTER SCIENCE? Computer Science is the study of computers and computational systems. Computer scientists deal mostly with software and software systems;

There are two ways to create Multiline Strings:

1). Adding black slash at the end of each line.

Eg:

1. >>> text1='hello\

2. user'

3. >>> text1

4. 'hellouser'

2).Using triple quotation marks:-

Eg:

1. >>> str2='''''welcome

2. to

3. SSSIT'''

4. >>> print str2

5. welcome

6. to

7. SSSIT

II.Numeric literals:

Numeric Literals are immutable. Numeric literals can belong to following four different

numerical types.

Int(signed integers) Long(long integers) float(floating point) Complex(complex)

Numbers( can be both

positive and negative) with

no fractional part.eg: 100

Integers of unlimited

size followed by

lowercase or uppercase

L eg: 87032845L

Real numbers with

both integer and

fractional part eg: -

26.2

In the form of a+bj where a forms

the real part and b forms the

imaginary part of complex number.

eg: 3.14j

III. Boolean literals:

A Boolean literal can have any of the two values: True or False.

IV. Special literals.

Python contains one special literal i.e., None.

Page 5: UNIT-1 · UNIT-1 WHAT IS COMPUTER SCIENCE? Computer Science is the study of computers and computational systems. Computer scientists deal mostly with software and software systems;

None is used to specify to that field that is not created. It is also used for end of lists in

Python.

Eg:

1. >>> val1=10

2. >>> val2=None

3. >>> val1

4. 10

5. >>> val2

6. >>> print val2

7. None

V.Literal Collections.

Collections such as tuples, lists and Dictionary are used in Python.

List:

o List contain items of different data types. Lists are mutable i.e., modifiable.

o The values stored in List are separated by commas(,) and enclosed within a square

brackets([]). We can store different type of data in a List.

o Value stored in a List can be retrieved using the slice operator([] and [:]).

o The plus sign (+) is the list concatenation and asterisk(*) is the repetition operator.

1. Eg: >>> list=['aman',678,20.4,'saurav']

2. >>> list1=[456,'rahul']

3. >>> list

4. ['aman', 678, 20.4, 'saurav']

5. >>> list[1:3]

6. [678, 20.4]

7. >>> list+list1

8. ['aman', 678, 20.4, 'saurav', 456, 'rahul']

9. >>> list1*2

10. [456, 'rahul', 456, 'rahul']

VARIABLES AND IDENTIFIERS

Variable is a name which is used to refer memory location. Variable also known as identifier

and used to hold value.

In Python, we don't need to specify the type of variable because Python is a type infer

language and smart enough to get variable type.

Page 6: UNIT-1 · UNIT-1 WHAT IS COMPUTER SCIENCE? Computer Science is the study of computers and computational systems. Computer scientists deal mostly with software and software systems;

Variable names can be a group of both letters and digits, but they have to begin with a

letter or an underscore.

Identifier Naming Variables are the example of identifiers. An Identifier is used to identify the literals used in

the program. The rules to name an identifier are given below.

o The first character of the variable must be an alphabet or underscore ( _ ).

o All the characters except the first character may be an alphabet of lower-case(a-z),

upper-case (A-Z), underscore or digit (0-9).

o Identifier name must not contain any white-space, or special character (!, @, #, %,

^, &, *).

o Identifier name must not be similar to any keyword defined in the language.

o Identifier names are case sensitive for example my name, and MyName is not the

same.

o Examples of valid identifiers : a123, _n, n_9, etc.

o Examples of invalid identifiers: 1a, n%4, n 9, etc.

Declaring Variable and Assigning Values Python does not bound us to declare variable before using in the application. It allows us to

create variable at required time.

We don't need to declare explicitly variable in Python. When we assign any value to the

variable that variable is declared automatically.

The equal (=) operator is used to assign value to a variable.

Multiple Assignment Python allows us to assign a value to multiple variables in a single statement which is also

known as multiple assignment.

We can apply multiple assignments in two ways either by assigning a single value to

multiple variables or assigning multiple values to multiple variables. Lets see given

examples.

Assigning single value to multiple variables

Eg:

1. x=y=z=50

2. print iple

3. print y

4. print z

Output:

Page 7: UNIT-1 · UNIT-1 WHAT IS COMPUTER SCIENCE? Computer Science is the study of computers and computational systems. Computer scientists deal mostly with software and software systems;

1. 50

2. 50

3. 50

Assigning multiple values to multiple variables:

1. a,b,c=5,10,15

2. print a

3. print b

4. print c

output:

1. 5

2. 10

3. 15

The values will be assigned in the order in which variables appears.

Basic Fundamentals: This section contains the basic fundamentals of Python like :

i)Tokens and their types.

ii) Comments

a)Tokens:

o Tokens can be defined as a punctuator mark, reserved words and each individual

word in a statement.

o Token is the smallest unit inside the given program.

There are following tokens in Python:

o Keywords.

o Identifiers.

o Literals.

o Operators.

Tuples:

o Tuple is another form of collection where different type of data can be stored.

o It is similar to list where data is separated by commas. Only the difference is that list

uses square bracket and tuple uses parenthesis.

o Tuples are enclosed in parenthesis and cannot be changed.

Eg:

Page 8: UNIT-1 · UNIT-1 WHAT IS COMPUTER SCIENCE? Computer Science is the study of computers and computational systems. Computer scientists deal mostly with software and software systems;

1. >>> tuple=('rahul',100,60.4,'deepak')

2. >>> tuple1=('sanjay',10)

3. >>> tuple

4. ('rahul', 100, 60.4, 'deepak')

5. >>> tuple[2:]

6. (60.4, 'deepak')

7. >>> tuple1[0]

8. 'sanjay'

9. >>> tuple+tuple1

10. ('rahul', 100, 60.4, 'deepak', 'sanjay', 10)

11. >>>

Dictionary:

o Dictionary is a collection which works on a key-value pair.

o It works like an associated array where no two keys can be same.

o Dictionaries are enclosed by curly braces ({}) and values can be retrieved by square

bracket([]).

Eg:

1. >>> dictionary={'name':'charlie','id':100,'dept':'it'}

2. >>> dictionary

3. {'dept': 'it', 'name': 'charlie', 'id': 100}

4. >>> dictionary.keys()

5. ['dept', 'name', 'id']

6. >>> dictionary.values()

7. ['it', 'charlie', 100]

Operators

The operator can be defined as a symbol which is responsible for a particular operation

between two operands. Operators are the pillars of a program on which the logic is built in a particular programming language. Python provides a variety of operators described as

follows.

o Arithmetic operators

o Comparison operators

o Assignment Operators

o Logical Operators

o Bitwise Operators

o Membership Operators

o Identity Operators

Page 9: UNIT-1 · UNIT-1 WHAT IS COMPUTER SCIENCE? Computer Science is the study of computers and computational systems. Computer scientists deal mostly with software and software systems;

Arithmetic operators Arithmetic operators are used to perform arithmetic operations between two operands. It

includes +(addition), - (subtraction), *(multiplication), /(divide), %(reminder), //(floor

division), and exponent (**).

Consider the following table for a detailed explanation of arithmetic operators.

OPERATOR DESCRIPTION + (Addition) It is used to add two operands. For example, if a = 20, b = 10 =>

a+b = 30 - (Subtraction) It is used to subtract the second operand from the first operand. If

the first operand is less than the second operand, the value result

negative. For example, if a = 20, b = 10 => a ? b = 10 / (divide) It returns the quotient after dividing the first operand by the second

operand. For example, if a = 20, b = 10 => a/b = 2

* (Multiplication)

It is used to multiply one operand with the other. For example, if a = 20, b = 10 => a * b = 200

% (reminder) It returns the reminder after dividing the first operand by the second

operand. For example, if a = 20, b = 10 => a%b = 0

** (Exponent) It is an exponent operator represented as it calculates the first operand power to second operand.

// (Floor division)

It gives the floor value of the quotient produced by dividing the two operands.

Comparison operator Comparison operators are used to comparing the value of the two operands and returns

boolean true or false accordingly. The comparison operators are described in the following

table.

OPERATOR DESCRIPTION

== If the value of two operands is equal, then the condition becomes true.

!= If the value of two operands is not equal then the condition becomes true.

<= If the first operand is less than or equal to the second operand, then the

condition becomes true. >= If the first operand is greater than or equal to the second operand, then

the condition becomes true. < If the first operand is less than the second operand, then the condition

becomes true. > If the first operand is greater than the second operand, then the condition

becomes true. <> If the value of two operands is not equal, then the condition becomes

true.

Assignment operators The assignment operators are used to assign the value of the right expression to the left

operand. The assignment operators are described in the following table.

Page 10: UNIT-1 · UNIT-1 WHAT IS COMPUTER SCIENCE? Computer Science is the study of computers and computational systems. Computer scientists deal mostly with software and software systems;

OPERATORS DESCRIPTION = It assigns the the value of the right expression to the left operand.

+= It increases the value of the left operand by the value of the right

operand and assign the modified value back to left operand. For example, if a = 10, b = 20 => a+ = b will be equal to a = a+ b and

therefore, a = 30. -= It decreases the value of the left operand by the value of the right

operand and assign the modified value back to left operand. For

example, if a = 20, b = 10 => a- = b will be equal to a = a- b and therefore, a = 10.

*= It multiplies the value of the left operand by the value of the right

operand and assign the modified value back to left operand. For example, if a = 10, b = 20 => a* = b will be equal to a = a* b and

therefore, a = 200. //= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will

assign 4//3 = 1 to a. %= It divides the value of the left operand by the value of the right

operand and assign the reminder back to left operand. For example, if

a = 20, b = 10 => a % = b will be equal to a = a % b and therefore, a = 0.

**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will

assign 4**2 = 16 to a.

Bitwise operator The bitwise operators perform bit by bit operation on the values of the two operands.

OPERATOR DESCRIPTION

& (binary

and)

If both the bits at the same place in two operands are 1, then 1 is copied to the result. Otherwise, 0 is copied.

| (binary

or) The resulting bit will be 0 if both the bits are zero otherwise the resulting bit will be 1.

^ (binary xor)

The resulting bit will be 1 if both the bits are different otherwise the resulting bit will be 0.

~ (negation)

It calculates the negation of each bit of the operand, i.e., if the bit is 0, the resulting bit will be 1 and vice versa.

<< (left

shift) The left operand value is moved left by the number of bits present in the right operand.

>> (right

shift) The left operand is moved right by the number of bits present in the right operand.

Logical Operators The logical operators are used primarily in the expression evaluation to make a decision.

Python supports the following logical operators.

Page 11: UNIT-1 · UNIT-1 WHAT IS COMPUTER SCIENCE? Computer Science is the study of computers and computational systems. Computer scientists deal mostly with software and software systems;

Operator Description

and If both the expression are true, then the condition will be true. If a and b are the two expressions, a → true, b

→ true => a and b → true.

or If one of the expressions is true, then the condition will be true. If a and b are the two expressions, a → true,

b → false => a or b → true.

not If an expression a is true then not (a) will be false and vice versa.

Membership Operators Python membership operators are used to check the membership of value inside a data

structure. If the value is present in the data structure, then the resulting value is true

otherwise it returns false.

Operator Description

in It is evaluated to be true if the first operand is found in the second operand (list, tuple, or dictionary).

not in It is evaluated to be true if the first operand is not found in the second operand (list, tuple, or dictionary).

Identity Operators

Operator Description

is It is evaluated to be true if the reference present at both sides point to the same object.

is not It is evaluated to be true if the reference present at both side do not point to the same object.

Page 12: UNIT-1 · UNIT-1 WHAT IS COMPUTER SCIENCE? Computer Science is the study of computers and computational systems. Computer scientists deal mostly with software and software systems;

Operator Precedence The precedence of the operators is important to find out since it enables us to know which

operator should be evaluated first. The precedence table of the operators in python is given

below.

Operator Description

** The exponent operator is given priority over all the others used in the expression.

~ + - The negation, unary plus and minus.

* / % // The multiplication, divide, modules, reminder, and floor division.

+ - Binary plus and minus

>> << Left shift and right shift

& Binary and.

^ | Binary xor and or

<= < > >= Comparison operators (less then, less then equal to, greater then, greater then equal to).

<> == != Equality operators.

= %= /= //= -= +=

*= **=

Assignment operators

is is not Identity operators

in not in Membership operators

not or and Logical operators

Page 13: UNIT-1 · UNIT-1 WHAT IS COMPUTER SCIENCE? Computer Science is the study of computers and computational systems. Computer scientists deal mostly with software and software systems;

Python Expressions: Expressions are representations of value. They are different from statement in the fact that statements do something while expressions are representation of value. For example any string is also an expressions since it represents the value of the string as well.

Python has some advanced constructs through which you can represent values and hence these constructs are also called expressions.

Python expressions only contain identifiers, literals, and operators.

Following are a few types of python expressions:

List comprehension The syntax for list comprehension is shown below:

[ compute(var) for var in iterable ]

For example, the following code will get all the number within 10 and put them in a list.

>>> [x for x in range(10)]

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Dictionary comprehension This is the same as list comprehension but will use curly braces:

{ k, v for k in iterable }

For example, the following code will get all the numbers within 5 as the keys and will keep the corresponding squares of those numbers as the values.

>>> {x:x**2 for x in range(5)}

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Generator expression The syntax for generator expression is shown below:

( compute(var) for var in iterable )

For example, the following code will initialize a generator object that returns the values within 10 when the object is called.

>>> (x for x in range(10))

<generator object <genexpr> at 0x7fec47aee870>

>>> list(x for x in range(10))

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Conditional Expressions You can use the following construct for one-liner conditions:

Page 14: UNIT-1 · UNIT-1 WHAT IS COMPUTER SCIENCE? Computer Science is the study of computers and computational systems. Computer scientists deal mostly with software and software systems;

true_value if Condition else false_value

Example:

>>> x = "1" if True else "2"

>>> x

'1'

Basic Data Types in Python

Integers

In Python 3, there is effectively no limit to how long an integer value can be. Of course, it is constrained by the amount of memory your system has, as are all things, but beyond that an integer can be as long as you need it to be:

The following strings can be prepended to an integer value to indicate a base other than 10:

Prefix Interpretation Base

0b (zero + lowercase letter 'b')

0B (zero + uppercase letter 'B')

Binary 2

0o (zero + lowercase letter 'o')

0O (zero + uppercase letter 'O')

Octal 8

0x (zero + lowercase letter 'x')

0X (zero + uppercase letter 'X')

Hexadecimal 16

Floating-Point Numbers

The float type in Python designates a floating-point number. float values are specified with a decimal point. Optionally, the character e or E followed by a positive or negative integer may be appended to specify scientific notation:

Eg: >>> 4.2 4.2 >>> type(4.2) <class 'float'>

Complex Numbers

Complex numbers are specified as <real part>+<imaginary part>j. For example:

Page 15: UNIT-1 · UNIT-1 WHAT IS COMPUTER SCIENCE? Computer Science is the study of computers and computational systems. Computer scientists deal mostly with software and software systems;

>>>

>>> 2+3j (2+3j) >>> type(2+3j) <class 'complex'

Strings

Strings are sequences of character data. The string type in Python is called str.

String literals may be delimited using either single or double quotes. All the characters between the opening delimiter and matching closing delimiter are part of the string:

>>>

>>> print("I am a string.") I am a string. >>> type("I am a string.") <class 'str'> >>> print('I am too.') I am too. >>> type('I am too.') <class 'str'>

A string in Python can contain as many characters as you wish. The only limit is your machine’s memory resources.

MIXED TYPE EXPRESSIONS

A mixed-type expressions is an expression containing operand of different type. The

CPU can only perform operation on values with the same internal representation scheme, and

thus only on operands of the same type.

Operands of mixed-type expressions therefore mustbe converted to a common type.

Value can be converted in one of two ways-by implicit(automatic) conversion,called

coercion,or by explict type conversion.

Type Conversion in Python

Page 16: UNIT-1 · UNIT-1 WHAT IS COMPUTER SCIENCE? Computer Science is the study of computers and computational systems. Computer scientists deal mostly with software and software systems;

Python defines type conversion functions to directly convert one data type to another which is useful in day to day and competitive programming. This article is aimed at providing the information about certain conversion functions.

1. int(a,base) : This function converts any data type to integer. ‘Base’ specifies the base in which string is if data type is string. 2. float() : This function is used to convert any data type to a floating point number 3. ord() : This function is used to convert a character to integer. 4. hex() : This function is to convert integer to hexadecimal string. 5. oct() : This function is to convert integer to octal string. 6. tuple() : This function is used to convert to a tuple. 7. set() : This function returns the type after converting to set. 8. list() : This function is used to convert any data type to a list type. 9. dict() : This function is used to convert a tuple of order (key,value) into a dictionary. 10. str() : Used to convert integer into a string. 11. complex(real,imag) : : This function converts real numbers to complex(real,imag) number.