Here n is a variable name. The value of that variable is 176.

Similar documents
\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

PYTHON. Varun Jain & Senior Software Engineer. Pratap, Mysore Narasimha Raju & TEST AUTOMATION ARCHITECT. CenturyLink Technologies India PVT LTD

Introduction to Python

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

JAVA OPERATORS GENERAL

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

RUBY OPERATORS. Ruby Arithmetic Operators: Ruby Comparison Operators:

Python at Glance. a really fast (but complete) ride into the Python hole. Paolo Bellagente - ES3 - DII - UniBS

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Chapter 4 : Informatics Practices. Data Handling. Class XI ( As per CBSE Board) Visit : python.mykvs.in for regular updates

Operators. Java operators are classified into three categories:

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

UNIVERSITÀ DI PADOVA. < 2014 March >

Chapter 4. Operations on Data

Chapter 3 : Computer Science. Class XI ( As per CBSE Board) Data Handling. Visit : python.mykvs.in for regular updates

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

ENGR 101 Engineering Design Workshop

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Advanced Algorithms and Computational Models (module A)

Data Handing in Python

Fundamental of Programming (C)

PYTHON- AN INNOVATION

Python memento TI-Smart Grids

Variable and Data Type I

Operators in C. Staff Incharge: S.Sasirekha

SECTION II: LANGUAGE BASICS

UNIT- 3 Introduction to C++

DaMPL. Language Reference Manual. Henrique Grando

Unit 3. Operators. School of Science and Technology INTRODUCTION

COMP Primitive and Class Types. Yi Hong May 14, 2015

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

Variable and Data Type I

Chapter 3: Operators, Expressions and Type Conversion

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore

CS 115 Lecture 4. More Python; testing software. Neil Moore

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Operators & Expressions

Fundamentals of Programming

Prof. Navrati Saxena TA: Rochak Sachan

Chapter 3 : Informatics Practices. Class XI ( As per CBSE Board) Python Fundamentals. Visit : python.mykvs.in for regular updates

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Python Intro GIS Week 1. Jake K. Carr

Department of Computer Science

4 Operations On Data 4.1. Foundations of Computer Science Cengage Learning

Python: common syntax

CMSC201 Computer Science I for Majors

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

DEPARTMENT OF MATHS, MJ COLLEGE

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

Conditional Expressions and Decision Statements

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following g roups:

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

9/10/10. Arithmetic Operators. Today. Assigning floats to ints. Arithmetic Operators & Expressions. What do you think is the output?

Full file at C How to Program, 6/e Multiple Choice Test Bank

Information Science 1

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

Collections. Lists, Tuples, Sets, Dictionaries

Expressions and Precedence. Last updated 12/10/18

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

SOFTWARE DEVELOPMENT 1. Operators 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

CA4003 Compiler Construction Assignment Language Definition

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

The SPL Programming Language Reference Manual

Chapter 2, Part III Arithmetic Operators and Decision Making

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

The Java language has a wide variety of modifiers, including the following:

And Parallelism. Parallelism in Prolog. OR Parallelism

Downloaded from Chapter 2. Functions

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Built-in Types of Data

1. What type of error produces incorrect results but does not prevent the program from running? a. syntax b. logic c. grammatical d.

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

Fundamentals of Programming (Python) Getting Started with Programming

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

STSCI Python Introduction. Class URL

L-System Fractal Generator: Language Reference Manual

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Arithmetic and Bitwise Operations on Binary Data

Introduction to Python

Lecture 3 Tao Wang 1

Course Outline. Introduction to java

VLC : Language Reference Manual

Unit-2 (Operators) ANAND KR.SRIVASTAVA

Revision of Basics of Python

Outline. Data and Operations. Data Types. Integral Types

Data Types and Conversion

Operators and Expressions

Lexical Considerations

The pixelman Language Reference Manual. Anthony Chan, Teresa Choe, Gabriel Kramer-Garcia, Brian Tsau

