0% found this document useful (0 votes)
22 views

Unit 1

The document provides an introduction to Python programming, detailing its history, features, applications, and syntax. It covers key concepts such as identifiers, keywords, indentation, comments, variables, constants, and literals, as well as the Integrated Development Learning Environment (IDLE) for running Python scripts. Python is highlighted as a high-level, interpreted, and object-oriented language that supports multiple programming paradigms.

Uploaded by

Athreya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Unit 1

The document provides an introduction to Python programming, detailing its history, features, applications, and syntax. It covers key concepts such as identifiers, keywords, indentation, comments, variables, constants, and literals, as well as the Integrated Development Learning Environment (IDLE) for running Python scripts. Python is highlighted as a high-level, interpreted, and object-oriented language that supports multiple programming paradigms.

Uploaded by

Athreya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

UNIT1: Introduction and syntax of Programming with Python

C22616.aDisplay message on screen using Python script on IDE.

● Python is a high general-purpose interpreted, interactive, free, open source and high-level

programming language.

● It supports object-oriented programming as well as procedural oriented programming.

● Python is a popular programming language because it provides more reliability of code, clear

syntax of code, advanced language features, scalability of code portability of code.

History of Python Language:

Python was conceived in the late 1980s

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

available under the NU General public license (GPL).

In Feb 1991 Guido Van Rossum published Python 0.9.0 to ALT source. In addition to exception handling

python includes classed, list strings.

In 1994 python 1.0 was released with new features like lambda, map, and filter and reduces which

aligned it heavily in relation to fictional programming.

Python 2.0, released in 2000, introduced features like list comprehensions and a garbage

collection system capable of collecting reference cycles.

Python 3.0, released in 2008, was a major revision of the language that is not completely backward-

compatible, in python 3.0 print statement is replaced with print () function.


UNIT1: Introduction and syntax of Programming with Python

Python was available for almost all operating systems such as windows, Mac,Linux/Unix etc.

Applications of Python:

Python is used in many application domains.

● Web and internet development

● Scientific and Numeric

● 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:

• Python 2.7.X (broader support, legacy libraries)

• Python 3.6.X (newer features, better future support)

Python execution model


UNIT1: Introduction and syntax of Programming with Python

Interpreter has two phases:

1. Source code is compiled into byte code

2.Byte code is executed on the Python Virtual Machine

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.

3. Free and Open Source:


Python language is freely available at official website The source-code is also available. Therefore it is
open source. The source-code is also available. Therefore it is open source. Since, it is open-source, this
means that source code is also available to the public. So you can download it as, use it as well as share
it.

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.

5. GUI Programming Support:


Graphical Users interfaces can be made using a module such as PyQt5, PyQt4. PyQt5 is the most popular
option for creating graphical apps with Python.
UNIT1: Introduction and syntax of Programming with Python

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.

8. Platform Independent and Portable language:


Python language is also a portable language. For example, if we have python code for windows and if we
want to run this code on other platform such as Linux, Unix and Mac then we do not need to change it,
we can run this code on any platform.

9. Integrated language:
Python is also an Integrated language because we can easily integrated python with other language like c,
c++ etc.

10. Large standard Library


Python has a large standard library which provides rich set of module and functions ,So the user does not
write own code for every single thing. There are many libraries present in python for, such as regular
expressions, unit-testing, web browsers etc.
11. Dynamically Typed Language:
Python is dynamic-typed language. That means the type (for example- int, double, long etc.) for a
variable is decided at run time, not in advance. Because of this feature we don’t need to specify the type
of variable. For example, x=10 here x can be anything such as String, int etc.

Characteristics of Python

Following are important characteristics of Python Programming:


● It supports functional and structured programming methods as well as OOP.
● It can be used as a scripting language or can be compiled to byte-code for building large
applications.
UNIT1: Introduction and syntax of Programming with 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.

Python building blocks


Python language building blocks are identifiers keywords variables their types and commenting

section etc. This basic contains are used and applied in almost every program. In this section we will see

and discuss this Python building blocks.

 Python identifiers
An identifier is a name given to entities like class, functions, variables, etc. It helps to differentiate one
entity from another.

Rules for writing identifiers


1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0
to 9) or an underscore _.
a. Names like myClass, var_1 and print_this_to_screen, all are valid example.
2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine.
3. Keywords cannot be used as identifiers.
4. We cannot use special symbols like !, @, #, $, % etc. in our identifiers.
5. An identifier can be of any length.
6. Python is a case-sensitive language. This means, num and Num are not the same.
7. Always name identifiers that make sense.
8. While, c = 10 is valid. Writing count = 10 would make more sense and it would be easier to figure
out what it does even when you look at your code after a long gap.
9. Multiple words can be separated using an underscore, this_is_a_long_variable.

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

