Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

Lexical Matters

• Program write as a script


• Lines
• Statement separator is a semicolon, but is only needed when there
is more than one statement on a line. (not recommended)
• A backslash as last character of the line makes the following line a
continuation of the current line.
• But, note that an opening "context" (parenthesis, square bracket, or curly
bracket) makes the backslash unnecessary.

DEPARTMENT OF APPLIED PHYSICS,


EVEN SEMESTER
UNIVERSITY OF CALCUTTA
Lexical Matters
• Comments # this is a comment
• Everything after "#" on a line is ignored. print("Hello world!“)
• Can not write a comment within string print(“# Within a string“)
# this is an example of string
• Types of comments
• Single line Hello world!
• Multiple line # Within a string

DEPARTMENT OF APPLIED PHYSICS,


EVEN SEMESTER
UNIVERSITY OF CALCUTTA
Lexical Matters
• Comments
• Documentation strings or Docstrings are like comments, but they are carried
with executing code.
• Doc strings can be viewed with several tools, e.g. help(), obj.__doc__, and, in IPython, a
question mark (?) after a name will produce help.
• Triple quote is used to write doc string at the top of a module or the first lines after the header
line of a function or class.
• Are not omitted by the interpreter
• About the functionality of a block of code

DEPARTMENT OF APPLIED PHYSICS,


EVEN SEMESTER
UNIVERSITY OF CALCUTTA
Python: Basics
• Variables
• Data types
• Operators
• Arrays
• Flow Control
• Methods
• File Handling
• OOPS

DEPARTMENT OF APPLIED PHYSICS,


EVEN SEMESTER
UNIVERSITY OF CALCUTTA
VALUES AND VARIABLES
Integer Values
String Values
Variables and Assignment

DEPARTMENT OF APPLIED PHYSICS,


EVEN SEMESTER
UNIVERSITY OF CALCUTTA
Integer Values
• Python supports a number of numeric and
nonnumeric values
• The Python statement print(4) prints the value 4, >>> 4
no require of quotation mark 4
>>> 3 + 4
• The value 4 is an example of an integer 7
expression. >>> 1 + 2 + 4 + 10 + 3
• The interactive shell attempts to evaluate both 20
>>> print(1 + 2 + 4 + 10 + 3)
expressions and statements 20
• Interactive shell’s sole activity consists of >>>x=4 No output will show, as
1. reading the text entered by the user, >>>x ‘x’ is not a value but
4 variable
2. attempting to evaluate the user’s input in the context of
what the user has entered up that point, and
3. printing its evaluation of the user’s input.

DEPARTMENT OF APPLIED PHYSICS,


EVEN SEMESTER
UNIVERSITY OF CALCUTTA
String Values >>> 19
19
>>> "19" String, not an
• A string is a sequence of characters '19'
>>> '19'
integer value
• Python recognizes both single quotes (') and '19’
>>> "Fred"
double quotes (") as valid ways to delimit a 'Fred'
string value. >>> 'Fred'
'Fred’
• String start with left ‘ symbol and ends with right >>> Fred
‘ symbol and similar for double quote symbol Traceback (most recent call last):
File "<stdin>", line 1, in <module>
• All expressions in Python have a type, NameError: name 'Fred' is not defined
sometimes denoted as its class
>>> str(1024)
>>> type(4) '1024'
<class 'int'> >>> int('wow')
Traceback (most recent call last):
>>> type('4') File "<stdin>", line 1, in <module>
<class 'str'> ValueError: invalid literal for int() with
base 10: 'wow'
• Any integer has a string representation, but not >>> int('3.4')
all strings have an integer equivalent Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with
base 10: '3.4'
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER
UNIVERSITY OF CALCUTTA
String Values
• Strings can be specified using single quotes. All white space are preserved as-is.
• Strings in double quotes work exactly the same way
• Multi-line strings can be specified using triple quotes - (""" or ‘‘’).
• Single quotes and double quotes can be used freely within the triple quotes.
'''This is a multi-line string. This
is the first line.
This is the second line.
"What's your name?," I asked.
He said "Bond, James Bond."
‘’’

This is a multi-line string. This is


the first line.
This is the second line.
"What's your name?," I asked.
He said "Bond, James Bond."

DEPARTMENT OF APPLIED PHYSICS,


EVEN SEMESTER
UNIVERSITY OF CALCUTTA
String Values
• Escape sequences are define 'What’s your name?’
File "<ipython-input-14-07336096f76e>",
special feature for string line 1
'What's your name?'
• \ can be used to single or double ^
quote within a string written within SyntaxError: invalid syntax
Escape
a single quote of double quote 'What\'s your name?’ sequence
marks "What's your name?“

• Backslash at the end of a line is used "What's your name?“


"What's your name?”
to indicate the continuation of the
string, but no new line is added print(" What\'s your
live?")
name? \n Where are you

• \n : starting of new line


What's your name?
• \b : backspace Where are you live?

• \t : tab >>> print('A\nB\nC’) A


• \a: ASCII Bell >>> print('D\tE\tF')
>>> print('WX\bYZ')
B
C
>>> print('1\a2\a3\a4\a5\a6') D E F
WYZ
123456
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER
UNIVERSITY OF CALCUTTA
String Values
• Escape sequences are define
special feature for string
#A backslash followed by three integers will
result in a octal value:
• \ooo: Octal value txt = "\110\145\154\154\157"
print(txt)
• \xh: Hex value
#A backslash followed by an 'x' and a hex
number represents a hex value:
txt = "\x48\x65\x6c\x6c\x6f"
print(txt)

DEPARTMENT OF APPLIED PHYSICS,


EVEN SEMESTER
UNIVERSITY OF CALCUTTA
String Values
• Raw Strings no special processing such as escape sequences
are handled
• Specify a raw string by prefixing r or R to the string.

s = 'a\tb\nA\tB’ rs = r'a\tb\nA\tB’
print(s) print(rs)

DEPARTMENT OF APPLIED PHYSICS,


EVEN SEMESTER
UNIVERSITY OF CALCUTTA
Integer and String Values
Mixing the two types directly is not
• Working with ‘+’ operator allowed
>>> '5' + 10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object
The plus operator (+) works differently for to str implicitly
strings; consider >>> 5 + '10'
>>> 5 + 10 Traceback (most recent call last):
File "<stdin>", line 1, in <module>
15
TypeError: unsupported operand type(s)
>>> '5' + '10' for +: 'int' and 'str'
'510'
>>> 'abc' + 'xyz' >>> 5 + int('10')
'abcxyz' 15
>>> '5' + str(10)
'510'

DEPARTMENT OF APPLIED PHYSICS,


EVEN SEMESTER
UNIVERSITY OF CALCUTTA
Variables and Assignment
>>> x = 5
• Variable is like a memory, where >>> x
5
value is stored >>> 5 = x
File "<stdin>", line 1
• Python variables also can represent values other than SyntaxError: can't assign to literal
numbers

Assignment statement:
x = 10 “x is assigned the value
print(x) x = 10
10,” print('x = ' + str(x))
x = 20
print('x = ' + str(x))
Assignment operator x = 30
print('x =', x)

x = 10
x = 20
comma-separated list
x = 30

DEPARTMENT OF APPLIED PHYSICS,


EVEN SEMESTER
UNIVERSITY OF CALCUTTA
Python Identifiers
• Normally, in mathematic calculation, a shorter variable
name chosen like x,
• Programmers should use longer, more descriptive variable
names.
• Good variable names make programs more readable by
humans.
• Names such as sum, height, and sub_total are much better than
the equally permissible s, h, and st.
• A variable’s name should be related to its purpose within
the program.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER
UNIVERSITY OF CALCUTTA
Python Identifiers
• A Python identifier is a name used to identify a variable,
function, class, module or other object.
• A variable name is one example of an identifier
• 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).

DEPARTMENT OF APPLIED PHYSICS,


EVEN SEMESTER
UNIVERSITY OF CALCUTTA
Python Identifiers
• Identifiers have the following form:
• An identifiers must contain at least one character.
• The first character of an identifiers must be an alphabetic letter (upper or lower
case) or the underscore
• ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_
• The remaining characters (if any) may be alphabetic characters (upper or lower
case), the underscore, or a digit
• ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_0123456789
• No other characters (including spaces) are permitted in identifiers.
• A reserved word cannot be used as an identifier.
• Python does not allow punctuation characters such as @, $, and % within
identifiers

DEPARTMENT OF APPLIED PHYSICS,


EVEN SEMESTER
UNIVERSITY OF CALCUTTA
Reserved Words
• Predefined meaning and syntax
• Can’t be used as identifiers for other programming elements like
name of variable, function etc.
• To check the keyword list, type following commands in
interpreter −
>>> import keyword
>>> keyword.kwlist
• To check whether a string is a keyword or not, we have a
keyword module import keyword
print( keyword.iskeyword(“var”) )
print( keyword.iskeyword(“False”) )
DEPARTMENT OF APPLIED PHYSICS, print( keyword.iskeyword(“continue”) )
EVEN SEMESTER
UNIVERSITY OF CALCUTTA print( keyword.iskeyword(“count”) )
Reserved Words
and False not
as finally or
assert for pass
break from raise
class global return
continue if True
def import try
del in while
elif is with
else lambda yield
Except None
exec nonlocal
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER
UNIVERSITY OF CALCUTTA
Reserved Words
>>> class = 15 >>> print('Our good friend print')

File "<stdin>", line 1 Our good friend print

class = 15 >>> print


<built-in function print>
ˆ
>>> type(print)
SyntaxError: invalid syntax
<class 'builtin_function_or_method'>
>>> print = 77
>>> print
77
>>> print('Our good friend print')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> type(print)
<class 'int'>

DEPARTMENT OF APPLIED PHYSICS,


EVEN SEMESTER
UNIVERSITY OF CALCUTTA
Python Identifiers
• Naming conventions for Python identifiers −
• Class names start with an uppercase letter. All other identifiers
start with a lowercase letter.
• Starting an identifier with a single leading underscore indicates
that the identifier is private.
• Starting an identifier with two leading underscores indicates a
strongly private identifier.
• If the identifier also ends with two trailing underscores, the
identifier is a language-defined special name.
class Dog: class Dog: >>> Dog1 = Dog("Labrador Retriver",
def __init__(self,dogBreed,dogEyeColor): "Brown")
def __init__(self,dogBreed,dogEyeColor): self.breed = dogBreed >>> Dog1.breed
self.breed = dogBreed self.eyeColor = dogEyeColor 'Labrador Retriver'
self.eyeColor = dogEyeColor >>> Dog1.eyeColor
'Brown'
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER
UNIVERSITY OF CALCUTTA
Python Identifiers
• Python is a case-sensitive language. → This means that
capitalization matters.
• if is a reserved word, but If, IF, or iF is a reserved word
• Identifiers also are case sensitive; the variable called Name
is different from the variable called name.
• Programmes must not be written to confuse human reader

DEPARTMENT OF APPLIED PHYSICS,


EVEN SEMESTER
UNIVERSITY OF CALCUTTA
Floating-point Numbers
• Python supports floating number system
• The range of floating-points values (smallest value to largest value,
both positive and negative) and precision (the number of digits
available) depends of the Python implementation for a particular
machine >>> round(x, 0)
>>> x = 23.3123400654033989 >>> x = 28793.54836 28794.0
>>> x >>> round(x) >>> round(x, 1)
23.312340065403397 28794 28793.5
>>> c = 2.998e8 >>> round(x, 1) >>> round(x, -1)
28793.5 28790.0
round(n, r) rounds
exponent floating-point expression
>>> round(x, 2) >>> round(x, -2)
of 10 𝑛 to the 10−𝑟 decimal 28793.55 28800.0
digit
>>> round(x, -3)
29000.0
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER
UNIVERSITY OF CALCUTTA
User Input
• User can feed input during the execution of a program/code
with, x = input() produces
print('Please enter some text:') only strings print('Please enter an integer value:')
x = input() x = input()
print('Text entered:', x) print('Please enter another integer value:')
print('Type:', type(x)) y = input()
num1 = int(x)
Please enter some text: num2 = int(y)
Computer programming print(num1, '+', num2, '=', num1 + num2)
Text entered: Computer programming
Type: <class 'str'> Please enter an integer value:
2
num1 = int(input('Please enter an integer Please enter another integer value:
value: ')) 17
num2 = int(input('Please enter another integer 2 + 17 = 19
value: '))
print(num1, '+', num2, '=', num1 + num2) Functional
num3 = int(float(input('Please enter a number: composition Does not accept
'))) float value
Accept int or
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER
UNIVERSITY OF CALCUTTA float value
print Function
w, x, y, z = 10, 15, 20, 25 10 15 20 25 print(‘{1} {0}’.format(0, 10**0))
print(w, x, y, z) 10,15,20,25 print(‘{1} {0}’.format(1, 10**1))
print(w, x, y, z, sep=',') 10152025 print(‘{1} {0}’.format(2, 10**2))
print(w, x, y, z, sep='') 10:15:20:25 print(‘{1} {0}’.format(3, 10**3))
print(w, x, y, z, sep=':') 10-----15-----20-----25 print(‘{1} {0}’.format(4, 10**4))
print(w, x, y, z, sep='-----')

Formatting string
print('{0} {1}'.format(0, 10**0)) 0 1 1 0
print('{0} {1}'.format(1, 10**1)) 1 10 10 1
print('{0} {1}'.format(2, 10**2)) 2 100 100 2
print('{0} {1}'.format(3, 10**3)) 3 1000 1000 3
print('{0} {1}'.format(4, 10**4)) 4 10000 10000 4

DEPARTMENT OF APPLIED PHYSICS,


EVEN SEMESTER
UNIVERSITY OF CALCUTTA
Problem
1. You have an N-element tuple or sequence that you would
like to unpack into a collection of N variables.
2. You need to unpack N elements from an iterable, but the
iterable may be longer than N elements, causing a “too
many values to unpack” exception Star Expression

>>> record = ('Dave', 'dave@example.com',


'773-555-1212', '847-555-1212')
>>> p = (4, 5)
>>> name, email, *phone_numbers =
>>> x, y = p user_record
>>> name
>>> data = [ 'ACME', 50, 'Dave'
91.1, (2012, 12, 21) ] >>> email
>>> name, shares, price, date 'dave@example.com'
= data >>> phone_numbers
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER
UNIVERSITY OF CALCUTTA
Problem
• Make a list of the largest or smallest N items in a collection

import heapq
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
print(heapq.nlargest(3, nums)) # Prints [42, 37, 23]
print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2]

DEPARTMENT OF APPLIED PHYSICS,


EVEN SEMESTER
UNIVERSITY OF CALCUTTA

You might also like