Leela Soft Python Madhu
Language Fundamentals in Python
Install of Python 3:
Windows: Install Python by double click on python<version>.exe file.
After Python Installation:
Windows: Python is included on the system PATH if we install it from the Windows Installer or
if we checked "Add Python 3.7 to PATH" during installation. Otherwise, we must add the install
location to the PATH manually.
To verify, open a command prompt and run the following command:
C:\Users\admin>py -3 --version
Note: We can use the py -0 command in the integrated terminal/CMD to view the versions of
python installed on our machine. The default interpreter is identified by an asterisk (*).
Version Checking:
After Python Installation:
To verify, open a command prompt and run the following command:
Tyep-1:
C:\Users\admin>py -3 --version
Type-2:
C:\Users\admin>py -0
Installed Pythons found by py Launcher for Windows
-3.7-32 * (here * is current version in our windows path)
-3.6-32
-2.7-32
How many ways to run a Python Script or Program:
Way1: By Using Python Interpreter:
Open Python Interpreter:
Start Menu -> All Programs -> Python3.7 ->next click on Python3.7 interpreter ->then write
our script ->press Enter.
REPL:
A read–eval–print loop (REPL), also termed an interactive top level or language shell, is a
simple, interactive computer programming environment that takes single user inputs (i.e.,
single expressions), evaluates them, and returns the result to the user; a program written in a
REPL environment is executed piecewise.
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
To start the language shell, type 'python' and press enter in CMD of windows.
Then it starts this process:
Read: take user input.
Eval: evaluate the input.
Print: shows the output to the user.
Loop: repeat.
Way2: By Using Python IDLE (Integrated Development Learning Environment):
Step 1: Open IDLE:
Start Menu -> All Programs -> Python3.7 ->click on IDLE
Step 2: Open a New File in IDLE:
File Menu->New File
Step 3: Then Write Our Script:
print("Welcome to Python Classes")
print("Welcome to Leela Soft Tech.")
Step 4: Then Save The File:
Save the file with .py extension
Step 5: Then Run That File:
In Menu Bar of a File, Click on Run Menu ->Run Module(F5).
Step 6: Output:
Then the output will be displayed on another window.
Way3: Run a Python File from a Windows CMD:
Basic Introduction about Command Prompt:
Open CMD:
✓ Win (key) + R ->Run Prompt
✓ Then type 'cmd' and press enter.
Enter into a local drive or disc from CMD:
Syntax:
C:\>driverleter: (and press enter)
Example:
C:\Users\madhu>E: (enter a drive letter present in your and press enter)
E:\>
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Change Directory (CD):
1.Enter into a directory or folder:
Syntax:
C:\>cd <folder_name>
Example:
Ex: C:\>cd py_examples
2.Exit from inner directory to outer directory:
Syntax:
C:\>cd.. (two dots)
Example:
E:\>py_example>cd..
E:\>
Choose one text editor (Editplus)
Step-1:
Open EditPlus:
Click on Editplus Short Cut or Open from Start Menu.
Select Python File:
File Menu ->New ->Others ->Python ->OK
Write Python Script:
print("Welcome to Python Classes")
print("Welcome to Leela Soft Tech.")
Save The File:
Save the file with '.py' extension in specified folder location.
Step-2:
Open CMD: WinKey+R ->type 'cmd' ->Press Enter
Step-3:
Go to our saved python file Location in cmd:
Step-4:
Then type the following command to run our python file:
Syntax:
py <file_name>.py (press enter)
(or)
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
python <file_name>.py (press enter)
Example:
E:\6pm>py test.py (press enter)
E:\6pm>python test.py (press enter)
Identifiers:
Every name in Python is called as an Identifier. That name may be class name, method name,
function or variable name.
Rules define an Identifiers in Python
✓ Identifiers are the names given to the fundamental building blocks in a program.
✓ These can be variables, class, object, functions, lists, dictionaries etc.
✓ There are certain rules defined for naming i.e., Identifiers.
• Allowed characters are a-z, A-Z, 0-9, ( _ ).
• Keywords (reserved words) should not be used as an identifier name.
• Python is case sensitive.
• First character of an identifier can be character, underscore ( _ ) but not digit.
• White spaces are not allowed.
Ex:1 Valid Identifiers
stdid, stdname
sub1, sub2
cust_id, cust_name, _empId
Ex:2
1name #not allowed
2id #not allowed
id1 #allowed
n1a #allowed
Ex:3 Keywords
if #not allowed
If #allowed
Ex:4 White Space
emp id #not allowed
emp_id #allowed
Ex:5 Case sensitive
empName
empname #allowed but both are different
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Literals:
It is a constant value assigned to a variable. It may be Integers, Floats, Strings, etc.,
Ex:
emp_id = 101 #integer literal
empName = "Scott" #string literal
empSalary = 2000.00 #float literal
Variables:
✓ A variable is the name given to a memory location. It is the basic unit of storage in a
program.
✓ The value stored in a variable can be changed during program execution.
✓ Variables are used to store the values, by using these values we are achieving the
project requirements.
Example:
For Employee we required:
employeeId, employeeName, employeeSalary,
For Student we required:
studentId, studentName,
In order to use a variable in a Python program we to need to perform one step, i.e, Variable
Initialization.
Syntax:
<identifier> = <value/literal>
Ex:
emp_id = 101
emp_name = "Scott"
emp_salary = 2000.00
Comments in Python:
✓ In Python, we use the hash '#' symbol to start writing a comment.
✓ It extends up to the newline character. "Python Interpreter ignores comment".
Comments are very important while writing a program. It describes what's going on inside a
program so that a person looking at the source code does not have a hard time figuring it out.
Example:
#This is a comment, Here print() function prints the value
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
print("Welcome to Python")
Multi-line comments:
If we have comments that extend multiple lines, one way of doing it is to use hash '#' in the
beginning of each line.
Example:
#This is a long comment
#
#and it extends up to multiple lines
Keywords:
✓ Keywords are the reserved words in Python. They are used to define the syntax and
structure of the Python language.
✓ We cannot use a keyword as variable name, function name or any other identifier.
✓ In Python, keywords are case sensitive.
There are 35 keywords in Python up to 3.7
True, False, None,
Operator Related:
and, or, not, is, in
Control Flow Statements:
if, else, elif
for, while, break, continue,
pass
Function Related:
def, return, lambda, global, nonlocal, yield
Class Related:
class, import, from, as
Exception Handling Related:
try, except, finally, raise, assert
For delete Object:
del
Resource Type (File closing, db connection close, etc,.):
with
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
New Keywords Introduced in 3.7 Version:
async, await
Observations:
1. Only alphabet symbols
2. Except first 3 remaining all are lowercase
Show the keywords in python from python interpreter or IDLE:
>>>import keyword
>>>keyword.kwlist
By using help() function:
>>> help()
help> keywords
Python Statement:
Instructions that a Python interpreter can execute are called statements.
For example, a = 1 is an assignment statement.
The if statement, for statement, while statement etc. are other kinds of statements in
Python.
Multi-line statement:
In Python, end of a statement is marked by a newline character. But we can make a statement
extend over multiple lines with the line continuation character (\).
Example:
a = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9
In Python, line continuation is implied inside parentheses (), brackets [] and braces {} also.
Example:
a = (1 + 2 + 3 +
4 + 5 + 6 +
7 + 8 + 9)
Here, the surrounding parentheses () do the line continuation implicitly.
Example for []:
colors = ['red',
'blue',
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
'green']
We could also put multiple statements in a single line using semicolons (;).
Example:
a = 1; b = 2; c = 3
a, b, c = 10, 20, 30
Built-in Functions:
The Python interpreter has a number of functions and types built into it that are always
available.
print()
input()
eval()
id()
type()
help()
hex()
bin()
oct()
format()
str()
ord()
chr()
list()
tuple()
range()
set()
frozenset()
dict()
sum()
len()
pow()
bool()
int()
float()
complex()
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
min()
max()
dir()
enumerate()
open()
filter()
zip()
globals()
map()
round()
Input And Output Statements:
print() function:
Print objects to the text stream file or console, separated by 'sep' and followed by 'end'.
Syntax of print() function:
print(value,.., sep=' ', end='\n', file=sys.stdout, flush=False)
Here, objects are the value(s) to be printed.
✓ The 'sep' separator is used between the values. If we don't use 'sep' it defaults into a
space character.
✓ After all values are printed, 'end' is printed. If we don't use 'end' defaults into a new line
character.
✓ The 'file' is the object where the values are printed and its default value is sys.stdout
(screen or console).
>>>print(1,2,3,4)
1 2 3 4
>>>print(1,2,3,4,sep='*')
1*2*3*4
>>>print(1,2,3,4,sep='#',end='&')
1#2#3#4&
Reading dynamic input from the keyboard:
In Python 2 the following 2 functions are available to read dynamic input from the keyboard.
1. raw_input()
2. input()
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
1. raw_input():
This function always reads the data from the keyboard in the form of String Format. We have to
convert that string type to our required type by using the corresponding type casting methods.
Ex:
x=raw_input("Enter First Number:")
print(type(x)) It will always print str type only for any input type
2. input():
input() function can be used to read data directly in our required format. We are not required
to perform type casting.
x=input("Enter Value)
type(x)
input([prompt]) function:
✓ If the prompt argument is present, it is written to standard output without a trailing
newline.
✓ The function then reads a line from input, converts it to a string (stripping a trailing
newline), and returns that.
✓ To convert this into a number we can use int() or float() functions and so on.
Example:
a = input("Enter a Number :")
b = input("Enter a Number :")
print("Value of 'a' is :",a)
print("Value of 'b' is :",b)
help([object]):
✓ Invoke the built-in help system.
✓ If no argument is given, the interactive help system starts on the interpreter console.
✓ If the argument is a string, then the string is looked up as the name of a module,
function, class, method, keyword, or documentation topic, and a help page is printed on
the console.
✓ If the argument is any other kind of object, a help page on the object is generated.
>>> help(complex)
Help on class complex in module builtins:
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
>>> help()
Welcome to Python 3.7's help utility!
help>
type(object):
With one argument, return the type of an object.
>>>a=10
>>> type(a)
<class 'int'>
>>> sal =2500.00
>>> type(sal)
<class 'float'>
id(object):
Return the "identity" of an object. This is an integer which is guaranteed to be unique and
constant for this object during its lifetime.
>>> a=10
>>> id(a)
1790458256
chr(i):
Return the string representing a character whose Unicode code point is the integer i.
>>> chr(65)
'A'
>>> chr(97)
'a'
>>> chr(48)
'0'
ord(c):
Given a string representing one Unicode character, return an integer representing the Unicode
code point of that character.
>>> ord('a')
97
>>> ord('€')
8364
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Python Indentation:
Most of the programming languages like C, C++, Java use braces { } to define a block of
code. Python uses indentation.
A code block (body of a function, loop etc.) starts with indentation and ends with the first un-
indented line. The amount of indentation is up to us, but it must be consistent throughout that
block.
Generally, four whitespaces are used for indentation and is preferred over tabs.
Example:
for i in range(1, 11):
print(i)
if i == 5:
break
Example:
>>>print(1000)
1000
>>> print(1000) (Here Starting two spaces are there)
IndentationError: unexpected indent
Indentation can be ignored in line continuation. But it is recommended to follow indent. It
makes the code more readable.
Example:1
if True:
print('Hello')
a = 5
Example:2 (line continuation)
if True:print('Hello'); a = 5
Both Example1, Example2 are valid and do the same thing. But the former style is clearer.
Note: Incorrect indentation will get an exception i.e., IndentationError.
Escape Characters in Python:
Escape characters are characters that are generally used to perform certain tasks and their
usage in code directs the compiler to take a suitable action mapped to that character.
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Escape
Description Example Output
Sequence
\\ Prints Backslash print("\\") \
\` Prints single-quote print("\'") '
\" Prints double quote print("\"") "
ASCII bell makes ringing the bell alert
\a print("\a") Beep sound
sounds.
ASCII backspace removes previous
\b print("ab" + "\b" + "c") ac
character
hello
\f ASCII formfeed ( FF ) print("hello\fworld")
world
hello
\n ASCII linefeed ( LF ) print("hello\nworld")
world
Prints a character from the Unicode
\N{name} print(u"\N{DAGGER}") †
database
ASCII carriage return (CR). Moves all
characters after ( CR ) the the beginning
\r print("123456\rXX_XX") XX_XX6
of the line while overriding same
number of characters moved.
\t ASCII horizontal tab (TAB). Prints TAB print("\t* hello") * hello
\v ASCII vertical tab (VT). N/A N/A
\uxxxx Prints 16-bit hex value Unicode character print(u"\u041b") Л
\Uxxxxxxxx Prints 32-bit hex value Unicode character print(u"\U000001a9") Ʃ
\ooo Prints character based on its octal value print("\043") #
\xhh Prints character based on its hex value print("\x23") #
Example 1
>>> # this example writes a string "ABC" using hex
>>> "\x41\x42\x43"
'ABC'
Example 2
>>> # this time using octal
>>> "\101\102\103"
'ABC'
Raw String to ignore escape sequence
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Sometimes we may wish to ignore the escape sequences inside a string. To do this we can place
r or R in front of the string. This will imply that it is a raw string and any escape sequence inside
it will be ignored.
Using repr()
This function returns a string in its printable format, i.e. doesn’t resolve the escape sequences.
Example:
ch = "I\nLove\tPython"
print (ch)
print (repr(ch))
Using “r/R”
Adding “r” or “R” to the target string triggers a repr() to the string internally and stops from
the resolution of escape characters.
Example:
# initializing target string
ch = "I\nLove\tPython"
print ("The string without r / R is : ")
print (ch)
print ("\r")
# using "r" to prevent resolution
ch1 = r"I\nLove\tPython"
print ("The string after using r is : ")
print (ch1)
print ("\r")
# using "R" to prevent resolution
ch2 = R"I\nLove\tPython"
print ("The string after using R is : ")
print (ch2)
www.leelasoft.com Cell: 78 42 66 47 66