Lorem

Delete this widget in your dashboard. This is just an example.

Ipsum

Delete this widget in your dashboard. This is just an example.

Dolor

Delete this widget in your dashboard. This is just an example.
 

Expressions in python

 

Expressions

    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. So, what are these?

Identifiers: Any name that is used to define a class, function, variable module, or object is an identifier. Literals: These are language-independent terms in Python and should exist independently in any programming language. In Python, there are the string literals, byte literals, integer literals, floating point literals, and imaginary literals. Operators: In Python you can implement the following operations using the corresponding tokens.

OperatorToken
add+
subtract-
multiply*
power**
Integer Division/
remainder%
decorator@
Binary left shift<<
Binary right shift>>
and&
or\
Binary Xor^
Binary ones complement~
Less than<
Greater than>
Less than or equal to<=
Greater than or equal to>=
Check equality==
Check not equal!=

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:

true_value if Condition else false_value

Example:

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

Precedence and Associativity of Operators in Python

 

Precedence and Associativity of Operators in Python

In this tutorial, you'll learn how precedence and associativity of operators affect the order of operations in Python.

Precedence of Python Operators

The combination of values, variables, operators, and function calls is termed as an expression. The Python interpreter can evaluate a valid expression.

For example:

>>> 5 - 7
-2

Here 5 - 7 is an expression. There can be more than one operator in an expression.

To evaluate these types of expressions there is a rule of precedence in Python. It guides the order in which these operations are carried out.

For example, multiplication has higher precedence than subtraction.

# Multiplication has higher precedence
# than subtraction
>>> 10 - 4 * 2
2

But we can change this order using parentheses () as it has higher precedence than multiplication.

# Parentheses () has higher precedence
>>> (10 - 4) * 2
12

The operator precedence in Python is listed in the following table. It is in descending order (upper group has higher precedence than the lower ones).

OperatorsMeaning
()Parentheses
**Exponent
+x, -x, ~xUnary plus, Unary minus, Bitwise NOT
*, /, //, %Multiplication, Division, Floor division, Modulus
+, -Addition, Subtraction
<<, >>Bitwise shift operators
&Bitwise AND
^Bitwise XOR
|Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not inComparisons, Identity, Membership operators
notLogical NOT
andLogical AND
orLogical OR

Let's look at some examples:

Suppose we're constructing an if...else block which runs if when lunch is either fruit or sandwich and only if money is more than or equal to 2.

# Precedence of or & and
meal = "fruit"

money = 0

if meal == "fruit" or meal == "sandwich" and money >= 2:
    print("Lunch being delivered")
else:
    print("Can't deliver lunch")

Output

Lunch being delivered

This program runs if block even when money is 0. It does not give us the desired output since the precedence of and is higher than or.

We can get the desired output by using parenthesis () in the following way:

# Precedence of or & and
meal = "fruit"

money = 0

if (meal == "fruit" or meal == "sandwich") and money >= 2:
    print("Lunch being delivered")
else:
    print("Can't deliver lunch")

Output

Can't deliver lunch

Associativity of Python Operators

We can see in the above table that more than one operator exists in the same group. These operators have the same precedence.

When two operators have the same precedence, associativity helps to determine the order of operations.

Associativity is the order in which an expression is evaluated that has multiple operators of the same precedence. Almost all the operators have left-to-right associativity.

For example, multiplication and floor division have the same precedence. Hence, if both of them are present in an expression, the left one is evaluated first.

