[Go to site: main page, start]

0% found this document useful (0 votes)
11 views28 pages

Introduction to Python Programming

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views28 pages

Introduction to Python Programming

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Jyoti Chandnani-7066603136

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.

Scripting and Programming languages:


Scripting Language:
1. Scripting languages based applications are run by interpreter.
2. Scripting languages based applications are not required explicit compilation.
3. We can run these scripting language based language directly.
4. Examples of scripting languages are Shell Script, Python, Perl, Ruby, Power Shell.. these all languages are
run by interpreter, that’s why these all languages are called scripting 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

Features of Python Language:


1. Python is simple, easy and powerful language.
a. The syntax of python is very simple and easy to remember, so anybody can easily remember the Python
syntaxes without having any programming basics.
b. That’s why Python is also called programmer-friendly language.
c. Python has few keywords, simple structure, and a clearly defined syntax. This allows the student to pick
up the language quickly.
2. Python is an Expressive language.
a. Python language is more expressive. The sense of expressive is the code is easily understandable.
3. Python is Free, Open and Redistribution Language.
a. Python is an example of FLOSS (Free/Libre and Open Source Software).
b. FLOSS is a community, which itself is based on the concept of sharing knowledge. FLOSS are free for
usage, modification and redistribution.
Examples of FLOSS are [Link]
2. Ubuntu
3. LibreOffice
4. Mozilla Firefox
5. Mono
6. Apache Web Server and 7. VLC Player
4. Python is an Interpretable language.
a. Python is an interpreted language i.e. interpreter executes the python code line by line at a time. So we
don’t need to compile our program before executing it. This makes debugging easy and thus suitable for
beginners.
5. Python is an extensible language.
a. Python can completely integrate with components of Java and .Net and also can invoke libraries of C and
C++. So here Python performs CROSS language operations
b. If we need a critical piece of code to run very fast, you can code that part of your program in C or C++
and then use them from our Python program.
6. Python is very rich in Libraries./ its completness
a. The Python is very rich in libraries. They help us to do various things involving regular expressions,
documentation generation, unit testing, threading, databases, web browsers, CGI(Common Gateway
Interface ), ftp(File Transfer Protocol), email, XML, WAV files, cryptography, GUI(graphical user interfaces)
using Tk(ToolKit), and also other system-dependent stuff. Remember, all this is always available wherever
Python is installed.
b. This is called the "batteries included" philosophy of Python.
7. Python is Oriented Programming language:
a. Python supports procedure-oriented programming as well as object-oriented programming. In
procedure-oriented languages.

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.

Some other features of Python language


1. Interactive language
2. Beginners language
3. Easy-to- learn
4. Easy-to-work
5. Easy-to maintain
6. Supports all major commercial databases
7. supports GUI applications
8. Scalable
9. Supports multiple databases
10. Supports indentation

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

What can we do by using Python?


By using Python we can develop,
1. GUI Applications.
2. Data Analytics Applications.
3. Gaming Applications.
4. Scientific Applications.
5. Task Automations.
6. Network Applications.
7. Animation Applications.
8. Test Cases Applications, and so on..
Simply Python can be used to make games, do data analysis, control robot, hardware, create GUIs or even
to create websites.
Advantages and Disadvantages of Python:
Advantages:
• Open source – Free and can edit source code
• Dynamically typed – No need to specify the type of variable before/after using it.
• Interpreted language – Opposite to compiled language.
• Objected oriented language
• Indentation – Whitespaces, No need of braces.
• Scripting language
• Easy to learn like normal English.
• Developed using ‘C’ language.
• Interface to Other programming languages. – Can include code from C, Java, .Net using
Cython, Jython and IronPython interfaces respectively.
• Platform independent – Works on multi platforms.
• Less code compared to other languages.
• No strict typing on variables and containers.
• Used by Lot many MNCs and worlds top most organizations like Google, NASA, MST and
Gaming apps etc
• Huge library.
• Multi-Threading and Multi processing.
Disadvantages:
• Slow compared to other programming languages like C,C++ or javaThreading not fully
implemented.
• All strings are not Unicode by default (Fixed in 3.0)
• Indentation – If mix tabs and spaces.
• Not using for mobile applications

