You are on page 1of 14

PROGRAMMING WITH PYTHON

CH 1 : INTRODUCTION AND SYNTAX OF PYTHON PROGRAM


INTRODUCTION

Python is a popular programming language.


It was created by Guido van Rossum, and released in 1991.
It is used for:

 web development (server-side),


 software development,
 mathematics,
 system scripting.

What can Python do?


 Python can be used on a server to create web applications.
 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping, or for production-ready software development.

Why Python?
 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
 Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
 Python can be treated in a procedural way, an object-oriented way or a functional way.

FEATURES OF PYTHON

1 Simple

Python is a simple and minimalistic language. This pseudo-code nature of Python is


one of its greatest strengths.

2 Easy to Learn

As you will see, Python is extremely easy to get started with. Python has an
extraordinarily simple syntax.

3 Free and Open Source

Python is an example of a FLOSS (Free/Libré and Open Source Software). In simple


terms, you can freely distribute copies of this software, read it's source code, make
changes to it, use pieces of it in new free programs, and that you know you can do these
things.

4 High-level Language

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.

5 Portable

Due to its open-source nature, Python has been ported (i.e. changed to make it work on) to
many platforms. All your Python programs can work on any of these platforms without
requiring any changes at all if you are careful enough to avoid any system-dependent
features.You can use Python on Linux, Windows, VxWorks, PlayStation and even PocketPC
!

6 Interpreted

Python does not need compilation to binary. You just run the program directly from the
source code. Internally, Python converts the source code into an intermediate form called
bytecodes and then translates this into the native language of your computer and then
runs it. This also makes your Python programs much more portable, since you can just
copy your Python program onto another computer and it just works!

7 Object Oriented

Python supports procedure-oriented programming as well as object-oriented programming.


In procedure- oriented languages, the program is built around procedures or functions
which are nothing but reusable pieces of programs. In object-oriented languages, the
program is built around objects which combine data and functionality. Python has a very
powerful but simplistic way of doing OOP, especially when compared to big languages like
C++ or Java.

8 Extensible

If you need a critical piece of code to run very fast or want to have some piece of
algorithm not to be open, you can code that part of your program in C or C++ and then use
them from your Python program.

9 Embeddable

You can embed Python within your C/C++ programs to give 'scripting' capabilities for your
program's users.

10 Extensive Libraries

The Python Standard Library is huge indeed. It can help you do various things involving
regular expressions, documentation generation, unit testing, threading, databases, web
browsers, CGI, ftp, , XML, XML-RPC, HTML, WAV files, cryptography, GUI (graphical user
interfaces), Tk, and other system-dependent stuff. Remember, all this is always available
wherever Python is installed. This is called the 'Batteries Included' philosophy of Python.

Python Syntax compared to other programming languages


 Python was designed for readability, and has some similarities to the English language with
influence from mathematics.
 Python uses new lines to complete a command, as opposed to other programming languages
which often use semicolons or parentheses.
 Python relies on indentation, using whitespace, to define scope; such as the scope of loops,
functions and classes. Other programming languages often use curly-brackets for this purpose.

INTERNAL WORKING OF PYTHON


The Python interpreter initializes its runtime engine called PVM which is the Python virtual machine. The
interpreter loads the machine language with the library modules and inputs it into the PVM. This converts
the byte code into executable code such as 0s and 1s (binary). And then it prints the results.

Character set

A character set is a set of valid characters acceptable by a programming language in scripting. In this
case, we are talking about the Python programming language. So, the Python character set is a valid set
of characters recognized by the Python language. These are the characters we can use during writing a
script in Python. Python supports all ASCII / Unicode characters that include:
 Alphabets: All capital (A-Z) and small (a-z) alphabets.
 Digits: All digits 0-9.
 Special Symbols: Python supports all kind of special symbols like, ” ‘ l ; : ! ~ @ # $ % ^ ` & * ( ) _ + –
={}[]\.
 White Spaces: White spaces like tab space, blank space, newline, and carriage return.
 Other: All ASCII and UNICODE characters are supported by Python that constitutes the Python
