• No results found

02_PythonIdentifiers.pdf

N/A
N/A
Protected

Academic year: 2020

Share "02_PythonIdentifiers.pdf"

Copied!
31
0
0

Loading.... (view fulltext now)

Full text

(1)

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/

(2)

Outline

1 Python Identifiers

2 Python Conventions

3 Keywords

4 Indentation

5 Multi-line statements

6 Comments

7 Operators

8 Exercises

(3)

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.

(4)

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.

(5)

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)

(6)

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")

(7)

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’]

(8)

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

(9)

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'''

(10)

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.

(11)

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__)

(12)

Using Python interpreter as a calculator I

The interpreter acts as a simple calculator.

The operators +, -, * and / work just like in most other languages

(13)

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):

(14)

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.

(15)

Comments

Problem

Write a program to accept two numbers and print their sum

(16)

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

(17)

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

(18)

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

(19)

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

(20)

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

(21)

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

(22)

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)

(23)

Operators

Operators in Python VII

Write a program to check if a given year is a leap year or not

(24)

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

(25)

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

(26)

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

(27)

Operators

Operator Precedence

(28)

Operator Precedence

(29)

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

(30)

Problem

What is the value of z in the following expression Z=4*6+8//2

(31)

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)

References

Related documents

As of May 30 th 2013, 22 public universities, 9 public constituent university colleges, 17 chartered private universities, 5 private constituent university colleges, 12 private

An SQL Injection Attack (SQLIA) is a type of attack [30] whereby an attacker (a crafted user) adds malicious keywords or operators into an SQL query (e.g., SQL

problemática de la prostitución, Government publication, October 1993, 17-19, 22, 30; Oscar Lewis, Ruth Lewis, and Susan Rigdon, Four Women: Living the Revolution, An Oral History

Discussion Paper Number 22, University of Western Cape, Regional Network for Equity in Health in Southern Africa (EQUINET). Smallholder irrigation schemes, agrarian reform

Title DA FORM 3481 AUG 2011 Author APD Keywords EQUIPMENT OPERATORS QUALIFICATION RECORD EXCEPT AIRCRAFT Created Date 962011 123613 PM.. DA FORM 348 1 AUG 2011 EXCEPT United States

Received 30 October 2013 Received in revised form 15 September 2014 Accepted 22 October 2014 Available online 30 November 2014 Keywords: Headgear Helmets Ergonomics Thermal

Wednesday 22 April Thursday 23 April Friday 24 April Saturday 25 April Sunday 26 April Monday 27 April Tuesday 28 April Wednesday 29 April Thursday 30 April Friday 1 May Saturday 2

Figure 22 Typical dependence of the gate controlled delay time t gd and the maximum gate current i GM 30 Figure 23 Schematic representation of the thyristor and diode turn-off