Skip to document
This is a Premium Document. Some documents on Studocu are Premium. Upgrade to Premium to unlock it.

MC4103 Python Programming UNIT-I

UNIT I BASICS OF PYTHON 9 Introduction to Python Programming – P...
Course

python programming (cs8151)

86 Documents
Students shared 86 documents in this course
University

Anna University

Academic year: 2021/2022
Uploaded by:
Anonymous Student
This document has been uploaded by a student, just like you, who decided to remain anonymous.
Technische Universiteit Delft

Comments

Please sign in or register to post comments.

Related Studylists

MCA notes

Preview text

MC4103 PYTHON PROGRAMMING

UNIT I BASICS OF PYTHON 9

Introduction to Python Programming – Python Interpreter and Interactive Mode– Variables and Identifiers – Arithmetic Operators – Values and Types – Statements. Operators – Boolean Values

  • Operator Precedence – Expression – Conditionals: If-Else Constructs – Loop Structures/Iterative Statements – While Loop – For Loop – Break Statement-Continue statement
  • Function Call and Returning Values – Parameter Passing – Local and Global Scope – Recursive Functions

Introduction:

Python is a general purpose interpreted, interactive, object-oriented and high-level programming language. Python was created by Guido van Rossum in the late eighties and early nineties. Like Perl, Python source code is now available under the GNU General Public License (GPL).Python was designed to be highly readable which uses English keywords frequently where as other languages use punctuation and it has fewer syntactical constructions than other languages.

  • Python is interpreted: This means that it is processed at runtime by the interpreter and you do not need to compile your program before executing it. This is similar to PERL and PHP.

  • Python is Interactive: This means that you can actually sit at a Python prompt and interact with the interpreter directly to write your programs.

  • Python is Object-Oriented: This means that Python supports Object-Oriented style or technique of programming that encapsulates code within objects.

  • Python is Beginner's Language: Python is a great language for the beginner programmers and supports the development of a wide range of applications, from simple text processing to WWW browsers to games.

Syntax and Style:

Statements and Syntax

Some rules and certain symbols are used with regard to statements in Python:

Symbol Description

Hash mark ( # ) Indicates Python comments

NEWLINE ( \n ) The standard line separator (one statement per line) Backslash ( \ ) Continues a line

Semicolon ( ; ) Joins two statements on a line Colon ( : ) Separates a header line from its suite

Comments:

A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the physical line end are part of the comment, and the Python interpreter ignores them.

#!/usr/bin/python # First comment

print "Hello, Python!"; # second comment This will produce following result:

Hello, Python!

A comment may be on the same line after a statement or expression: name = "Madisetti" # This is again comment

You can comment multiple lines as follows:

This is a comment.This is a comment, too. # This is a comment, too. # I said that already.

Continuation ( \ ):

In Python you normally have one instruction per line. Long instructions can span several lines using the line-continuation character “\”. Some instructions, as triple quoted strings, list, tuple and dictionary constructors or statements grouped by parentheses do not need a line-continuation character. It is possible to write several statements on the same line, provided they are separated by semi-colons.

check conditions

if (weather_is_hot == 1) and \ (shark_warnings == 0) :

name = "John" # A string print counter

print miles print name

Here 100, 1000 and "John" are the values assigned to counter, miles and name variables, respectively. While running this program, this will produce following result:

Values and types

A value is one of the fundamental things like a letter or a number that a program manipulates. The values we have seen so far are 2 (the result when we added 1 + 1), and 'Hello, World!'.

These values belong to different types : 2 is an integer, and 'Hello, World!' is a string , so-called because it contains a "string" of letters. You (and the interpreter) can identify strings because they are enclosed in quotation marks.

The print statement also works for integers.

>>> print 4 4

If you are not sure what type a value has, the interpreter can tell you.

>>> type('Hello, World!') <type 'str'> >>> type(17) <type 'int'>

Not surprisingly, strings belong to the type str and integers belong to the type int. Less obviously, numbers with a decimal point belong to a type called float, because these numbers are represented in a format called floating-point.

>>> type(3) <type 'float'>

What about values like '17' and '3'? They look like numbers, but they are in quotation marks like strings.

>>> type('17') <type 'str'>

A common way to represent variables on paper is to write the name with an arrow pointing to the variable's value. This kind of figure is called a state diagram because it shows what state each of the variables is in (think of it as the variable's state of mind). This diagram shows the result of the assignment statements:

The print statement also works with variables.

>>> print message What's up, Doc? >>> print n 17 >>> print pi 3.

In each case the result is the value of the variable. Variables also have types; again, we can ask the interpreter what they are.

>>> type(message) <type 'str'> >>> type(n) <type 'int'> >>> type(pi) <type 'float'>

The type of a variable is the type of the value it refers to.

2 Variable names and keywords

Programmers generally choose names for their variables that are meaningful they document what the variable is used for.