character set.

Tokens

A token is the smallest individual unit in a python program. All statements and instructions in a program
are built with tokens. The various tokens in python are :

1. Keywords: Keywords are words that have some special meaning or significance in a programming
language. They can’t be used as variable names, function names, or any other random purpose. They
are used for their special features. In Python we have 33 keywords some of them are: try, False, True,
class, break, continue, and, as, assert, while, for, in, raise, except, or, not, if, elif, print, import, etc.
Example

# for loop
for x in range(1, 9):

# Print the value of x


print(x)

# Check if the value of x is less than 6


# Here if the value of x is less than 6
# then the loop will continue
# Here, if, continue, else, break,
# for loop are keywords
if x < 6:
continue

# If i greater than 6 then break loop


else:
break
2. Identifiers: Identifiers are the names given to any variable, function, class, list, methods, etc. for their
identification. Python is a case-sensitive language and it has some rules and regulations to name an
identifier. Here are some rules to name an identifier:-
 As stated above, Python is case-sensitive. So case matters in naming identifiers. And
hence python and Python are two different identifiers.
 Identifier starts with a capital letter (A-Z) , a small letter (a-z) or an underscore( _ ). It can’t start with
any other character.
 Except for letters and underscore, digits can also be a part of identifier but can’t be the first character
of it.
 Any other special characters or whitespaces are strictly prohibited in an identifier.
 An identifier can’t be a keyword
Keywords on python are
And, as pass, print, import, class, continue,elif, return, none, false, while …etc
For Example: Circle_Area, emp_salary .

Python Variable

Variable is containers which store values. Python is not “statically typed”. We do not need to
declare variables before using them or declare their type. A variable is created the moment we
first assign a value to it. A Python variable is a name given to a memory location. It is the basic
unit of storage in a program.

example

Var = "Muchhala polytechnic"


print(Var)
o/p : Muchhala polytechnic.
x = 5
y = "John"
print(x)
print(y)
o/p : 5 john

Types of Literals in Python

Python literals are of several types, and their usage is also pretty varied. So let’s check them out
one by one.

There are five types of literal in Python, which are as follows-

 String Literals
 Numeric Literals
 Boolean Literals
 Literal Collections
 Special Literals

What is String literals


A string literal can be created by writing a text (a group of Characters ) surrounded by a single(”),
double(“”), or triple quotes. By using triple quotes we can write multi-line strings or display them in the
desired way.
Example: Here Muchhala is a string literal that is assigned to a variable(s).
string literals
# in single quote
s = ' Muchhalapolytechnicclg'
# in double quotes
t = " Muchhalapolytechnicclg"
# multi-line String
m = '''muchhala
polytecnic
clg'''

print(s)
print(t)
print(m)
o/p:
Muchhalapolytechnicclg
Muchhalapolytechnicclg

muchhala
polytecnic
clg
What is Character literal
It is also a type of string literal where a single character is surrounded by single or double quotes.
character literal in single quote
s = 'd'

# character literal in double quotes


b = "a"

print(v)
print(w)
o/p
d
a

What is Numeric literal


They are immutable and there are three types of numeric literal:
1. Integer
2. Float python
3. Complex.
Integer:
Both positive and negative numbers including 0. There should not be any fractional part.
Example:
We assigned integer literals (0b10100, 50, 0o320, 0x12b) into different variables. Here, ‘a‘ is a binary literal, ‘b’ is a decimal
literal, ‘c‘ is an octal literal, and ‘d‘ is a hexadecimal literal. But on using the print function to display a value or to get the output
they were converted into decimal.
integer literal

# Binary Literals
a = 0b10100

# Decimal Literal
b = 50

# Octal Literal
c = 0o320

# Hexadecimal Literal
d = 0x12b
print(a, b, c, d)
20 50 208 299
Float
These are real numbers having both integer and fractional parts .
# Float Literal
e = 3.14
f = 0.5
print(e, f)
0/p 3.14
0.5

