Introduction to Python Programming
Introduction to Python Programming
Index
1. Introduction to Python
2. Scripting and Programming languages
3. Features of Python
4. Installing Python software
5. What can we do by using Python
6. Advantages and Disadvantages of Python
7. Why should we learn Python
8. How Python's Datatypes Compare to Other Languages
9. Starting IDE
10. The Interactive shell
11. Python application or program development
12. Python Tokens
14. Help() function
15. Indentation
16. Quotations in Python
17. Multiline statement
18. Comments in Python
19. Python Variables
20. Escape Sequence
21. First Python Program
22. Reading data from keyboard
23. Data types in python
24. Type conversion functions ?`
25. Eval function
1
Python Jyoti Chandnani-7066603136
Introduction to PYTHON
Introduction:
1. Under the leadership of Andrew Stuart Tanenbaum, a group of employees developed Distributed
Operating System.
2. Group of Employees used ABC scripting language to develop Distributed Operating System.
3. ABC scripting language is very simple and easy to learn and work.
4. Guido Van Rossum is a member in that group and he likes ABC scripting language very well as it is very
simple and easy.
5. In Christmas holidays, Guido Van Rossum started developing a new language to be simpler and easy
compare to ABC scripting language and all other existing languages.
6. Finally he developed a new language.
7. He likes “Monty Python’s Flying Circus” English daily serial very well.
8. So he has taken the word ‘PYTHON’ from that serial and kept for his language.
9. So finally Guido Van Rossum developed PYTHON Scripting language at the National Research Institute for
Mathematics and Computer Science in Netherlands in 1989 and it available to the public in 1991.
10. Python is now maintained by a core development team at the institute, although Guido van Rossum still
holds a vital role in directing its progress.
11. Python 1.0 was released in January 1994.
12. Python 2.0 was released In October 2000 and Python 2.7.11 is the latest edition of Python 2.
13. Meanwhile, Python 3.0 was released in December 2008.
14. Python is a general purpose high level programming language.
15. Python is recommended as first programming language for beginners.
16. Guido Van Rossum has developed Python language by taking almost all programming features from
different languages.
17. The most of syntaxes in python have taken from C and ABC languages.
Programming Languages:
1. Programming language based applications are run by compiler.
2. Programming language based applications are required explicit compilation.
3. Programming language based applications can’t run directly without compilation.
4. Examples of Programming languages are C, C++, JAVA, .NET… these all programming languages
are run by compiler. That’s why these all languages are called Programming languages.
Note: Most of the people call Python is a scripting language because the way of developing Python
applications and executing Python applications are similar to scripting languages.
2
Python Jyoti Chandnani-7066603136
What is Python?
1. Python is a simple, powerful and high level, interactive, object oriented scripting language.
2. Python is a general purpose and portable language.
Different languages used to develop Python
1. Procedural oriented programing language……..C.
2. Object oriented programming language…………C++, JAVA.
3. Scripting language…………………………………………..Shell Script, Perl
4. Modular Programming language…………………….Modula-3
3
Python Jyoti Chandnani-7066603136
b. The program is built around procedures or functions which are nothing but reusable pieces of programs.
In object-oriented languages.
c. The program is built around objects which combine data and functionality. Python is very powerful in
way of doing object-oriented programming, especially, when compared to languages like C++ or Java.
8. Python is a Portable /cross platform Language:
a. Due to its Open source nature, Python has been ported to many flat forms.
b. All our Python programs will work on any platform without requiring any changes at all. So Python is also
called Cross Platform language.
c. We can use Python on Linux, Windows, Macintosh, Solaris, OS/2, Amiga, AROS, AS/400, BeOS, OS/390,
z/OS, Palm OS(also called Garnet OS), QNX, VMS, Psion, Acorn RISC OS, VxWorks, PlayStation, Sharp Zaurus,
Windows CE and PocketPC !
9. High-level Language:
a. When you write programs in Python, you never need to bother about the low-level details such as
managing the memory used by your program, etc.
b. The memory allocates dynamically when we run the application.
Installing Python3
Step1: Goto [Link] and download latest version of python, like below
Step2: goto downloads folder and select downloaded python and run and install
Step3: set variable path like bellow
My computer➔properties➔Advanced system settings➔environment variables ➔Under user variables,
create new variable with name PATH, like below
PATH= C:\Users\Jyoti\AppData\Local\Programs\Python\Python36-32\Scripts\;
C:\Users\Jyoti\AppData\Local\Programs\Python\Python36-32\
4
Python Jyoti Chandnani-7066603136
5
Python Jyoti Chandnani-7066603136
6
Python Jyoti Chandnani-7066603136
Dynamically typed language: A language in which types are discovered at execution time; the opposite of
statically typed. VBScript and Python are dynamically typed, because they figure out what type a variable is
when you first assign it a value.
Strongly typed language: A language in which types are always enforced. Java and Python are strongly
typed. If you have an integer, you can't treat it like a string without explicitly converting it.
Weakly typed language: A language in which types may be ignored; the opposite of strongly typed.
VBScript is weakly typed. In VBScript, you can concatenate the string '12' and the integer 3, to get the string
'123', then treat that as the integer 123, all without any explicit conversion. So Python is both dynamically
typed (because it doesn't use explicit datatype declarations) and strongly Typed (because once a variable
has a datatype, it actually matters).
Starting IDLE
While the Python interpreter is the software that runs our Python programs, the interactive development
environment (IDLE) software is where we will enter your programs, much like a word processor. Let’s start
IDLE now.
1. On Windows 7 or newer, click the Start icon in the lower-left corner of our screen, enter IDLE in the
search box, and select IDLE (Python GUI).
2. On Windows XP, click the Start button and then select Programs➔Python 3.6 ➔IDLE (Python GUI).
3. On Mac OS X, open the Finder window, click Applications, click Python 3.4, and then click the IDLE icon.
4. On Ubuntu, select Applications ➔Accessories ➔Terminal and then enter idle3. (You may also be able
to click Applications at the top of the screen, select Programming, and then click IDLE 3.)
The Interactive Shell
No matter which operating system you’re running, the IDLE window that first appears should be mostly
blank except for text that looks something like this:
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32 Type
"copyright", "credits" or "license()" for more information.
>>>
Window of idle
7
Python Jyoti Chandnani-7066603136
This window is called the interactive shell. A shell is a program that lets us type instructions into the
computer, much like the Terminal or Command Prompt on OS X and Windows, respectively. Python’s
interactive shell lets us enter instructions for the Python interpreter software to run. The computer reads
the instructions you enter and runs them immediately.
Specify how to separate the objects, if there is more than one. Default is '
sep='separator' Optional. '
ex: print("Hello", "how are you?", sep="---")
Output :
Hello---how are you?
In interactive mode, command line shell, we type Python programs and the interpreter prints the result:
>>> 10+20
30
The chevron, >>>, is the prompt, that is used by interpreter to indicate that it is ready. So that’s why when
we enter 10+20 and click enter then immediately interpreter return 30.
8
Python Jyoti Chandnani-7066603136
This interactive mode is not used to develop any business applications. It is just used to test the
features of Python.
-In script mode, we write python program in a file and use the interpreter to execute the content of
that file. The extension of this file is .py.
-Here we can write our Python program in any of the editors or IDE’s,
-Different editors used for Python program are Notepad, Notepad++, EditPlus, nano, gedit, IDL..
-Different IDE’s used for Python program are Pycharm, Eric, Eclipse, Pyscripter, Netbeans…
-This script mode is used to develop business applications.
Eg:
Open Python➔File➔New File,
Write your Python program herein the new file and save the file with an extension .py.
Like
A=10
B=5
print(A+B)
print(A+B)
save this file with [Link]
open the file [Link], click on run tab and then run module or press F5. Now we can see the output
in python shell winow.
Tokens
The smallest individual unit in a program is called Token.
In a passage of text, individual words and punctuation marks are called tokens lexical unite or lexical
elements. The smallest individual unit in a program is called token.
Python has the following tokens:
1. Keyword 2. Identifiers 3. Literals 4. Operators 5. Punctuators
9
Python Jyoti Chandnani-7066603136
Keywords:
Keyword is a word having special meaning reserved by programming language. The keywords in Python are
having some predefined functionality. These keywords may not be used as constant or variable or any
other identifier names.
If we use help(‘keywords’) then interpreter displays all list of available keywords in Python.
Or
>>> import keyword
>>> [Link]
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except',
'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return',
'try', 'while', 'with', 'yield']
Python contains totally 33 keywords. Out of 33, only True, False and None are capitalized
10
Python Jyoti Chandnani-7066603136
Identifiers:
-A Python identifier is a name used to identify a variable, function, class, module, or other
object.
Rules for name 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).
• Python does not allow punctuation characters such as @, $, and % within identifiers.
• Python is a case sensitive programming language. Thus Application and application are two different
identifiers in Python.
Any identifier starting with two leading underscores indicates a strong private identifier
1. An identifier should not start with digit but it can contain digits, like
>>> 12ab=100 SyntaxError: invalid syntax
>>> ab12=100
2. An identifier can contain underscores (single, double and also triple)
>>> _total=10
>>> to_tal=20
>>> total_=30
>>> _to_tal_=40
>>> __total='Python'
>>> total__='Jyoti'
>>> to__tal='Computer'
>>> ___total=40
>>> ___to__tal_=100
3. An identifier must not contain special characters(except underscore)
>>> @total=100 SyntaxError: invalid syntax
>>> to@tal=200 SyntaxError: can't assign to operator
>>> to$tal=200 SyntaxError: invalid syntax
>>> total%=200 NameError: name 'total' is not defined
>>> total!=10 NameError: name 'total' is not defined
>>> !total=10 SyntaxError: invalid syntax
>>> total*=10 NameError: name 'total' is not defined
>>> &to_tal=200 SyntaxError: invalid syntax
>>> *total=20 SyntaxError: starred assignment target must be in a list or tuple
4. Identifiers are case-sensitive, so Python language is a case sensitive language
>>> a=100
>>> A=200
>>> print(a)
>>> print(A)
>>> var='python'
>>> print(Var) ➔NameError: name 'Var' is not defined
5. Keywords or reserved words can’t be used as identifiers
>>> if=100 SyntaxError: invalid syntax
>>> return='Python' SyntaxError: invalid syntax
>>> def='dev' SyntaxError: invalid syntax
>>> del=200 SyntaxError: invalid syntax
Valid Identifiers : V, x1 4th (The first character must be a letter)
Invalid Identifiers :Sum-stud, Order- no (Illegal character -), _CH Error flag (Illegal Blank space)
11
Python Jyoti Chandnani-7066603136
Literals
Literals (constants) are data items that have a fixed value. Python allows several kinds of
literals:
(i) String literals (ii) Numeric literals (iii) Boolean literals (iv) Special Literal None (v) Literals Collections
String literals
In Python, String literals are sequence of characters which are enclosed in single quotes ‘ and double
quotes “.
Text enclosed in quotes form a string literal in Python. E.g. ‘a’, ‘abc’, “abc”. Following are some valid string
literals:
Note: String literals are a sequence of characters surrounded by quotes: single, double or triple.
Multi-line string
In multi-line string, text is spread across multiple lines as one single string. It can be created in 2 ways:
(a) By adding a backslash at the end of normal single quote or double quote string. In normal strings, just
add a backslash before pressing ‘enter’ to continue.
e.g. a=”class\
XI”
12
Python Jyoti Chandnani-7066603136
For multi-line string with single quote and backslash character at the end of line, while calculating the size,
backslash is not counted.
>>>a=”c\
d\
e”
Numeric literals
Numeric literals in Python can belong to any of the following 4 types:
· int (signed integer)
Often called integers. These are positive or negative numbers with no decimal point.
13
Python Jyoti Chandnani-7066603136
Boolean literals
Used to represent one of the two boolean values, that is True and False.
For example:
>>>bool_1=(6>10)
>>>print (bool_1)
False
Special literals· None
It is used to indicate something that has not been created yet or to signify the absence of values in a
situation. Python doesn’t display anything when we give a command to display the value of a variable
containing value as None.
For example:
>>>value1=20
>>>value2=None
>>>value1
Help()
This function is used to get python documentation of a specific python keywords or variables
help() takes either one or none arguments.
If we want to give one argument then it should be either python keyword or a variables.
if we specify any python keyword as anargument to the help(), then it will display python documentation of
that specified keyword.
eg1:
>>> help('if')
The "if" statement
******************
The "if" statement is used for conditional execution:
if_stmt ::= "if" expression ":" suite
( "elif" expression ":" suite )*
["else" ":" suite]
It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true
(see
section Boolean operations for the definition of true and false); then that suite is executed (and no other
part
of the "if" statement is executed or evaluated). If all expressions are false, the suite of the "else" clause, if
present, is executed.
Related help topics: TRUTHVALUE
14
Python Jyoti Chandnani-7066603136
eg2:
>>> help('return')
The "return" statement
**********************
return_stmt ::= "return" [expression_list]
"return" may only occur syntactically nested in a function definition, not within a nested class definition.
If an expression list is present, it is evaluated, else "None" is substituted.
"return" leaves the current function call with the expression list (or "None") as return value.
When "return" passes control out of a "try" statement with a "finally" clause, that "finally" clause is
executed
before really leaving the function.
In a generator function, the "return" statement indicates that the generator is done and will cause
"StopIteration" to be raised. The returned value (if any) is used as an argument to construct "StopIteration"
and becomes the "[Link]" attribute.
In an asynchronous generator function, an empty "return" statement indicates that the asynchronous
generator is done and will cause "StopAsyncIteration" to be raised. A non-empty "return" statement is
a syntax error in an asynchronous generator function.
Related help topics: FUNCTIONS
Expression:
An expression is any legal combination of symbols that represents a value.
For example: 15, a+10, a+3, b>5
Statement:
A statement is a programming statement that does something i.e., some action takes
place.
print (“Hello”) # this statement calls print function.
Note: While an expression is evaluated, a statement is executed i.e., some action takes
place.
15
Python Jyoti Chandnani-7066603136
Indentation:
1. One of the most distinctive features of Python is its use of indentation to mark blocks of code.
2. Generally we use curly braces in C, C++ and JAVA languages but in python curly braces are not
allowed to indicate black of code for class, function definition or flow control. Blocks of code are
denoted by indentation.
3. Instead of curly braces { }, indentations are used to represents a block.
Syn:
Im_a_parents:
Im_a_child:
Im_a_grand_child
Im_another_child:
Im_another_grand_child:
The number of spaces in the indentation is variable, but all statements within the block must be
indented the same amount. Both blocks in this example are fine:
if True:
print ("This condition is True")
else:
print ("This condition is False")
However, the second block in this example will generate an error because first print in the else part is
not following indentation:
if True:
print ("Hello, Python programmer")
print ("This condition is True")
else:
print ("Hello, Python programmer")
print ("This condition is False")
Quotations:
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the
same type of quote starts and ends the string.
Generally triple quotes are used to write the string across multiple lines. For example, all the following
are legal:
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
16
Python Jyoti Chandnani-7066603136
Multi-Line Statements:
Statements in Python typically end with a new line. Python does, however, allow the use of the line
continuation character (\) to denote that the line should continue. For example:
total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do not need to use the line continuation
character. For example:
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Comments:
Comments are used in programming to describe the purpose of the code. This helps you as
well as other programmers to understand the intent of the code. Comments are completely ignored
by compilers and interpreters.
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and
up to the physical line end are part of the comment, and the Python interpreter ignores them.
Python ignores comments, and we can use them to write notes or remind ourself what the
code is trying to do. Any text for the rest of the line following a hash mark (#) is part of a comment.
Sometimes, programmers will put a # in front of a line of code to temporarily remove it while
testing a program. This is called commenting out code, and it can be useful when we’re trying to figure
out why a program doesn’t work. we can remove the # later when we are ready to put the line back in.
Python also ignores the blank line after the comment. we can add as many blank lines to our
program as we want. This can make our code easier to read, like paragraphs in a book.
#!/usr/bin/python
# First comment
print "Hello, Python!"; # second comment
This will produce following result:
Hello, Python!
# Python is easy.
# Python is simple, too.
# Python is powerful, too.
# These all are comments.
17
Python Jyoti Chandnani-7066603136
Variables:
Variables are nothing but reserved memory locations to store values. This means that when you create a
variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in
the reserved memory. Therefore, by assigning different data types to variables, you can store integers,
decimals, or characters in these variables.
We use these variable names to make program code read more than like English . If we didn’t use good
names for things in our software, we would get lost when we tried to read our code again.
We can assign single value to single variable or multiple values to multiple variables at a time.
And also we can assign single value to multiple variables.
>>> n=20.4
>>> print(n) ➔
>>> type(n) <class 'float'>
>>> r='Jyoti'
>>> print(r) ➔
18
Python Jyoti Chandnani-7066603136
output:
Let's talk about Ramya.
She's 74 inches tall.
She's 75 kgs heavy.
Actually that's not too heavy.
She's got Blue eyes and black hair.
Her teeth are usually White depending on the coffee.
Hi This is Ramya, If I add 28, 74, and 75 I get 177.
Eg2:
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
19
Python Jyoti Chandnani-7066603136
output:
There are 100 cars available.
There are only 30 drivers available.
There will be 70 empty cars today.
We can transport 120.0 people today.
We have 90 to carpool today.
We need to put about 3.0 in each car.
Eg3:
print( "Mary had a little lamb.")
print ("Its fleece was white as %s." % 'snow')
print("And everywhere that Mary went.")
print( "." * 10) # what'd that do?
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
# watch that comma at the end. try removing it to see what happens
print( end1 + end2 + end3 + end4 + end5 + end6,)
print (end7 + end8 + end9 + end10 + end11 + end12)
output:
Mary had a little lamb.
Its fleece was white as snow.
And everywhere that Mary went.
..........
Cheese
Burger
Eg4:
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print ("Here are the days: ", days)
print("Here are the months: ", months)
20
Python Jyoti Chandnani-7066603136
Output:
Here are the days: Mon Tue Wed Thu Fri Sat Sun
Here are the months: Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
21
Python Jyoti Chandnani-7066603136
Eg2:
>>> b=input('Enter any float value: ')
Enter any float value: 10.6
>>> print(b) ➔
>>> type(b) <class 'str'>
Eg3:
>>> c=input('Enter any complex number: ')
Enter any complex number: 2+6j
>>> print(c) ➔
>>> type(c) <class 'str'>
Eg4:
>>> d=input('Enter either True or False: ')
Enter either True or False: True
>>> print(d) ➔
>>> type(d) <class 'str'>
Eg:
In interactive mode:
>>> name=input('What Is Your Name: ')
What Is Your Name: Jyoti
>>> loc=input("What is Your Location: ")
What is Your Location: Thane
>>> print(""" Hello """ + name +", How are You. How is your " +loc+ ".");
Hello Jyoti, How are You. How is your Thane.
In script mode:
Open file and write the following code and save the file.
name = input("What is your Name: ")
loc = input("What is your Location: ")
print('Hello ' + name +', How are you. How is Your ' +loc+'.')
If we run the file, we can see the following in the python screen.
22
Python Jyoti Chandnani-7066603136
Eg:
print('What is your age?') # ask for their age
myAge = input()
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
output:
What is your age?
28
You will be 29 in a year.
Execution Process:
23
Python Jyoti Chandnani-7066603136
24
Python Jyoti Chandnani-7066603136
2. Float(): This float() conversion function is used to convert other types into float type.
Way-1
>>> a=input("Enter First Number: ") Enter First Number: 10.5
>>> b=input("Enter Second Number") Enter Second Number20.5
>>> print (a) 10.5
>>> print(b) 20.5
>>> type(a) <class 'str'>
>>> type(b) <class 'str'>
>>> c=a+b
>>> print(c) 10.520.5
>>> type(c) <class 'str'>
>>> x=float(a)
>>> y=float(b)
>>> print(x) 10.5
>>> print(y) 20.5
>>> type(x) <class 'float'>
>>> type(y) <class 'float'>
>>> z=x+y
>>> print(z) 31.0
>>> type(z) <class 'float'>
26
Python Jyoti Chandnani-7066603136
3. Complex(): This complex() conversion function is used to convert string type data into Complex type.
Way-1
>>> a=input("Enter Number: ") Enter Number: 2+3j
>>> print(a) 2+3j
>>> type(a) <class 'str'>
>>> x=complex(a)
>>> print(x) (2+3j)
>>> type(x) <class 'complex'>
Way-2
>>> print(complex(input("Enter Number: ")))
>>> Enter Number: 4+6j
>>> (4+6j)
4. Bool(): This bool() conversion function is used to convert string type data into Boolean type.
Way-1
>>> a=input("Enter either True or False: ") Enter either True or False: True
>>> print(a) True
>>> x=bool(a)
>>> print(x) True
>>> type(x) <class 'bool'>
Way-2
>>> print(bool(input("Enter Either True or False: ")))
>>> Enter Either True or False: True
>>> True
27
Python Jyoti Chandnani-7066603136
Eval Function
This function is also used to convert the data into required type. But generally this function converts
the type of the variable based on the value.
28