# Left-right associativity
# Output: 3
print(5 * 2 // 3)

# Shows left-right associativity
# Output: 0
print(5 * (2 // 3))

Output

3
0

Note: Exponent operator ** has right-to-left associativity in Python.

# Shows the right-left associativity of **
# Output: 512, Since 2**(3**2) = 2**9
print(2 ** 3 ** 2)

# If 2 needs to be exponated fisrt, need to use ()
# Output: 64
print((2 ** 3) ** 2)

We can see that 2 ** 3 ** 2 is equivalent to 2 ** (3 ** 2).


Non associative operators

Some operators like assignment operators and comparison operators do not have associativity in Python. There are separate rules for sequences of this kind of operator and cannot be expressed as associativity.

For example, x < y < z neither means (x < y) < z nor x < (y < z)x < y < z is equivalent to x < y and y < z, and is evaluated from left-to-right.

Furthermore, while chaining of assignments like x = y = z = 1 is perfectly valid, x = y = z+= 2 will result in error.

# Initialize x, y, z
x = y = z = 1

# Expression is invalid
# (Non-associative operators)
# SyntaxError: invalid syntax

x = y = z+= 2

Output

  File "<string>", line 8
    x = y = z+= 2
             ^
SyntaxError: invalid syntax

Python Output Using print() function

 

Python Output Using print() function

We use the print() function to output data to the standard output device (screen). We can also output data to a file, but this will be discussed later.

An example of its use is given below.

print('This sentence is output to the screen')

Output

This sentence is output to the screen

Another example is given below:

a = 5
print('The value of a is', a)

Output

The value of a is 5

In the second print() statement, we can notice that space was added between the string and the value of variable a. This is by default, but we can change it.

The actual syntax of the print() function is:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Here, objects is the value(s) to be printed.

The sep separator is used between the values. It defaults into a space character.

After all values are printed, end is printed. It defaults into a new line.

The file is the object where the values are printed and its default value is sys.stdout (screen). Here is an example to illustrate this.

print(1, 2, 3, 4)
print(1, 2, 3, 4, sep='*')
print(1, 2, 3, 4, sep='#', end='&')

Output

1 2 3 4
1*2*3*4
1#2#3#4&

Output formatting

Sometimes we would like to format our output to make it look attractive. This can be done by using the str.format() method. This method is visible to any string object.

>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
The value of x is 5 and y is 10

Here, the curly braces {} are used as placeholders. We can specify the order in which they are printed by using numbers (tuple index).

print('I love {0} and {1}'.format('bread','butter'))
print('I love {1} and {0}'.format('bread','butter'))

Output

I love bread and butter
I love butter and bread

We can even use keyword arguments to format the string.

>>> print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name = 'John'))
Hello John, Goodmorning

We can also format strings like the old sprintf() style used in C programming language. We use the % operator to accomplish this.

>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457

Python Input

Up until now, our programs were static. The value of variables was defined or hard coded into the source code.

To allow flexibility, we might want to take the input from the user. In Python, we have the input() function to allow this. The syntax for input() is:

input([prompt])

where prompt is the string we wish to display on the screen. It is optional.

>>> num = input('Enter a number: ')
Enter a number: 10
>>> num
'10'

Here, we can see that the entered value 10 is a string, not a number. To convert this into a number we can use int() or float() functions.

>>> int('10')
10
>>> float('10')
10.0

This same operation can be performed using the eval() function. But eval takes it further. It can evaluate even expressions, provided the input is a string

>>> int('2+3')
Traceback (most recent call last):
  File "<string>", line 301, in runcode
  File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '2+3'
>>> eval('2+3')
5

Python Import

When our program grows bigger, it is a good idea to break it into different modules.

A module is a file containing Python definitions and statements. Python modules have a filename and end with the extension .py.

Definitions inside a module can be imported to another module or the interactive interpreter in Python. We use the import keyword to do this.

For example, we can import the math module by typing the following line:

import math

We can use the module in the following ways:

import math
print(math.pi)

Output

3.141592653589793

Now all the definitions inside math module are available in our scope. We can also import some specific attributes and functions only, using the from keyword. For example:

>>> from math import pi
>>> pi
3.141592653589793

While importing a module, Python looks at several places defined in sys.path. It is a list of directory locations.

>>> import sys
>>> sys.path
['', 
 'C:\\Python33\\Lib\\idlelib', 
 'C:\\Windows\\system32\\python33.zip', 
 'C:\\Python33\\DLLs', 
 'C:\\Python33\\lib', 
 'C:\\Python33', 
 'C:\\Python33\\lib\\site-packages']

Expressions in python

  Expressions Python Expressions: Expressions are representations of value. They are different from statement in the fact that statements do...

Lorem

Please note: Delete this widget in your dashboard. This is just a widget example.

Ipsum

Please note: Delete this widget in your dashboard. This is just a widget example.

Dolor

Please note: Delete this widget in your dashboard. This is just a widget example.