Complex
The numerals will be in the form of a + bj, where ‘a‘ is the real part and ‘b‘ is the complex part.
Example:
z = 7 + 5j
# real part is 0 here.
k = 7j
print(z, k)
o/p (7+5j) 7j

What is Boolean literal


There are only two Boolean literals in Python. They are true and false. In Python, True represents the value
as 1 and False represents the value as 0.
Example 1:
In this example ‘a‘ is True and ‘b‘ is False because 1 is equal to True.
a = (1 == True)
b = (1 == False)
c = True + 3
d = False + 7

print("a is", a)
print("b is", b)
print("c:", c)
print("d:", d)
o/p
a is True
b is False
c: 4
d: 7

What is List literal

The list contains items of different data types. The values stored in List are separated by a comma (,) and
enclosed within square brackets([]). We can store different types of data in a List. Lists are mutable .
List literals
number = [1, 2, 3, 4, 5]
name = ['Amit', 'sumit', 'romit', 2]
print(number)
print(name)
o/p:
[1, 2, 3, 4, 5]
['Amit', 'kabir', 'bhaskar', 2]

What is Tuple literal


A tuple is a collection of different data-type. It is enclosed by the parentheses ‘()‘ and each element is
separated by the comma(,). It is immutable . Ordered, unchangeable, heterogeneous & contains duplicate

# Tuple literals
even_number = (2, 4, 6, 8)
odd_number = (1, 3, 5, 7)
print(even_number)
print(odd_number)
o/p: (2, 4, 6, 8)
(1, 3, 5, 7)
What is Dictionary literal
Dictionary stores the data in the key-value pair. It is enclosed by curly braces ‘{}‘ and each pair is
separated by the commas(,). We can store different types of data in a dictionary. Dictionaries are
mutable.
{'a': 'apple', 'b': 'ball', 'c': 'cat'}
{'name': 'amit', 'age': 20, 'ID': 20}

What is Set literal


Set is the collection of the unordered data set. It is enclosed by the {} and each element is separated by
the comma(,).
Example: We can create a set of vowels and fruits.
# Set literals
vowels = {'a', 'e', 'i', 'o', 'u'}
fruits = {"apple", "banana", "cherry"}

print(vowels)
print(fruits)

o/p
{'a', 'e', 'i', 'o', 'u'}
{"apple", "banana", "cherry"}
What is Special literal
Python contains one special literal (None). ‘None’ is used to define a null variable. If ‘None’ is compared with
anything else other than a ‘None’, it will return false.
# Special literals
water_remain = None
print(water_remain)
o/p: none

Python Data Types

 Numeric data types: int, float, complex.


 String data types: str.
 Sequence types: list, tuple, range.
 Binary types: bytes, bytearray, memoryview.
 Mapping data type: dict.
 Boolean type: bool.
 Set data types: set, frozenset. Python Numeric Data Type. Python numeric data type is used to hold numeric values like;


Numeric
In Python, numeric data type represent the data which has numeric value. Numeric value can be integer, floating
number or even complex numbers. These values are defined as int, float and complex class in Python.
 Integers – This value is represented by int class. It contains positive or negative whole numbers (without
fraction or decimal). In Python there is no limit to how long an integer value can be.
 Float – This value is represented by float class. It is a real number with floating point representation. It is
specified by a decimal point. Optionally, the character e or E followed by a positive or negative integer may be
appended to specify scientific notation.
 Complex Numbers – Complex number is represented by complex class. It is specified as (real part) +
(imaginary part)j. For example – 2+3j
Note – type() function is used to determine the type of data type.
Python program to
# demonstrate numeric value
a = 5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))
o/p
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>
Sequence Type
In Python, sequence is the ordered collection of similar or different data types. Sequences allows to store
multiple values in an organized and efficient fashion. There are several sequence types in Python –
 String
 List
 Tuple
1) String
In Python, Strings are arrays of bytes representing Unicode characters. A string is a collection of one or
more characters put in a single quote, double-quote or triple quote. In python there is no character data
type, a character is a string of length one. It is represented by str class.

