Unit 1
Unit 1
● Python is a high general-purpose interpreted, interactive, free, open source and high-level
programming language.
● Python is a popular programming language because it provides more reliability of code, clear
ABC programming language is said to be the predecessor of python language which was capable of
exception handling and interfacing with the amoeba operating System, like pearl python source code is
In Feb 1991 Guido Van Rossum published Python 0.9.0 to ALT source. In addition to exception handling
In 1994 python 1.0 was released with new features like lambda, map, and filter and reduces which
Python 2.0, released in 2000, introduced features like list comprehensions and a garbage
Python 3.0, released in 2008, was a major revision of the language that is not completely backward-
Python was available for almost all operating systems such as windows, Mac,Linux/Unix etc.
Applications of Python:
● Education
● Desktop GUIs
● Software Development
● Business Applications
Features of python
1. Interpreted
Python is an interpreted language i.e. interpreter executes the code line by line at a time.
Python is processed at runtime. The source code of python is converted into an immediate form
called bytecode.
● User need not to compile their program before execution. This makes debugging easy and thus
suitable for beginners. Two major versions of interpreter are currently available:
Byte code is regenerated every time source code OR the python version on the machine
changes. Byte code generation saves repeated compilation time.
2.Easy to code:
Python is high level programming language. Python is very easy to learn as compared to other
language like c, c#, java script, java etc. It is very easy to code in python language. It is also developer-
friendly language. Python gained its popularity just because of less usage of keywords, simple structure
and clearly defined syntax.
4. Object-Oriented Language:
One of the key features of python is Object-Oriented programming. Python supports object oriented
language and concepts of classes, objects encapsulation etc.
6. High-Level Language:
Python is a high-level language. When we write programs in python, we do not need to remember the
system architecture, nor do we need to manage the memory.
7. Extensible feature:
Python is a Extensible language. We can write some python code into c or c++ language and also we
can compile that code in c/c++ language.
9. Integrated language:
Python is also an Integrated language because we can easily integrated python with other language like c,
c++ etc.
Characteristics of Python
● It provides very high-level dynamic data types and supports dynamic type checking.
● It supports automatic garbage collection.
● It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
section etc. This basic contains are used and applied in almost every program. In this section we will see
Python identifiers
An identifier is a name given to entities like class, functions, variables, etc. It helps to differentiate one
entity from another.
Python Keywords
Keywords are the reserved words in Python.
UNIT1: Introduction and syntax of Programming with Python
We cannot use a keyword as a variable name, function name or any other identifier. They are used to
define the syntax and structure of the Python language.
In Python, keywords are case sensitive. For example – Python keyword “while” is used for while loop
There are 33 keywords in Python 3.7. This number can vary slightly in the course of time.
All the keywords except True, False and None are in lowercase and they must be written as it is. The list
of all the keywords is given below.
as elif if or yield
Keywords in Python
Indentation
Indentation refers to the spaces at the beginning of a code line. the indentation in Python is very
important. Python uses indentation to indicate a block of code.
Where in other programming languages the indentation in code is for readability only, Most of the
programming languages like C, C++, Java use braces { } to define a block of code. In Python, we use
space/tab as indentation to indicate the same to the compiler..
A code block (body of a function, loop etc.) starts with indentation and ends with the first unintended
line. Python indentation is a way of telling a Python interpreter that the group of statements belongs to a
particular block of code
UNIT1: Introduction and syntax of Programming with Python
Generally, four white spaces are used for indentation and is preferred over tabs. Here is an example.
for i in range(1,11):
print(i)
if i == 5:
break
The enforcement of indentation in Python makes the code look neat and clean. This results into Python
programs that look similar and consistent.
Indentation can be ignored in line continuation. But it's a good idea to always indent. It makes the code
more readable. For example:
If True:
print(“hello”)
a=5;
and
if True:print(“hello”);a=5
Both are valid and do the same thing. But the former style is clearer. Incorrect indentation will result
into Indentation Error.
Comments
Comments are very important while writing a program. It describes what's going on inside a
program so that a person looking at the source code does not have a hard time figuring it out.
It extends up to the newline character. Comments are for programmers, for better understanding of a
program. Python Interpreter ignores the comment.
1. #This is a comment
2. #print out Hello
3. print('Hello')
Multi-line comments
UNIT1: Introduction and syntax of Programming with Python
If we have comments that extend multiple lines, one way of doing it is to use hash (#) in the beginning of
each line. For example:
Another way of doing this is to use triple quotes, either ''' or """.
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Creating Variables
A variable is a named location used to store data in the memory. It is helpful to think of variables as a
container that holds data which can be changed later throughout programming. For example, x=10
Unlike other programming languages, Python has no command for declaring a variable.
x=5
y = "John"
print(x)
print(y)
Python is a type inferred language; it can automatically know John is a string and declare variable y as a
string.
UNIT1: Introduction and syntax of Programming with Python
Variables do not need to be declared with any particular type and can even change type after they have
been set.
x = 4 # x is of type int
x = "python" # x is now of type string
print(x)
x = "John"
# is the same as
x = 'John'
And you can assign the same value to multiple variables in one line:
x = y = z = "Orange"
print(x)
print(y)
print(z)
Constants
A constant is a type of variable whose value cannot be changed. It is helpful to think of constants as
containers that hold information which cannot be changed later.
Non technically, you can think of constant as a bag to store some books and those books cannot be
replaced once placed inside the bag.
In Python, constants are usually declared and assigned on a module. Here, the module means a new file
containing variables, functions etc which is imported to main file. Inside the module, constants are
written in all capital letters and underscores separating the words.
UNIT1: Introduction and syntax of Programming with Python
Create a constant.py
PI=3.14
GRAVITY=9.8
Literals
Literal is a raw data given in a variable or constant. In Python, there are various types of literals
they are as follows:
Numeric Literals
Numeric Literals are immutable (unchangeable). Numeric literals can belong to 3 different
numerical types Integer, Float, and Complex.
UNIT1: Introduction and syntax of Programming with Python
● We assigned integer literals into different variables. Here, a is binary literal, b is a decimal literal, c is an
octal literal and d is a hexadecimal literal.
● When we print the variables, all the literals are converted into decimal values.
● 10.5 and 1.5e2 are floating-point literals. 1.5e2 is expressed with exponential and is equivalent to 1.5 *
102.
String literals
A string literal is a sequence of characters surrounded by quotes. We can use both single, double
or triple quotes for a string. And, a character literal is a single character surrounded by single or double
quotes.
In the above syntax , This is Python is a string literal and C is a character literal. The value with triple-
quote """ assigned in the multiline_str is multi-line string literal.
Boolean literals
A Boolean literal can have any of the two values: True or False.
x = (1 == True)
y = (1 == False)
a = True + 4
b = False + 10
In the above program, we use boolean literal True and False. In Python, True represents the value
as 1 and False as 0. The value of x is True because 1 is equal to True. And, the value
of y is False because 1 is not equal to False.
Literal Collections
There are four different literal collections List literals, Tuple literals, Dict literals, and Set literals.
Features of IDLE:
Multi-window text editor with syntax highlighting.
The interactive mode involves running your codes directly on the Python shell which can be
accessed from the terminal of the operating system.
In the script mode, you have to create a file, give it a name with a .py the extension then runs your
code. The interactive mode is suitable when running a few lines of code.
The script mode is recommended when you need to create large applications.
Interactive Mode
● Interactive mode is used for very quickly and conventional running single line or block of
code .
● Here are example using the python shell that come with the basic python installation
● The >>> indicates that the shell is ready to accept interactive commands for example if we
want to print the statement interactive mode simply type the appropriate code and hit enter.
UNIT1: Introduction and syntax of Programming with Python
The following are the advantages of running your code in interactive mode:
1. Helpful when your script is extremely short and you want immediate results.
2. Faster as you only have to type a command and then press the enter key to get the results.
3. Good for beginners who need to understand Python basics.
The following are the disadvantages of running your code in the interactive mode:
1. Editing the code in interactive mode is hard as you have to move back to the previous commands
or else you have to rewrite the whole command again.
2. It's very tedious to run long pieces of code.
Script Mode
If you need to write a long piece of Python code or your Python script spans multiple files, interactive
mode is not recommended. Script mode is the way to go in such cases.
In script mode, You write your code in a text file then save it with a .py extension which stands for
"Python".
Note that you can use any text editor for this.
If you are in the standard Python shell, you can click "File" then choose "New" or simply hit "Ctrl + N"
on your keyboard to open a blank script in which you can write your code. You can then press "Ctrl + S"
to save it.
After writing your code, you can run it by clicking "Run" then "Run Module" or simply press F5.
Let us create a new file from the Python shell and give it the name "first.py". We need to run the "Hello
World" program. Add the following code to the file:
UNIT1: Introduction and syntax of Programming with Python
Click "Run" then choose "Run Module". This will run the program:
1. Can be tedious when you need to run only a single or a few lines of cod.
2. You must create and save a file before executing your code.
UNIT1: Introduction and syntax of Programming with Python
1. In script mode, a file must be created and saved before executing the code to get results. In
interactive mode, the result is returned immediately after pressing the enter key.
2. In script mode, you are provided with a direct way of editing your code. This is not possible in
interactive mode.
Data Types
In programming, the data type is an important concept. Variables can store data of different types,
and different types can do different things. Data types are the classification or categorization of data
items. It represents the kind of value that tells what operations can be performed on a particular data.
Since everything is an object in Python programming, data types are actually classes and variables are
instance (object) of these classes.
Everything in Python is an object. You have to understand that Python represents all its data as objects.
An object’s mutability is determined by its type. Some of these objects like lists and dictionaries
are mutable, meaning you can change their content without changing their identity. Other objects like
integers, floats, strings and tuples are objects that cannot be changed.
Python provides various standard data types that define the storage method on each of them. The data
types defined in Python are given below.
1. Numbers
2. String
3. List
4. Tuple
5. Dictionary
Numbers
Number stores numeric values. Python creates Number objects when a number is assigned to a variable.
For example;
1. a = 3, b = 5 #a and b are number objects
Python supports 4 types of numeric data.
1. int (signed integers like 10, 2, 29, etc.)
2. long (long integers used for a higher range of values like 908090800L, -0x1929292L, etc.)
3. float (float is used to store floating point numbers like 1.9, 9.902, 15.2, etc.)
4. complex (complex numbers like 2.14j, 2.0 + 2.3j, etc.)
UNIT1: Introduction and syntax of Programming with Python
Python allows us to use a lower-case L to be used with long integers. However, we must always use an
upper-case L to avoid confusion.
A complex number contains an ordered pair, i.e., x + iy where x and y denote the real and imaginary
parts respectively).
String
The string can be defined as the sequence of characters represented in the quotation marks. In python, we
can use single, double, or triple quotes to define a string.
String handling in python is a straightforward task since there are various inbuilt functions and operators
provided.
In the case of string handling, the operator + is used to concatenate two strings as the operation "hello"+"
python" returns "hello python".
The operator * is known as repetition operator as the operation "Python " *2 returns "Python Python ".
The following example illustrates the string handling in python.
1. str1 = 'hello javatpoint' #string str1
2. str2 = ' how are you' #string str2
3. print (str1[0:2]) #printing first two character using slice operator
4. print (str1[4]) #printing 4th character of the string
5. print (str1*2) #printing the string twice
6. print (str1 + str2) #printing the concatenation of str1 and str2
Output:
he
o
hello javatpointhello javatpoint
hello javatpoint how are you
List
• List is a more general sequence object that allows the individual items to be of different types
• Lists can be nested just like arrays, i.e., you can have a list of lists.
UNIT1: Introduction and syntax of Programming with Python
The items stored in the list are separated with a comma (,) and enclosed within square brackets [].
use slice [:] operators to access the data of the list. The concatenation operator (+) and repetition operator
(*) works with the list in the same way as they were working with the strings.
Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the items of
different data types. The items of the tuple are separated with a comma (,) and enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.
Let's see a simple example of the tuple.
1. t = ("hi", "python", 2)
2. print (t[1:]);
3. print (t[0:1]);
4. print (t);
5. print (t + t);
6. print (t * 3);
7. print (type(t))
8. t[2] = "hi";
Output:
('python', 2)
('hi',)
('hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2, 'hi', 'python', 2)
UNIT1: Introduction and syntax of Programming with Python
<type 'tuple'>
Traceback (most recent call last):
File "main.py", line 8, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment
Dictionary
Dictionary is an ordered set of a key-value pair of items. It is like an associative array or a hash table
where each key stores a specific value. Key can hold any primitive data type whereas value is an arbitrary
Python object.A dictionary is unordered and changeable. We use the keys to access the items from a
dictionary.
To declare a dictionary The items in the dictionary are separated with the comma and enclosed in the
curly braces {}.
Consider the following example.
d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'};
print("1st name is "+d[1]);
print("2nd name is "+ d[4]);
print (d);
print (d.keys());
print (d.values());
Output:
1st name is Jimmy
2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
[1, 2, 3, 4]
['Jimmy', 'Alex', 'john', 'mike']
Range
Range is a data type which is mainly used when we are using a loop. Lets take an example to understand
this.
>>>for x in range(10)
A set is a collection which is unordered, it does not have any indexes as well. To declare a set in python
we use the curly brackets.
UNIT1: Introduction and syntax of Programming with Python
Myset={10,20,30,40}
A set does not have any duplicate values, even though it will not show any errors while declaring the set,
the output will only have the distinct values.
To access the values in a set we can either loop through the set, or use a membership operator to find a
particular value.
Example1
for x in myset:
print(x)
Example 2
20 in myset
Example 3
myset.add('edureka')
Example 4
Example 5
myset.remove('edureka')
#we can use the discard or pop method to remove an item from a set as well.
Example 6
myset1 = {10,30,50}
myset.issubset(myset1)
myset.union(myset1)
#this will return a set with the union of the two sets.
Declaration of variables is not required in Python. If there is need of a variable, you think of a name and
start using it as a variable.
Another remarkable aspect of Python: Not only the value of a variable may change during program
execution but the type as well. You can assign an integer value to a variable, use it as an integer for a
while and then assign a string to the variable.
In the following line of code, we assign the value 42 to a variable: i=42
The equal "=" sign in the assignment shouldn't be seen as "is equal to". It should be "read" or interpreted
as "is set to", meaning in our example "the variable i is set to 42". Now we will increase the value of this
variable by 1:
>>>print(i)
43
>>>
We can convert between different data types by using different type conversion functions like int(),
float(), str() etc.
1. >>> float(5)
2. 5.0
Conversion from float to int will truncate the value (make it closer to zero).
1. >>> int(10.6)
2. 10
3. >>> int(-10.6)
4. -10
1. >>> float('2.5')
2. 2.5
3. >>> str(25)
4. '25'
5. >>> int('1p')
6. Traceback (most recent call last):
7. File "<string>", line 301, in runcode
8. File "<interactive input>", line 1, in <module>
9. ValueError: invalid literal for int() with base 10: '1p'
1. >>> set([1,2,3])
2. {1, 2, 3}
3. >>> tuple({5,6,7})
4. (5, 6, 7)
5. >>> list('hello')
6. ['h', 'e', 'l', 'l', 'o']
1. >>> dict([[1,2],[3,4]])
2. {1: 2, 3: 4}
3. >>> dict([(3,26),(4,44)])
4. {3: 26, 4: 44}
● Input means data entered by the user of the program. In python, the input function is
used to accept an input from a user the raw Input () function available for input on
older version.
# Output
print ("Hello, " + name)
UNIT1: Introduction and syntax of Programming with Python