Some Other Points about Python:


1. Python is a general-purpose language.
2. It has wide range of applications from Web development (like: Django and Bottle), scientific and
mathematical computing (Orange, SymPy, NumPy) to desktop graphical user Interfaces (Pygame, Panda3D).
3. The syntax of the language is clean and length of the code is relatively short. It's fun to work in Python
because it allows you to think about the problem rather than focusing on the syntax.

5
Python Jyoti Chandnani-7066603136

Why should we learn Python?


There are four reasons to learn Python,
1. Very Simple Syntax
Python programming is very fun, it is very easy to understand and write the python code. The syntax feels
very natural.
Eg:
a=10
b=20
sum=a+b
print(sum)
so here if you even don’t have any programming knowledge before, we can easily guess that this program
is adding two numbers and print result.
2. Not overly strict
You don't need to define the type of a variable in Python. Also, it's not necessary to add semicolon at the
end of the [Link] enforces you to follow good practices (like proper indentation). These small
things can make learning much easier for beginners.
3. Expressiveness of the language
Python allows you to write programs having greater functionality with fewer lines of code. If we write 1000
lines of code by using any programming language, the same functionality can be achieved in Python with
just 20% to 30% code of that programming language. This is just an example. You will be amazed how much
you can do with Python once you learn the basics.
4. Great Community and support
Python has a large supporting community. These are numerous active forums online which can be handy if
you are stuck. Some of them are:
a. Learn Python Subreddit
b. Google Forum for Python
c. Python Questions – stack overflow

6
Python Jyoti Chandnani-7066603136

How Python's Datatypes Compare to Other Languages


Statically typed language: A language in which types are fixed at compile time. Most statically typed
languages enforce this by requiring you to declare all variables with their data types before using them.
Java and C are statically typed languages.

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.

Understanding Print()- to print or display output in python


The print() function prints the given object to the standard output device (screen) or to the text stream
[Link] doesn't return any value;
For example, enter the following into the interactive shell next to the
>>> prompt:
>>> print('Hello, Python Jyoti!')
After we type that line and press enter, the interactive shell should display this in response:
>>> print('Hello, Python Jyoti!')
Hello, Python Jyoti
>>> print(‘Hello Jyoti’) → string enclosed in Single quotes is also valid in python

Python multiple print statements without printing on the next line.


>>>print ("value",10,20,30,end=" ")
>>>print ("value",10,20,30)
Output:
value 10 20 30 value 10 20 30

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?

Try in Script Mode


a=5
print("a =", a, sep='00000', end='\n\n\n')
print("a =", a, sep='0', end='')

Writing into the file using print


sourceFile = open('[Link]', 'w')
print('Pretty cool, huh!', file = sourceFile)
[Link]()

Python Application or program development


Python is considered an interpreted language because Python programs are executed by an
interpreter. There are two ways to use the interpreter:
1. Interactive mode
2. Script mode.

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.

Python Character Set


Character set is the set of valid characters that a language can recognize. A character represents any letter,
digit or any other symbol. Python has the following character sets:
· Letters – A to Z, a to z
· Digits – 0 to 9
· Special Symbols - + - * / etc.
· Whitespaces – Blank Space, tab, carriage return, newline, form feed
· Other characters – Python can process all ASCII and Unicode characters as part of data or literals.

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:

‘John’, “Tom”, ‘Class 12’, “200453A”, ‘12345’

Note: String literals are a sequence of characters surrounded by quotes: single, double or triple.

Python allows us to have 2 string types:


· Single-line string
String created by enclosing text in single quotes, a double quotes are normally single-line string, i.e., they
must be terminated in one line.
E.g. A variable a=’John’.

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”

(b) By typing the text in triple quotation marks.


e.g. a=”””class
XI”””
B=’’’class
XII’’’
Size of String
Python determines the size of a string as the count of characters in the string.
1. e.g. sizeof “abc”=3
But, if our string literals have an escape sequence contained within it, then make sure to count the escape
sequence as one character.
2. e.g. ‘\\’ size is 1 (escape sequence)
3. “\ab” size is 2
4. “Seema\’s pen” size is 11
For multi-line string with triple quote, while calculating the size, the EOL(End Of Line), the character at the
end is also counted.
5. a=””” X
y
z ””” has size 5.

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.