Transcription:

UNIT II DATA, EXPRESSIONS, STATEMENTS 9 Python interpreter and interactive mode; values and types: int, float, boolean, string, and list; variables, expressions, statements, tuple assignment, precedence of operators, comments; modules and functions, function definition and use, flow of execution, parameters and arguments; Illustrative programs: exchange the values of two variables, circulate the values of n variables distance between two points. Unit-II Two Marks 1.Define values and types A value is one of the basic things ina programs like a letter or a number. The values are belonging to different types. For example >>> type( Hello ) <type str > >>> type(17) <type float > 2. Define variables. A variable is a name that refers to a value. They can contain both letters and numbers but they do not begin with a letter. The underscore _ can appear in a name. Example: >>> n=176 Here n is a variable name. The value of that variable is 176. 3.Define Boolean Operators. A Boolean expression is an expression that is either true (or) false. The Operator == which compares two operands and produces True if they are equal otherwise it is false. >>> 5==5 True >>> 5==6 False 4. Define String A string is a sequence of characters. We can access the character one at a time. >>> fruit= banana

>>> letter = fruit[0] >>> print letter B 5.Define List. A List is a sequence of values. The values are characters in a list they can be of any type. The values in a list are called elements. Examples [10,20,30,40] number List [ a, b, c, d ]-> Character List [ a,20,5,25.5,[20,30]]-> Nested List []-> Empty List 6.What do you mean by mutable list. The values in the list are changed. So it is called mutable list. >>> n=[17,35] >>> n[0]=5 >>>n=[5,35]-> n[0] is changed as 5. 7. Define Expression An expression is a combination of values, variables and operators. A value all by itself is considered an expression. 8. Define Tuples A Tuple is a sequence of values. The values can be of any type, They are indexed by integers. Tuples are immutable. A tuple is a comma separated list of values. >>> t=( a, b, c ) 9. What is the function of slice in tuple? It prints the values from starting to end-1. >>> t[1:3]

>>( a, b ) 10. Write a program for swapping of two numbers? a=5 b=6 a,b=b,a print (a,b) 11. What are different Membership Operators in python? In Evaluates to true, if it finds a variable in the specified sequence and false otherwise. Not in- Evaluates to true, if it does not finds a variable in the specified sequence and false otherwise. 12.Define Functions A function is a named sequence of statements that performs a computation. A function takes an argument and returns a result. The result is called the return value. Example def print_1(): print ( welcome ) 13.Define Module A module is a file that contains a collection of related functions. >>> import math >>> print math < module math (built-in)> 14.What are the different types of arguments? 1.Function arguments 2.keyword arguments 3.Default arguments 4.variable length arguments. PART-B (16 marks)

1. Define Operators. What are the different types of Operators in python? Explain in detail. 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 Python Arithmetic Operators Assume variable a holds 10 and variable b holds 20, then Operator Description Example + Addition Adds values on either side of the a + b = 30 operator. - Subtraction Subtracts right hand operand from left a b = -10 hand operand. * Multiplies values on either side of the a * b = 200 Multiplication operator / Division Divides left hand operand by right b / a = 2 hand operand % Modulus Divides left hand operand by right b % a = 0 hand operand and returns remainder ** Exponent Performs exponential (power) a**b =10 to the power 20 calculation on operators Floor Division - The division of operands where the result is the // quotient in which the digits after the 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, decimal point are removed. But if one -11.0//3 = -4.0 of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity): 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, (a == b) is not true. then the condition becomes true.!= If values of two operands are not equal, then condition becomes true. If the value of left operand is greater > than the value of right operand, then (a > b) is not true. condition becomes true. If the value of left operand is less than < the value of right operand, then (a < b) is true. condition becomes true. If the value of left operand is greater >= than or equal to the value of right (a >= b) is not true. operand, then condition becomes true. If the value of left operand is less than <= or equal to the value of right operand, (a <= b) is true. then condition becomes true. Python Assignment Operators Assume variable a holds 10 and variable b holds 20, then Operator Description Example Assigns values from right side operands = c = a + b assigns value of a + b into c to left side operand += Add AND -= Subtract AND *= Multiply AND /= Divide AND %= Modulus AND It adds right operand to the left operand and assign the result to left operand c += a is equivalent to c = c + a It subtracts right operand from the left operand and assign the result to left c -= a is equivalent to c = c - a operand It multiplies right operand with the left operand and assign the result to left c *= a is equivalent to c = c * a operand It divides left operand with the right c /= a is equivalent to c = c / ac /= a is operand and assign the result to left equivalent to c = c / a operand It takes modulus using two operands and assign the result to left operand c %= a is equivalent to c = c % a **= Performs exponential (power) Exponent calculation on operators and assign c **= a is equivalent to c = c ** a AND value to the left operand //= Floor It performs floor division on operators c //= a is equivalent to c = c // a Division and assign value to the left operand

