You are on page 1of 45

102044504 - Programming with Python

UNIT - 1
Introduction to Python
and
Language Fundamentals

1
OUTLINE – UNIT 1
• Basics of Language • Basics of Python
• Python Introduction • print()
• What is Python? • inut()
• Why Python? • Identifiers
• Advantages of Python • Keyword
• Python Characteristics • Lines & indentation
• Python Features
• Python Applications • ELEMENTS of PYTHON
• Types in Python
• Type Conversion
• Operators
2
• Comments
Python - Introduction
WHAT IS PYTHON?
• Python is a very popular general-purpose interpreted, interactive,
object-oriented, and high-level programming language.
• Python is dynamically-typed and garbage-collected programming
language.
• It was created by Guido van Rossum during 1985- 1990.
• Like Perl, Python source code is also available under the GNU General
Public License (GPL).

3
Basics of Language
WHAT IS PYTHON?

• Low-level versus high-level refers to whether we program using instructions


and data objects at the level of the machine (e.g., move 64 bits of data from
this location to that location) or whether we program using more abstract
operations (e.g., pop up a menu on the screen) that have been provided by
the language designer.

• General versus targeted to an application domain refers to whether the


primitive operations of the programming language are widely applicable or are
fine-tuned to a domain.

• Interpreted versus compiled refers to whether the sequence of instructions


written by the programmer, called source code, is executed directly (by an
interpreter) or whether it is first converted (by a compiler) into a sequence of
machine-level primitive operations.

4
Python - Introduction
WHY PYTHON?
• Python is Open Source which means its available free of cost.
• Python is simple and so easy to learn
• Python is versatile and can be used to create many different things.
• Python has powerful development libraries include AI, ML etc.
• Python is much in demand for Industries.

5
Python - Introduction
Advantages of PYTHON
• Python is Interpreted − Python is processed at runtime by the interpreter. You
do not need to compile your program before executing it. This is similar to
PERL and PHP.
• Python is Interactive − You can actually sit at a Python prompt and interact
with the interpreter directly to write your programs.
• Python is Object-Oriented − Python supports Object-Oriented style or
technique of programming that encapsulates code within objects.
• Python is a Beginner's Language − Python is a great language for the
beginner-level programmers and supports the development of a wide range
of applications from simple text processing to WWW browsers to games.

6
Python - Introduction
PYTHON Characteristics:
• 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.
• 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.

7
Python - Introduction
PYTHON Features:
• Easy-to-learn − Python has few keywords, simple structure, and a clearly
defined syntax. This allows the student to pick up the language quickly.
• Easy-to-read − Python code is more clearly defined and visible to the eyes.
• Easy-to-maintain − Python's source code is fairly easy-to-maintain.
• A broad standard library − Python's bulk of the library is very portable and
cross-platform compatible on UNIX, Windows, and Macintosh.
• Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
• Portable − Python can run on a wide variety of hardware platforms and has
the same interface on all platforms.

8
Python - Introduction
PYTHON Features:
• Extendable − You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more
efficient.
• Databases − Python provides interfaces to all major commercial databases.
• GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows
MFC, Macintosh, and the X Window system of Unix.
• Scalable − Python provides a better structure and support for large programs
than shell scripting.

9
Python - Introduction
PYTHON Applications:

10
Python - Basics

11
Python – Basics (how to works)

Run
with some input

Write/Edit
OK?
NO
YES

YES
NO More
Inputs?
12
Python - Basics
PYTHON - print() function
To print as an output on console
Syntax:
print(“---”)
print(‘---’)

Example:
print(“welcome to python”)
a=5
print(a)
print(“a:”,a)

13
Python - Basics

PYTHON IMPORTANT POINTS:


• Python program communicates its results to user using print

• Most useful programs require information from users

– Name and age for a travel reservation system

• Python 3 uses input to read user input as a string (str)

14
Python - Basics
Python – input() function
To take input from User
• Take as argument a string to print as a prompt
• Returns the user typed value as a string
– details of how to process user string later

• Example:

a = input(“enter name”)

print(a)

15
Python - Basics
Python – Identifiers

• A Python identifier is a name used to identify a variable, function,


class, module or other object.
• 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.

16
Python - Basics
Python – Identifiers

• For use in program


• Python Class names start with an uppercase letter. All other identifiers
start with a lowercase letter.
• Starting an identifier with a single leading underscore indicates that
the identifier is private identifier.
• Starting an identifier with two leading underscores indicates a
strongly private identifier.
• If the identifier also ends with two trailing underscores, the identifier is
a language-defined special name.

17
Python - Basics
Python – Keywords / Reserve Words

18
Python - Basics
Python – Lines & Indentation
• Python programming provides no braces to indicate blocks of code for
class and function definitions or flow control.
• Blocks of code are denoted by line indentation, which is rigidly enforced.

CORRECT IN-Correct

if True: if True:
print ("True") print ("True")
else: else:
print ("False") print ("False")

19
ELEMENTS of PYTHON

20
ELEMENTS of PYTHON
• Python program, sometimes called a script,
• is a sequence of definitions and commands.

• A command, often called a statement, instructs the interpreter


to do something.

• Commands manipulate objects


• Each object is associated with a Type
• Type:
• A set of values
• A set of operations on these values
• Expressions: An operation (combination of objects and
operators)

21
Types &
Type Conversion
in Python