Variable names can be arbitrarily long. They can contain both letters and numbers, but they have to begin with a letter. Although it is legal to use uppercase letters, by convention we don't. If you do, remember that case matters. Bruce and bruce are different variables.

The underscore character (_) can appear in a name. It is often used in names with multiple words, such as my_name or price_of_tea_in_china.

If you give a variable an illegal name, you get a syntax error:

>>> 76trombones = 'big parade' SyntaxError: invalid syntax >>> more$ = 1000000 SyntaxError: invalid syntax >>> class = 'Computer Science 101' SyntaxError: invalid syntax

76trombones is illegal because it does not begin with a letter. more$ is illegal because it contains an illegal character, the dollar sign. But what's wrong with class?

It turns out that class is one of the Python keywords. Keywords define the language's rules and structure, and they cannot be used as variable names.

Python has twenty-nine keywords:

and def exec if not return assert del finally import or try break elif for in pass while class else from is print yield continue except global lambda raise

Although expressions contain values, variables, and operators, not every expression contains all of these elements. A value all by itself is considered an expression, and so is a variable.

>>> 17 17 >>> x 2

Confusingly, evaluating an expression is not quite the same thing as printing a value.

>>> message = 'Hello, World!' >>> message 'Hello, World!' >>> print message Hello, World!

When the Python interpreter displays the value of an expression, it uses the same format you would use to enter a value. In the case of strings, that means that it includes the quotation marks. But if you use a print statement, Python displays the contents of the string without the quotation marks.

In a script, an expression all by itself is a legal statement, but it doesn't do anything. The script

17 3. 'Hello, World!' 1 + 1

produces no output at all. How would you change the script to display the values of these four expressions?

2 Operators and operands

Operators are special symbols that represent computations like addition and multiplication. The values the operator uses are called operands.

The following are all legal Python expressions whose meaning is more or less clear:

20+32 hour-1 hour60+minute minute/60 5**2 (5+9)(15-7)

The symbols +, -, and /, and the use of parenthesis for grouping, mean in Python what they mean in mathematics. The asterisk (*) is the symbol for multiplication, and ** is the symbol for exponentiation.

When a variable name appears in the place of an operand, it is replaced with its value before the operation is performed.

Addition, subtraction, multiplication, and exponentiation all do what you expect, but you might be surprised by division. The following operation has an unexpected result:

>>> minute = 59 >>> minute/ 0

The value of minute is 59, and in conventional arithmetic 59 divided by 60 is 0, not 0. The reason for the discrepancy is that Python is performing integer division.

When both of the operands are integers, the result must also be an integer, and by convention, integer division always rounds down , even in cases like this where the next integer is very close.

A possible solution to this problem is to calculate a percentage rather than a fraction:

>>> minute*100/ 98

Interestingly, the + operator does work with strings, although it does not do exactly what you might expect. For strings, the + operator represents concatenation , which means joining the two operands by linking them end-to-end. For example:

fruit = 'banana' bakedGood = ' nut bread' print fruit + bakedGood

The output of this program is banana nut bread. The space before the word nut is part of the string, and is necessary to produce the space between the concatenated strings.

The * operator also works on strings; it performs repetition. For example, 'Fun'*3 is 'FunFunFun'. One of the operands has to be a string; the other has to be an integer.

On one hand, this interpretation of + and * makes sense by analogy with addition and multiplication. Just as 4*3 is equivalent to 4+4+4, we expect 'Fun'*3 to be the same as 'Fun'+'Fun'+'Fun', and it is. On the other hand, there is a significant way in which string concatenation and repetition are different from integer addition and multiplication. Can you think of a property that addition and multiplication have that string concatenation and repetition do not?

2 Composition

So far, we have looked at the elements of a program variables, expressions, and statements in isolation, without talking about how to combine them.

One of the most useful features of programming languages is their ability to take small building blocks and compose them. For example, we know how to add numbers and we know how to print; it turns out we can do both at the same time:

>>> print 17 + 3 20

In reality, the addition has to happen before the printing, so the actions aren't actually happening at the same time. The point is that any expression involving numbers, strings, and variables can be used inside a print statement. You've already seen an example of this:

print 'Number of minutes since midnight: ', hour*60+minute

You can also put arbitrary expressions on the right-hand side of an assignment statement:

percentage = (minute * 100) / 60

This ability may not seem impressive now, but you will see other examples where composition makes it possible to express complex computations neatly and concisely.

Warning: There are limits on where you can use certain expressions. For example, the left-hand side of an assignment statement has to be a variable name, not an expression. So, the following is illegal: minute+1 = hour.

2 Comments

As programs get bigger and more complicated, they get more difficult to read. Formal languages are dense, and it is often difficult to look at a piece of code and figure out what it is doing, or why.

For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing. These notes are called comments , and they are marked with the # symbol:

compute the percentage of the hour that has elapsed

percentage = (minute * 100) / 60

In this case, the comment appears on a line by itself. You can also put comments at the end of a line:

percentage = (minute * 100) / 60 # caution: integer division

Python - Basic Operators

Operators are the constructs which can manipulate the value of operands.

Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.

Types of Operator

Python language supports the following types of operators.

 Arithmetic Operators  Comparison (Relational) Operators  Assignment Operators  Logical Operators  Bitwise Operators  Membership Operators  Identity Operators

Let us have a look on all operators one by one.

Python Arithmetic Operators

Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example

  • Addition Adds values on either side of theoperator. a + b = 30
  • Subtraction Subtracts right hand operand from left hand operand.

a – b = -

  • Multiplies values on either side of thea * b = 200

Multiplication operator

/ Division

Divides left hand operand by right hand operand b / a = 2

% Modulus Divides left hand operand by right hand operand and returns remainder

b % a = 0

** Exponent

Performs exponential (power) calculation on operators a**b =10 to the power 20

//

Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i., rounded away from zero (towards negative infinity) −

9//2 = 4 and 9.0//2 = 4, -11//3 = -4, -11//3 = -4.

Python Comparison Operators

These operators compare the values on either sides of them and decide the relation among them. They are also called Relational operators.

Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example

== If the values of two operands are equal,then the condition becomes true. (a == b) is not true.

!= If values of two operands are not equal, then condition becomes true.

(a != b) is true.

<> If values of two operands are not equal,then condition becomes true. (a <> b) is true. This is similar to !=operator.

AND

operand and assign the result to left operand

%= Modulus AND

It takes modulus using two operands and assign the result to left operand c %= a is equivalent to c = c % a

**= Exponent AND

Performs exponential (power) calculation on operators and assign value to the left operand

c **= a is equivalent to c = c ** a

//= Floor Division

It performs floor division on operators and assign value to the left operand c //= a is equivalent to c = c // a

Python Bitwise Operators

Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in the binary format their values will be 0011 1100 and 0000 1101 respectively. Following table lists out the bitwise operators supported by Python language with an example each in those, we use the above two variables (a and b) as operands −

a = 0011 1100

b = 0000 1101


a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

There are following Bitwise operators supported by Python language

Operator Description Example

& Binary AND

Operator copies a bit to the result if it exists in both operands (a & b) (means 0000 1100)

| Binary OR It copies a bit if it exists in either operand.

(a | b) = 61 (means 0011 1101)

^ Binary XOR

It copies the bit if it is set in one operand but not both. (a ^ b) = 49 (means 0011 0001)

~ Binary Ones Complement

It is unary and has the effect of 'flipping' bits.

(~a ) = -61 (means 1100 0011 in 2's complement form due to a signed binary number.

Was this document helpful?
This is a Premium Document. Some documents on Studocu are Premium. Upgrade to Premium to unlock it.

MC4103 Python Programming UNIT-I

Course: python programming (cs8151)

86 Documents
Students shared 86 documents in this course

University: Anna University

Was this document helpful?

This is a preview

Do you want full access? Go Premium and unlock all 64 pages
  • Access to all documents

  • Get Unlimited Downloads

  • Improve your grades

Upload

Share your documents to unlock

Already Premium?
MC4103 PYTHON PROGRAMMING
UNIT I BASICS OF PYTHON 9
Introduction to Python Programming Python Interpreter and Interactive Mode– Variables and
Identifiers Arithmetic Operators Values and Types Statements. Operators Boolean Values
Operator Precedence Expression Conditionals: If-Else Constructs Loop
Structures/Iterative Statements While Loop For Loop Break Statement-Continue statement
Function Call and Returning Values Parameter Passing Local and Global Scope
Recursive Functions
Introduction:
Python is a general purpose interpreted, interactive, object-oriented and high-level programming
language. Python was created by Guido van Rossum in the late eighties and early nineties. Like
Perl, Python source code is now available under the GNU General Public License (GPL).Python
was designed to be highly readable which uses English keywords frequently where as other
languages use punctuation and it has fewer syntactical constructions than other languages.
Python is interpreted: This means that it is processed at runtime by the interpreter and
you do not need to compile your program before executing it. This is similar to PERL and PHP.
Python is Interactive: This means that you can actually sit at a Python prompt and
interact with the interpreter directly to write your programs.
Python is Object-Oriented: This means that Python supports Object-Oriented style or
technique of programming that encapsulates code within objects.
Python is Beginner's Language: Python is a great language for the beginner
programmers and supports the development of a wide range of applications, from simple text
processing to WWW browsers to games.
Syntax and Style:
Statements and Syntax
Some rules and certain symbols are used with regard to statements in Python:
Symbol Description

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.

Why is this page out of focus?

This is a Premium document. Become Premium to read the whole document.