· long (long integer)


long integers or longs are integers of unlimited size, written like integers and followed by an upper or
lowercase ‘l’.

· float (floating point real values)


float represents real numbers and are written with decimal point, dividing the integer and fractional parts.
· complex (complex number) Are in the form of a + bj;
e.g-1
x=2 + 0j
print [Link]
print [Link]
O/P:
2.0
0.0
e.g-2
x=7 + 8j
print [Link], “ “,[Link]
O/P : 7.0 8.0

Python allows 3 types of integer literals:


(a) Decimal Integer Literal: An integer literal consisting of sequence of digits taken to be a decimal integer
literal unless it begins with 0 (zero).
(b) Octal Integer Literal: A sequence of digits starting with 0 is taken as octal integer literal.
e.g. Decimal 8 is 010.
(c) Hexadecimal Integer Literal: A sequence of digits preceded by OX or ox is taken to be hexadecimal
integer literal.
(d) Floating Point Literal: A number with a fractional part or decimal point consists of sign (+,-), sequence of
decimal digits with a dot such as
0.0609, 15.0609
These numbers can also be used to represent a number in engineering and scientific notation
6.09 * 10-2 , 1.50609 * 101

Note: Exponent form – A real literal in exponent form consists of 2 parts:


mantissa and exponent. E.g. 6.09 E0(-2) is exponent form of 0.0609.

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

Some of the basic functions


Python supports so many functions. Some of those are, print(), type(), id()
Print(): This function displays the output on the screen.
Type(): this function checks the data type of specific variable.
Id(): this functions finds address of variable.

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!

A comment may be on the same line after a statement or expression:


name = "Parlapalli" # declaring variable name
You can comment multiple lines as follows:

# 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.

Assigning Values to Variables:

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.

Assigning single value to single variable:


The operand to the left of the = operator is the name of the variable, and the operand to the right of
the = operator is the value stored in the variable.
For example:
>>> m=10
>>> print(m) ➔
>>> type(m) <class 'int'>
>>> id(m) 1624729872

>>> n=20.4
>>> print(n) ➔
>>> type(n) <class 'float'>
>>> r='Jyoti'
>>> print(r) ➔

>>> type(r) <class 'str'>


>>> k=2+5j
>>> print(k) ➔
>>> type(k) <class 'complex'>
>>> b=True
>>> print(b) ➔
>>> type(b) <class 'bool'>

Assigning multiple values to multiple variables


>>> a,b,c=10,10.5,'satya'
>>> print(a)➔
>>> type(a) <class 'int'>
>>> id(a) 1624729872
>>> print(b) ➔
>>> type(b) <class 'float'>
>>> id(b) 49688512
>>> print(c) ➔
>>> type(c) <class 'str'>

18
Python Jyoti Chandnani-7066603136

>>> id(c) 54580896


Here, number of variables must be equal to number of values.
If both are having different number of variables or values then interpreter will return error, like below
>>> a,b,c,d=1,2,3 ValueError: not enough values to unpack (expected 4, got 3)
>>> a,b,c,d=1,2,3,4,5 ValueError: too many values to unpack (expected 4)

Assigning same value to multiple variables


>>> x=y=z=10
>>> print(x) ➔
>>> type(x) <class 'int'>
>>> print(y) ➔
>>> type(y) <class 'int'>
>>> print(z) ➔
>>> type(z) <class 'int'>

Some Examples on Variables:


Eg1:
my_name = ‘Ramya’
my_age = 28 # not a lie
my_height = 74 # inches
my_weight = 75 # kgs
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'black'
print ("Let's talk about %s." % my_name)
print ("She's %d inches tall." % my_height)
print ("She's %d kgs heavy." % my_weight)
print ("Actually that's not too heavy.")
print ("She's got %s eyes and %s hair." % (my_eyes, my_hair))
print ("Her teeth are usually %s depending on the coffee." % my_teeth)
print("Hi This is %s, If I add %d, %d, and %d I get %d." % (my_name,my_age, my_height, my_weight,
my_age + my_height + my_weight))

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