22
Types in Python
Text Type: str x = "Hello World"

Numeric Types: int, float, complex x = 20


x = 20.5
x = 1j
Sequence Types: list, tuple, range x = ["apple", "banana"]
x = ("apple", "banana“)
x = range(6)
Mapping Type: dict x = {"name" : "John", "age" : 36}

Set Types: set, frozenset x = {"apple", "banana"}


x = frozenset({"apple“,”banana”}
Boolean Type: bool x = True

Binary Types: bytes, bytearray, x = b"Hello“


memoryview x = bytearray(4)

None Type: NoneType x = None


23
Types in Python
• Scalar
– Indivisible objects that do not have internal structure
– int (signed integers), float (floating point), bool
(Boolean), NoneType
• NoneType is a special type with a single value
• The value is called None
• Non-Scalar
– Objects having internal structure
– str (strings)

24
Types Conversion
• Conversion of value of one type to other

• We are used to int ↔ float conversion in Math

– Integer 3 is treated as float 3.0 when a real number is


expected

– Float 3.6 is truncated as 3, or rounded off as 4 for integer


contexts

• Type names are used as type converter functions

25
Types Conversion

Note that float to int conversion


is truncation, not rounding off

26
Types Conversion

27
Operators

28
Operators
• Arithmetic + - * // / % **
• Comparison == != > < >= <=
• Assignment = += -= *= //= /= %= **=
• Logical and or not
• Bitwise & | ^ ~ >> <<
• Membership in not in
• Identity is is not

29
Operators - Arithmetic
Operator Name Example
+ Addition 10 + 20 = 30

- Subtraction 20 – 10 = 10

* Multiplication 10 * 20 = 200

/ Division 20 / 10 = 2

% Modulus 22 % 10 = 2

** Exponent 4**2 = 16

// Floor Division 9//2 = 4

30
Operators - Comparison
Operator Name Example

== Equal 4 == 5 is not true.

!= Not Equal 4 != 5 is true.

> Greater Than 4 > 5 is not true.

< Less Than 4 < 5 is true.

>= Greater than or Equal to 4 >= 5 is not true.

<= Less than or Equal to 4 <= 5 is true.

31
Operators - Assignment
Operator Name Example
= Assignment Operator a = 10
+= Addition Assignment a += 5 (Same as a = a + 5)

-= Subtraction Assignment a -= 5 (Same as a = a - 5)

*= Multiplication Assignment a *= 5 (Same as a = a * 5)

/= Division Assignment a /= 5 (Same as a = a / 5)

%= Remainder Assignment a %= 5 (Same as a = a % 5)

**= Exponent Assignment a **= 2 (Same as a = a ** 2)

//= Floor Division Assignment a //= 3 (Same as a = a // 3)

32
Operators - Logical
Operator Description Example

and Logical If both the operands are (a and b) is true.


AND true then condition
becomes true.

or Logical OR If any of the two operands (a or b) is true.


are non-zero then
condition becomes true.

not Logical Used to reverse the logical Not(a and b) is false.


NOT state of its operand.

33
Operators - Bitwise
Operator Name Example
& Binary AND Sets each bit to 1 if both bits are 1

| Binary OR Sets each bit to 1 if one of two bits is 1

^ Binary XOR Sets each bit to 1 if only one of two bits is 1

~ Binary Ones Inverts all the bits


Complement

<< Binary Left Shift left by pushing zeros in from the right and let the
leftmost bits fall off
Shift

>> Binary Right Shift right by pushing copies of the leftmost bit in from
the left, and let the rightmost bits fall off
Shift

34
Operators - Membership
Python’s membership operators test for membership in a
sequence, such as strings, lists, or tuples.

Operato Description Example


r
in Evaluates to true if it finds a
variable in the specified
x in y, here in results in a 1 if x is
sequence and false
a member of sequence y.
otherwise.

not in Evaluates to true if it does x not in y, here not in results in a


not finds a variable in the 1 if x is not a member of
specified sequence and false sequence y.
otherwise.

35
Operators - Identity
Identity operators compare the memory locations of two objects.

Operator Description Example

is Evaluates to true if the


variables on either side of the
operator point to the same x is y, here is results in 1 if id(x)
object and false otherwise. equals id(y).

is not Evaluates to false if the


variables on either side of the
operator point to the same x is not y, here is not results in 1 if
object and true otherwise. id(x) is not equal to id(y).

36
Control Statement

37
Control Statement
In Python, there are three forms of the if...else statement.

• if statement
• if...else statement
• if...elif...else statement
• Nested if…..else statement

38
Control Statement - example

39
Control Statement – example
short hand if.. - if..else..

40
Control Statement - example
“Not” with if….
The not keyword is a
logical operator, and is
used to reverse the result
of the conditional
statement:

The pass Statement


if statements cannot be
empty, but if you for
some reason have an if
statement with no
content, put in the pass
statement to avoid
getting an error.
41
Looping

42
Looping
The while Loop
With the while loop we can execute a set of statements as long as a
condition is true.

43
Looping
The for Loop
It has the ability to iterate over the items of any sequence, such as a list or a
string.

44
Looping
Python break Statement
The break statement is used
to terminate the loop
immediately when it is
encountered.

Python continue Statement


The continue statement is used to
skip the current iteration of the
loop and the control flow of the
program goes to the next
iteration.

45

You might also like