Python Bitwise Operators Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in binary format they will be as follows 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 Operator copies a bit to the result if it (a & b) (means 0000 1100) AND exists in both operands It copies a bit if it exists in either Binary OR (a b) = 61 (means 0011 1101) operand. ^ Binary It copies the bit if it is set in one (a ^ b) = 49 (means 0011 0001) XOR operand but not both. ~ Binary (~a ) = -61 (means 1100 0011 in 2's It is unary and has the effect of Ones complement form due to a signed 'flipping' bits. Complement binary number. << Binary Left Shift >> Binary Right Shift The left operands value is moved left by the number of bits specified by the a << = 240 (means 1111 0000) right operand. The left operands value is moved right by the number of bits specified by the a >> = 15 (means 0000 1111) right operand. Python Logical Operators There are following logical operators supported by Python language. Assume variable a holds 10 and variable b holds 20 then Used to reverse the logical state of its operand. Python Membership Operators

Python s membership operators test for membership in a sequence, such as strings, lists, or tuples. There are two membership operators as explained below Operator Description Example in Evaluates to true if it finds a variable in x in y, here in results in a 1 if x is a the specified sequence and false member of sequence y. otherwise. not in Evaluates to true if it does not finds a x not in y, here not in results in a 1 if x is variable in the specified sequence and not a member of sequence y. false otherwise. Python Identity Operators Identity operators compare the memory locations of two objects. There are two Identity operators explained below: Operator Description Example is Evaluates to true if the variables on x is y, here is results in 1 if id(x) equals either side of the operator point to the id(y). same object and false otherwise. is not Evaluates to false if the variables on x is not y, here is not results in 1 if id(x) either side of the operator point to the is not equal to id(y). same object and true otherwise. Python Operators Precedence The following table lists all operators from highest precedence to lowest. Operator Description ** Exponentiation (raise to the power) ~ + - Complement, unary plus and minus (method names for the last two are +@ and -@) * / % // Multiply, divide, modulo and floor division + - Addition and subtraction >> << Right and left bitwise shift & Bitwise 'AND' ^ Bitwise exclusive `OR' and regular `OR' <= < > >= Comparison operators <> ==!= Equality operators = %= /= //= -= += *= Assignment operators **= is is not Identity operators in not in Membership operators

not or and Logical operators 1. Define function?.what are the different types of arguments in python A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for application and a high degree of code reusing. Defining a Function Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ). Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses. The first statement of a function can be an optional statement - the documentation string of the function or docstring. The code block within every function starts with a colon (:) and is indented. The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None. Syntax def functionname( parameters ): "function_docstring" function_suite return [expression] By default, parameters have a positional behavior and you need to inform them in the same order that they were defined. Example The following function takes a string as input parameter and prints it on standard screen. def printme( str ): "This prints a passed string into this function" print str return Calling a Function Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code. Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt. Following is the example to call printme() function #!/usr/bin/python