average_passengers_per_car = passengers / cars_driven


print ("There are", cars, "cars available.")
print ("There are only", drivers, "drivers available.")
print ("There will be", cars_not_driven, "empty cars today.")
print ("We can transport", carpool_capacity, "people today.")
print ("We have", passengers, "to carpool today.")
print ("We need to put about", average_passengers_per_car, "in each car.")

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

First Python Program


However, Python is one of the easiest languages to learn, and creating "Hello, Python
Developer!" program is as simple as writing print("Hello, Python Developer!"). So, we are going to
write a different program.
Program to Add Two Numbers:
>>>x = 10
>>>y= 20
>>>sum = x+y
>>>print(sum)

How this program executes?


Line 1: #Add two numbers
Any line starting with # in Python programming is a comment
Line 2: x=10 → Here, x is a variable. You can store a value in a variable. Here, 3 is stored in this variable.
Line 3: y=20 ➔Similarly, 20 stored in y variable.
Line 4: sum = x+y
The variables x and y are added using + operator. The result of addition is then stored in another
variable sum.
Line 5: print(sum) → The print() function prints the output to the screen. In our case, it prints 30 on the
screen.
Reading data from Keyboard:
1. Input to the program can come in various ways, for example from a database, from another computer,
from mouse clicks and movements or from the internet.
2. Generally in most cases the input comes from the keyboard. For this purpose, Python provides the
function input().
3. The input of the user will be returned as a string without any changes.
4. If this raw input has to be transformed into another data type needed by the algorithm, we can use
either casting (type casting) functions or the eval().
Direct input from user (default data type is string)
Eg1:
>>> n=input('Enter Number: ')
Enter Number: 10
>>> print(n) ➔
>>> type(n) <class 'str'>
>>> id(n) 106802720

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

Converting type data by using casting function


>>> n=int(input('Enter Number: ')) Enter Number: 10
>>> print(n) ➔10
>>> type(n) <class 'int'>

Converting type of data by using eval functions


>>> n1=eval(input('Enter Number: ')) Enter Number: 10
>>> print(n1) ➔10
>>> type(n1) <class 'int'>

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.

What is your Name: Jyoti


What is your Location: Thane
Hello Jyoti, How are you. How is Your Thane.

22
Python Jyoti Chandnani-7066603136

Difference between python2 and python3


In Python 2 has two versions of input functions, input() and raw_input(). The input() function
treats the received data as string if it is included in quotes '' or "", otherwise the data is treated as
number.
In Python 3, raw_input() function is deprecated. Further, the received data is always
treated as string.
In Python 2
>>> x=input('Enter any value:')
'Enter any value:100 #entered data is treated as number
>>> x
100
>>> x=input('Enter any value:')
'Enter any value:'10' #eentered data is treated as string
>>> x
'10'
>>> x=raw_input("'Enter any value:")
'Enter any value:10 #entered data is treated as string even without ''
>>> x
'10'
>>> x=raw_input("'Enter any value:")

'Enter any value:'10' #entered data treated as string including ''


>>> x "'10'"
In Python 3
>>> x=input("'Enter any value:")
'Enter any value:10
>>> x
'10'

>>> x=input("'Enter any value:")


'Enter any value:'10' #entered data treated as string with or without ''
>>> x
"'10'"
>>> x=raw_input("'Enter any value:") # will result NameError
Traceback (most recent call last):
File "", line 1, in
x=raw_input("'Enter any value:")
NameError: name 'raw_input' is not defined

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

Data types In Python:


1. Data types are some of the keywords in any programming languages.
2. Data types are used to define what type of data that we are passing to the specific variable.
3. Generally variables will not store the values without having data types in other languages.
4. But in Python language, variables allow values without specifying data types also, because Python
allocates the data types dynamically at run time when python application is running.
5. In Python language, data types are decided by interpreter based on the value that is given to variable by
user.
6. Programmers should not specify the data type of variable when developing the program, if we specify
explicitly then interpreter will throw error.

Python supports two types of data types,


1. Basic data types or fundamental data types
2. Composite data types or collections data types
Basic data types or fundamental data types
Python supports different types of basic data types,
1. int
2. float
3. complex
4. bool
5. str