Creating String
Strings in Python can be created using single quotes or double quotes or even triple quotes.
Python Program for
# Creation of String
# with single Quotes
String1 = 'Welcome to the python World'
print("String with the use of Single Quotes: ")
print(String1)

# Creating a String
# with double Quotes
String1 = "it’s easy"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))

# Creating a String
# with triple Quotes
String1 = '''first program"hello"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))

# Creating String with triple


# Quotes allows multiple lines
String1 = '''study
For
marks'''
print("\nCreating a multiline String: ")
print(String1)
String with the use of Single Quotes:
Welcome to the python World
String with the use of Double Quotes:
It’s easy
<class 'str'>

String with the use of Triple Quotes:


'first program"hello"'

<class 'str'>
Creating a multiline String:

study
For
Marks
2) List
Lists are just like the arrays, declared in other languages which is a ordered collection of data. It is very flexible as
the items in a list do not need to be of the same type.

Creating List
Lists in Python can be created by just placing the sequence inside the square brackets []
Python program to demonstrate
# Creation of List

# Creating a List
List = []
print("Initial blank List: ")
print(List)

# Creating a List with


# the use of a String
List = ['snehaldeshmukh']
print("\nList with the use of String: ")
print(List)

# Creating a List with


# the use of multiple values
List = ["python", "For", "program"]
print("\nList containing multiple values: ")
print(List[0])
print(List[2])

# Creating a Multi-Dimensional List


# (By Nesting a list inside a List)
List = [['python', 'For'], ['program']]
print("\nMulti-Dimensional List: ")
print(List)

o/p
initial blank List:
[]
List with the use of String:
['snehaldeshmukh']
List containing multiple values:
python
program
Multi-Dimensional List:
[['python', 'For'], ['program']]
3) Tuple
Just like list, tuple is also an ordered collection of Python objects. The only difference between tuple and list is that
tuples are immutable i.e. tuples cannot be modified after it is created. It is represented by tuple class.

Creating Tuple
In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or without the use of
parentheses for grouping of the data sequence. Tuples can contain any number of elements and of any datatype
(like strings, integers, list, etc.).
Note: Tuples can also be created with a single element, but it is a bit tricky. Having one element in the
parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple .
Creating a Tuple with
# the use of Strings
Tuple1 = ('snehal', 'deshmukh')
print("\nTuple with the use of String: ")
print(Tuple1)

# Creating a Tuple with


# the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))
o/p
Tuple with the use of String:
('snehal', 'deshmukh')
Tuple using List:
(1, 2, 4, 5, 6)

Boolean
Data type with one of the two built-in values, True or False. Boolean objects that are equal to True are
truthy (true), and those equal to False are falsy (false). But non-Boolean objects can be evaluated in
Boolean context as well and determined to be true or false. It is denoted by the class bool.
Python program to
# demonstrate boolean type

print(type(True))
print(type(False))

print(type(true))
<class 'bool'>
<class 'bool'>
Set
In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements. The
order of elements in a set is undefined though it may consist of various elements.
Creating Sets
Sets can be created by using the built-in set() function with an iterable object or a sequence by placing the
sequence inside curly braces, separated by ‘comma’. Type of elements in a set need not be the same, various
mixed-up data type values can also be passed to the set.
Creating a Set with
# a mixed type of values
# (Having numbers and strings)
set1 = set([1, 2, 'python', 4, 'For', 6, 'python'])
print("\nSet with the use of Mixed Values")
print(set1)
{1, 2, 4, 6, 'Geeks', 'For'}

Dictionary
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike
other Data Types that hold only single value as an element, Dictionary holds key:value pair. Key-value is provided in
the dictionary to make it more optimized. Each key-value pair in a Dictionary is separated by a colon :, whereas
each key is separated by a ‘comma’.
Creating Dictionary
In Python, a Dictionary can be created by placing a sequence of elements within curly {} braces, separated by
‘comma’. Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and
must be immutable. Dictionary can also be created by the built-in function dict(). An empty dictionary can be
created by just placing it to curly braces{}.
Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'snehal', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
o/p : Dictionary with the use of Mixed Keys:

{1: [1, 2, 3, 4], 'Name': 'sd'}

Question & Answers

1 Name different modes of python./ difference betn interactive & script mode
Python is a programming language that lets you work quickly and integrate systems more efficiently. It is a widely-
used general-purpose, high-level programming language. It was designed with an emphasis on code readability,
and its syntax allows programmers to express their concepts in fewer lines of code. In the Python programming
language, there are two ways in which we can run our code
1 Interactive mode
Interactive means “working simultaneously and creating impact of our work on the other’s work”.
Interactive mode is based on this ideology only. In the interactive mode as we enter a command and
press enter, the very next step we get the output. The output of the code in the interactive mode is
influenced by the last command we give. Interactive mode is very convenient for writing very short lines
of code. This mode is very suitable for beginners in programming as it helps them evaluate their code line
by line and understand the execution of code well.
Example 1:
To run python in command prompt type “python”. Then simply type the Python statement on >>> prompt. As we
type and press enter we can see the output in the very next line.
# Python program to display "Hello co6I"
print("Hello co6I")
o/p: Hello co6I

2. Script mode
In the script mode, a python program can be written in a file. This file can then be saved and executed
using the command prompt. We can view the code at any time by opening the file and editing becomes
quite easy as we can open and view the entire code as many times as we want. Script mode is very
suitable for writing long pieces of code. It is much preferred over interactive mode by experts in the
program. The file made in the script mode is by default saved in the Python installation folder and the
extension to save a python file is “.py”.
Example :
In order to execute “Hello ” using script mode we first make a file and save it.
Then use the command prompt to execute this file o/p is seen on cmd
2 Differences between list and tuple

SR.NO. LIST TUPLE

1 Lists are mutable Tuples are immutable

The implication of iterations is comparatively


2 The implication of iterations is Time-consuming Faster

The list is better for performing operations, such as insertion and Tuple data type is appropriate for accessing the
3 deletion. elements

Tuple consumes less memory as compared to


4 Lists consume more memory the list

5 Lists have several built-in methods Tuple does not have many built-in methods.

6 The unexpected changes and errors are more likely to occur In tuple, it is hard to take place.

3 Explain Local and Global variable


Local variable
are those which are not defined inside any function and have a global scope whereas local variables are those which
are defined inside a function and its scope is limited to that function only. In other words, we can say that local
variables are accessible only inside the function in which it was initialized whereas the global variables are accessible
throughout the program and inside every function. Local variables are those which are initialized inside a function
and belong only to that particular function. It cannot be accessed anywhere outside the function.
Global variable
These are those which are defined outside any function and which are accessible throughout the program,
i.e., inside and outside of every function.

How to give single and multiline comment in python.


single-line comment
Hash character(#) is used to comment the line in the Python program. Comments does not have to be text to explain
the code, it can also be used to prevent Python from executing code.
The hash character should be placed before the line to be commented. Consecutive single-line comments can be
used as multiline comments in Python.
Example: print(“hello”) # print("Mathematics")
o/p hello

Multi-line string as a comment


Python multi-line comment is a piece of text enclosed in a delimiter (“””) on each end of the comment. Again there
should be no white space between delimiters (“””).
They are useful when the comment text does not fit into one line; therefore needs to span across lines. Multi-line
comments or paragraphs serve as documentation for others reading your code.
4 List Data types used in python. Explain any two with example
Ans is page no 8 #same notes
5 Explain building blocks of python
Ans tokens on page no 4.
6 Describe internal working of python
Ans page 3 explain with dig
7 Explain dictionary data types in detail
Ans page 11
8 Write in brief about any 5 keywords in python
Ans on page 4
8 Define the terms
Identifier
Tuple
List
9 explain with diagram internal working of python.
10 what are variables explain with example

You might also like