False class finally is return

None continue for lambda try

True def from nonlocal while

and del global not with

as elif if or yield

assert else import pass

break except in raise

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.

Single Line comment

In Python, we use the hash (#) symbol to start writing a comment.

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:

1. #This is a long comment


2. #and it extends
3. #to multiple lines

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

Here, we have created a named x. We have assigned value 10 to the variable.

Variables are containers for storing data values.

Unlike other programming languages, Python has no command for declaring a variable.

Creating and assigning a value to a variable

A variable is created the moment you first assign a value to it.

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)

String variables can be declared either by using single or double quotes:

x = "John"
# is the same as
x = 'John'

Python allows you to assign values to multiple variables in one line:

x, y, z = "Orange", "Banana", "Cherry"


print(x)
print(y)
print(z)

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.

Assigning value to a constant in Python

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

Example 3: Declaring and assigning value to a constant

Create a constant.py

PI=3.14

GRAVITY=9.8

Rules and Naming Convention for Variables and constants


Variables
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
Rules for Python variables and constants :

● Constant and variable names should have a combination of letters in lowercase (a to z) or


uppercase (A to Z) or digits (0 to 9) or an underscore (_).
● A variable name cannot start with a number.
● If you want to create a variable name having two words, use underscore to separate them. For
example: emp_id
● A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
● Variable names are case-sensitive (age, Age and AGE are three different variables)
● Never use special symbols like !, @, #, $, %, etc.

 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

In the above syntax,

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

strings = "This is Python"


char = "C"
multiline_str = " " "This is a multiline string with more than one line code." " "

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.

fruits = ["apple", "mango", "orange"] #list


numbers = (1, 2, 3) #tuple
UNIT1: Introduction and syntax of Programming with Python

alphabets = {'a':'apple', 'b':'ball', 'c':'cat'} #dictionary


vowels = {'a', 'e', 'i' , 'o', 'u'} #set

Integrated Development Learning Environment (IDLE):


Is a graphical user interface which is completely written in Python?
It is bundled with the default implementation of the python language and also comes with optional part
of the Python packaging.

Features of IDLE:
Multi-window text editor with syntax highlighting.

 Running Python script


There are two modes through which we can create and run Python scripts:
1. Interactive mode and
2. script mode.

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:

Pros and Cons of Script Mode


The following are the advantages of running your code in script mode:

1. It is easy to run large pieces of code.


2. Editing your script is easier in script mode.
3. Good for both beginners and experts.

The following are the disadvantages of using the script mode:

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

Key Differences Between Interactive and Script Mode


Here are the key differences between programming in interactive mode and programming in script mode:

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.

Following are the standard or built-in data type of python:


● Numeric
● Sequence Type
● Boolean
● Set
● Dictionary
UNIT1: Introduction and syntax of Programming with Python

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

. • Equivalent to arrays in other languages.

• Lists have no fixed size and can be expanded or contracted as needed.

• Items in list can be retrieved using the index.

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

Consider the following example.


1. l = [1, "hi", "python", 2]
2. print (l[3:]);
3. print (l[0:2]);
4. print (l);
5. print (l + l);
6. print (l * 3);
Output:
[2]
[1, 'hi']
[1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2, 1, 'hi', 'python', 2]

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)

>>>Print(x) # print x in range 1 to 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)

#this will get all the values.

Example 2

20 in myset

#this will return true if the value is in the set.

Example 3

#to add a value in a set

myset.add('edureka')

Example 4

#to add multiple values in a list

myset.update([ 10, 20, 30, 40, 50])

Example 5

#to remove an item from a set

myset.remove('edureka')

#we can use the discard or pop method to remove an item from a set as well.

Example 6

myset = {10, 20, 30}


UNIT1: Introduction and syntax of Programming with Python

myset1 = {10,30,50}

myset.issubset(myset1)

#this will return false

myset.union(myset1)

#this will return a set with the union of the two sets.

DECLERATION AND USE OF DATA TYPES IN PYTHON

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

>>>

Conversion between data types

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

Conversion to and from string must contain compatible values.


UNIT1: Introduction and syntax of Programming with Python

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'

We can even convert one sequence to another.

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

To convert to dictionary, each element must be a pair

1. >>> dict([[1,2],[3,4]])
2. {1: 2, 3: 4}
3. >>> dict([(3,26),(4,44)])
4. {3: 26, 4: 44}

Input and Output in Python programming

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

Syntax var_name=input () #without any argument


Syntax var_name=input (‘string) #with argument
# Taking input from the user
name = input("Enter your name: ")

# Output
print ("Hello, " + name)
UNIT1: Introduction and syntax of Programming with Python

Enter your name: vaishali


Hello, vaishali

You might also like