def printme( str ): "This prints a passed string into this function" print str return; printme("i'm first call to user defined function!") printme("again second call to the same function") I'm first call to user defined function! Again second call to the same function Pass by reference vs value All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example def changeme( mylist ): "This changes a passed list into this function" mylist.append([1,2,3,4]); print "Values inside the function: ", mylist return mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]] Function Arguments You can call a function by using the following types of formal arguments: Required arguments Keyword arguments Default arguments Variable-length arguments Required arguments Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition. # Function definition is here def printme( str ): "This prints a passed string into this function"

print str return; printme() When the above code is executed, it produces the following result: Traceback (most recent call last): File "test.py", line 11, in <module> printme(); TypeError: printme() takes exactly 1 argument (0 given) Keyword arguments Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name. This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. You can also make keyword calls to the printme() function in the following ways #!/usr/bin/python # Function definition is here def printme( str ): "This prints a passed string into this function" print str return; # Now you can call printme function printme( str = "My string") My string Default arguments A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. def printinfo( name, age = 35 ): "This prints a passed info into this function" print "Name: ", name print "Age ", age return; printinfo( age=50, name="miki" ) printinfo( name="miki" ) Name: miki Age 50 Name: miki Age 35

Variable-length arguments You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments. Syntax for a function with non-keyword variable arguments is this def functionname([formal_args,] *var_args_tuple ): "function_docstring" function_suite return [expression] An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Following is a simple example # Function definition is here def printinfo( arg1, *vartuple ): "This prints a variable passed arguments" print "Output is: " print arg1 for var in vartuple: print var return; # Now you can call printinfo function printinfo( 10 ) printinfo( 70, 60, 50 ) Output is: 10 Output is: 70 60 50 1.Simple Calculator Program def sum(a,b): return a+b def sub(a,b): return a-b def mul(a,b): return a*b def div(a,b):

return(a//b) print ("Addition", sum(5,6)) print ("Subtraction",sub(8,4)) print ("Multiplication",mul(8,4)) print ("Division",div(8,2)) Addition 11 Subtraction 4 Multiplication 32 Division 4 2.Circulate n values in a List def rotate(l,y=1): if(len(l)==0): return 1 y=y%len(l) return l[y:]+l[:y] print(rotate([1,2,3,4])) print(rotate([2,3,4,1])) print(rotate([3,4,1,2])) print(rotate([3,2,1,4])) [2, 3, 4, 1] [3, 4, 1, 2] [4, 1, 2, 3] [2, 1, 4, 3] 3. Swapping of two variables def swap(a,b):

print("values before swapping", a,b) a,b=b,a print("values after swapping", a,b) swap(4,5) Values before swapping 4 5 Values after swapping 5 4 4. Distance between two points import math p1 = [4, 0] p2 = [6, 6] distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) ) print(distance) Distance between two points 6.324555320336759 5.Sum of n numbers def sum(n): s=0 for i in range(1,n): s=s+i return s n=input("enter the input value of n") n=int(n) print("sum of n numbers", sum(n)) Enter the input value of n 10

Sum of n numbers 45 6. Sum of odd and even numbers def sumofevenodd(n): se=0 so=0 for i in range(1,n): if i%2==0: se=se+i else: so=so+i return se,so n=input("enter the input value of n") n=int(n) print("sum of n numbers", sumofevenodd(n)) Enter the input value of n 10 Sum of n numbers (20, 25) 7. Variable Length arguments def sum(farg,*args): s=0 for i in args: s=s+i print ("Sum of three numbers",s) sum(1,4,5,6) Sum of three numbers 15 def somefunction(**kwargs):

if 'text' in kwargs: print (kwargs['text']) somefunction(text='welcome') Welcome 9. Keyword arguments def print_info(name,age=25): print ("Name:",name) print("age",age) print_info(name='uma',age=35) print_info(name='reka') Name: Uma Age 35 Name: Reka Age 25