Python Syntax
Python Syntax
1
Elements of Python
2
Variables
3
Identifiers
4
Identifiers
5
6
Assignment Statement
7
8
Multiple Assignments
9
Comments in Python
10
Types in Python
11
12
Type Conversion (Type Cast)
13
Example
14
Type Conversion and Input
15
Operators
16
Binary Operations
17
Unary Operators
18
The // operator
19
The % operator
20
Recap
21
22
What is the value assigned to x?
x = -5*4//2*3+-1*2;
23
24
Basic Data Types in Python
25
26
Strings
27
28
String: Operations(1)
29
String: Operations(2)
30
String Operations: Indexing and
Slicing
Strings can be indexed where the first
character has index 0
Index can be positive as well as negative
Negative indices start counting from the right
Negatives indices start from -1
-1 means last, -2 second last, ... , and so on
Using an index that is too large or too small
results in “index out of range” error
31
String Operations: Indexing and
Slicing
To obtain a substring
s[start : end] means substring of s starting at index start
and ending at index end-1
s[0:len(s)] is same as s
Both start and end are optional
If start is omitted, it defaults to 0
If end is omitted, it defaults to the length of string
s[:] is same as s[0:len(s)], that is same as s
32
More Slicing
>>> print(name[-4:-1]) # substring from fourth last character to the
second last character from end
>>> print(name[-4:]) # substring from fourth last character of string
>>> print(name[-4:4]) # substring from fourth last character to the
character at index 3
33
Out of Range Slicing A
0
c
1
a
2
d
3
s
4
-5 -4 -3 -2 -1
34
Specifying a Stride in a String Slice
35
Other String functions
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
edswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position of
where it was found
format() Formats specified values in a string
split() Splits the string at the specified separator, and returns a list
36
37
Unpacking Strings
38
Exercises
Q1. Read radius of a circle and side of a
square from user using single input() method.
Then calculate and display area of the circle
and the square.
Input:
3.33 3.33
Output:
Area of circle:34.82
Area of square:11.09
39
Q2. Write a program that reads names of two
python files and strips the extension. The
filenames are then concatenated to form a
single string. The program then prints 'True' if
the newly generated string is palindrome, or
prints 'False' otherwise.
Input: malay.py alam.py
Output: True
40
Q3. Write a program that reads full name as a
input and returns abbreviations of the first
and middle names except the last name.
Note that the abbreviations must be in capitals.
Also, only the first letter in the Surname must be in
higher case.
Eg.
Input: Sachin Ramesh Tendulkar
Output: S. R. Tendulkar
41