Int data type:


If we assign integer value to any variable then interpreter decides that variable as int type variable,
Eg:
>>> a=10;
>>> print(a)➔
>>> type(a) <class 'int'>

Float Data type


If we assign float value to any variable then interpreter decides that variable as Float Type variable.
Eg:
>>> b=10.5
>>> print(b) ➔
>>> type(b) <class 'float'>

String Data Type


If we assign string value to any variable then interpreter decides that variable as String type variable.
Eg:
>>> c='Jyoti'
>>> print(c)➔
>>> type(c) <class 'str'>

24
Python Jyoti Chandnani-7066603136

Bool Data type


If we assign either True or False to any variable then interpreter decides that variable as Bool type
variable.
Eg:
>>> d=True
>>> print(d) ➔
>>> type(d) <class 'bool'>
>>> id(d) 1625727600

Complex Data type


If we assign complex number to any variable then interpreter makes that variable as Complex type
variable.
Eg:
>>> e=3+4j
>>> print(e) ➔
>>> type(e) <class 'complex'>
>>> id(e) 47539552

Type Conversion Functions


We can convert datatype in two different ways:
1. type casting functions
2. eval function

Type casting functions


These type conversion functions are used to convert string type data into required types
1. int(): This int() function is used to convert into int data type.
Eg: Get two integers from the user and perform addition on those user values
Way-1
>>> a=input("Enter First Number: ") ➔Enter First Number: 10
>>> b=input("Enter Second Number: ") ➔ Enter Second Number: 20
>>> print (a) ➔10
>>> print (b) ➔20
>>> type(a) ➔<class 'str'>
>>> type(b) ➔<class 'str'>

>>> c=a+b #adding two str variables


>>> print(c) ➔
>>> type(c) <class 'str'>

>>> x=int(a) #converting str ‘a’ into int ‘x’


>>> y=int(b) #converting str ‘b’ into int ‘y’
>>> print(x)
>>> print(y)
>>> type(x)
>>> type(y)
>>> z=x+y #adding two int variables
>>> print(z)➔ 30
>>> type(z) <class 'int'>
25
Python Jyoti Chandnani-7066603136

Way-2 (shorter way)


>>> a=int(input("Enter First Number: ")) Enter First Number: 10
>>> b=int(input("Enter Second Number: ")) Enter Second Number: 20
>>> print(a) 10
>>> print(b) 20
>>> type(a) <class 'int'>
>>> type(b) <class 'int'>
>>> c=a+b
>>> print(c) 30
>>> type(c) <class 'int'>

Way-3 (shortest way)


>>> print("The sum is " + str(int(input("Enter First Number: ")) + int(input("Enter Second Number: "))))
>>> Enter First Number: 10
>>> Enter Second Number: 20
>>> The sum is 30

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

Way-2 (shorter way)


>>> a=float(input("Enter First Number: ")) Enter First Number: 10.5
>>> b=float(input("Enter Second Number")) Enter Second Number2.3
>>> print(a) 10.5
>>> print(b) 2.3
>>> c=a+b
>>> print(c) 12.8

26
Python Jyoti Chandnani-7066603136

Way-3 (shortest way)


>>> print(float(input("Enter First Number: ")) + float(input("Enter Second Number: ")))
>>> Enter First Number: 10.5
>>> Enter Second Number: 20.5
>>> 31.0

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.

Converting int value:


>>> a=eval(input('enter value for a: '))
enter value for a: 10
>>> print(a) 10
>>> type(a) <class 'int'>

Converting float value


>>> b=eval(input('enter value for b: '))
enter value for b: 10.6
>>> print(b) 10.6
>>> type(b) <class 'float'>

Converting string value


>>> c=eval(input("enter value for c: "))
enter value for c: 'Jyoti'
>>> print(c) Jyoti
>>> type(c) <class 'str'>

Converting complex value


>>> d=eval(input('enter value for d: '))
enter value for d: 2+5j
>>> print(d) (2+5j)
>>> type(d) <class 'complex'>

Converting bool value


>>> e=eval(input('enter value for e:'))
enter value for e:True
>>> print(e) True
>>> type(e) <class 'bool'>

28

You might also like