Python Identifiers, Keywords, and Operators
Nihar Ranjan Roy
[email protected], [email protected] Department of Computer Science and Engineering
GD Goenka University, Gurugram
Home Page:https://sites.google.com/site/niharranjanroy/
Outline
1 Python Identifiers
2 Python Conventions
3 Keywords
4 Indentation
5 Multi-line statements
6 Comments
7 Operators
8 Exercises
Python Identifiers
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other object.
1 An identifier starts with a letter ‘A’ to ‘Z’ or ‘a’ to ‘z’ or an underscore
( ) followed by zero or more letters, underscores and digits (0 to 9).
2 Python does not allow punctuation characters such as @, $, and %
within identifiers.
3 Python is a case sensitive programming language.
Python Conventions
Few conventions being followed in Python
1 Class names start with an uppercase letter. All other identifiers start
with a lowercase letter.
2 Starting an identifier with a single leading underscore indicates that
the identifier is private.
3 Starting an identifier with two leading underscores indicates a strongly
private identifier.
4 If the identifier also ends with two trailing underscores, the identifier
is a language-defined special name.
Keywords
Python Keywords
Below are python reserved words and cannot be used as constant or variable or any other identifier names. All the Python keywords contain lowercase letters only.
and as assert break class continue def
del elif else except False finally for
from global if import in is lambda
None nonlocal not or pass raise return
True try while with yield
import keyword
print(keyword.kwlist)
Indentation is important in Python
Python provides no braces to indicate blocks of code.
Blocks of code are denoted by line indentation, which is rigidly enforced.
The number of spaces in the indentation may vary, but all statements within the block must be indented the same amount.
marks=57; if marks>50:
print("Pass") else:
print("Fail")
print("Program Terminated")
Multi-line statements
Multiline statements
Multiline statements in python are terminated with a\
TotalCost=Var_one+\ Var_two+\ Var_three
Statements contained within the [],{},or() brackets do not need to use the line continuation character. For example
days = [’Monday’, ’Tuesday’, ’Wednesday’, ’Thursday’, ’Friday’,’Saturday’,’Sunday’]
Comments
A hash symbol (#) which is not inside a string literal begins a comment.
Characters following # and up to the end of the physical line are part of the comment and the Python interpreter ignores them.
#This program demostrates comments # in python
print("Hello Nihar") # displays the text
Comments
Multi-line Comments
Multi-line comments can be made using either ”’ or ”””
"""This program demostrates comments in python """
print("Hello Nihar") # displays the text
''' This is another way to write multiline comments in python'''
Docstring in Python I
Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods.
The docstrings are declared using ”””triple double quotes””” just below the class, method or function declaration. All functions should have a docstring.
The docstrings can be accessed using the doc method of the
object or using the help function.
Comments
Docstring in Python II
#defining a function def add(a,b):
""" This function adds two numbers and displays the result """
print(a+b) #initializing a and b a=4, b=5
add(a,b) #calling function print(add.__doc__)
Using Python interpreter as a calculator I
The interpreter acts as a simple calculator.
The operators +, -, * and / work just like in most other languages
Comments
Using Python interpreter as a calculator II
for floor division us // and for remainder user %
Operators with mixed type operands convert the integer (int) operand to floating point (float):
Accepting user input
input() function is used to accept input from the user in Python.
#accept input from the user
username=input("Please enter your name\n")
print("Hello "+username+ " Welcome to the world of Python programming!!")
Above code has the following output.
Comments
Problem
Write a program to accept two numbers and print their sum
Solution
#program to add two numbers no1=input("Input first number ") no2=input("Input second number ") sum=float(no1)+float(no2)
print("Sum is "+str(sum))
python sum.py
Input first number 23 Input second number 12.3 Sum is 35.3
Operators
Operators in Python I
In python operators have been grouped following categories
Arithmetic operators
Assignment operators
Comparison operators
Logical operators Identity operators
Membership operators
Bitwise operators
Operators in Python II
Arithmetic operators are used with numeric values to perform common mathematical operations:
Operator Name Example
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
∗∗ Exponentiation x∗∗ y
// Floor division x // y
Operators
Operators in Python III
Find the output of the following expressions
a=9 b=5 r1=a%b r2=a%-b r3=-a%b r4=-a%-b
Operators in Python IV
Assignment Operators
Assignment operators are used to assign values to variables: a=b
Some of the short hand assignment operators in python are
+= , -=, *=, /=, %= , //=, **=,&= ,|=, V
= ,>>= ,<<=
A short hand operator works like this a+=b is equivalent to a=a+b
Operators
Operators in Python V
Comparison operators are used to compare two values:
Operator Name Example
== Equal x == y
! = Not equal x ! = y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x>= y
<= Less than or equal to x<= y
Operators in Python VI
Logical operators are used to combine conditional statements:
Operator Description Example
and Returns True if both
statements are true
x<5 and y <10
or Returns True if one of the
statements is true
x<5 or y<4
not Reverse the result,
re-turns False if the result is true
not(x <5 and y <10)
Operators
Operators in Python VII
Write a program to check if a given year is a leap year or not
Operators in Python VIII
Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:
Operator Description Example
is Returns true if both
vari-ables are the same object
x is y
is not Returns true if both
vari-ables are not the same object
x is not y
Operators
Operators in Python IX
Membership operators are used to test if a sequence is presented in an object:
Operator Description Example
in Returns True if a sequence with the specified value is present in the object
x in y
not in Returns True if a sequence with the specified value is not present in the object
x not in y
Operators in Python X
Bitwise operators are used to compare (binary) numbers:
Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
V XOR Sets each bit to 1 if only one of two bits
is 1
v NOT Inverts all the bits
<< Zero fill left shift Shift left by pushing zeros in from the
right and let the leftmost bits fall off
>> Signed right shift Shift right by pushing copies of the
left-most bit in from the left, and let the right-most bits fall off
Operators
Operator Precedence
Operator Precedence
Operators
Associativity
When an expression contains operators with equal precedence then the associativity property decides which operation is to be performed first. (Direction of execution)
left to right 4+5-3+2
right to left x=y=z=7
Problem
What is the value of z in the following expression Z=4*6+8//2
Exercises
Exercises
1. Translate each of the following mathematical expressions into an
equivalent Python representation
i. (3+4)/(7)
ii. n(n-1)/2
2. Examine each of the following expression. Predict its output. Also
comment if this expression is legal or illegal, explain why.
i. 10/5
ii. 5//10
iii. 5.0/10
iv. 10%4+8/4
v. 3**10/3
3. Write a program to find area of a circle.
4. Write a program to convert temperature in Centigrade to Fahrenheit.
F = 9
5×C + 32 (1)