Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 38

Introduction to Python

Python is a powerful high-level, interpreted, interactive and object-oriented scripting


language. Python is designed to be highly readable. It uses English keywords frequently
whereas the other languages use punctuations (like brackets, comma ).

Python is Interpreted: Python is processed at runtime by the interpreter. You do not


need to compile your program before executing it.
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.

Python was developed by Guido van Rossum in the late 80s and early 90s at the

National Research Institute for Mathematics and Computer Science in the Netherlands.
Python Features
Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax. This allows a
student to pick up the language quickly.
Easy-to-read: Python code is more clearly defined and visible to the eyes.
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 code.
Portable: Python can run on a wide variety of hardware platforms and has the same interface on all
platforms.
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.
Python Official Website :
http://www.python.org/ Getting Python
Binaries of latest version of Python 3 (Python Linux platform
3.5.1) are available on this download page Different flavors of Linux use different package managers
for installation of new packages. On Ubuntu Linux, Python 3
The following different installation options are is installed using the following command from the terminal.
available.
• Windows x86-64 embeddable zip file $sudo apt-get install python3-minimal
• Windows x86-64 executable installer
Download Gzipped source tarball from Python's
• Windows x86-64 web-based installer download URL:
https://www.python.org/ftp/python/3.5.1/Python-
3.5.1.tgz
Mac OS Extract the tarball
Download Mac OS installers from this tar xvfz Python-3.5.1.tgz
URL:https://www.python.org/downloads/m Configure and Install:
ac-osx/ cd Python-3.5.1
 Mac OS X 64-bit/32-bit installer : python- ./configure --prefix=/opt/python3.5.1
3.5.1-macosx10.6.pkg make
 Mac OS X 32-bit i386/PPC installer : sudo make install
python-3.5.1-macosx10.5.pkg
Script Mode Programming & Run
Let us write a simple Python program in a script.
Python files have the extension .py.
print (“Hello, Python!”)
On Linux
nano rasp_1.py #to create python file
Python rasp_1.py #to get output
On Windows
C:\Python34>Python test.py

This produces the following result-


Hello, Python! ( in all OS )
Python Identifiers
Identifier is the name given to entities like class, functions, variables etc. in Python. It helps differentiating
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 (_). 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 identifier.

a@ = 0
File "<interactive input>", line 1
a@ = 0
SyntaxError: invalid syntax
Quotation in Python
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.
Word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is made up of multiple lines and sentences."""
Comments in Python
A hash sign (#) that is not inside a string literal is the beginning of a comment. All
characters after the #, up to the end of the physical line, are part of the comment and the
Python interpreter ignores them.

# First comment
print ("Hello, Python!") # second comment

name = “swati shree" # This is again comment


Python Variables
• A variable is a location in memory used to store
some data (value).
• The rules for writing a variable name is same as
the rules for writing identifiers in Python.
• We don't need to declare a variable before using
it. We don't even have to declare the type of the
variable. This is handled internally according to
the type of value we assign to the variable.
Variable assignment Multiple assignments
We use the assignment operator (=) to assign In Python, multiple assignments can be made in
values to a variable. Any type of value can be a single statement as follows:
assigned to any valid variable. a, b, c = 9, 8.3, “Morning”
a = 9
b = 8.3 This assigns the “python” string to all the three
c = “Morning” variables.
x = y = z = “python”
• Here, we have three assignment statements.
5 is an integer assigned to the variable a .
• Similarly, 3.2 is a floating point number and
"Hello" is a string (sequence of characters)
assigned to the variables b and c
respectively.
#empty list
LIST
A=[]
#list of integers
B=[1,2,3]
#list with mixed datatypes
C=[1,”hello”,3.4]
S=[5,6,7,8,9,2,3]
#nested list
D=[“mouse”,[8,4,6],[‘a’]]
• print (B)

• print (C[2])
• print (D[1])
• print (S[1:4])
Python Input, Output
Some of the functions like input() and print() are widely used for standard input and
output operations respectively.

Example:
a = 5
print('The value of a is', a)
# Output: The value of a is 5

name=input(‘what is your name?’)


print(‘nice to meet you’+ name+ ‘:-)’)
# Output: what is your name? swati
# nice to meet you swati :-)
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
 Here, objects is the value(s) to be printed.
 The sep separator is used between the values. It defaults into a space character.
 After all values are printed, end is printed. It defaults into a new line.
 The file is the object where the values are printed and its default value is sys.stdout
(screen). Here are an example to illustrate this.

print(1,2,3,4) # Output: 1 2 3 4
print(1,2,3,4,sep='*') # Output: 1*2*3*4
print(1,2,3,4,sep='#',end='&') # Output: 1#2#3#4&
Output formatting in string format
Sometimes we would like to format our output to make it look attractive. This can be done by
using the str.format() method. This method is visible to any string object.
x = 5; y = 10
print('The value of x is {} and y is {}'.format(x,y))

## Output: The value of x is 5 and y is 10


Here the curly braces {} are used as placeholders. We can specify the order in which it is
printed by using numbers (tuple index).
print('I love {0} and {1}'.format(‘chicken',‘egg'))
# Output: I love chicken and egg
print('I love {1} and {0}'.format(‘chicken',‘egg'))
# Output: I love egg and chicken
Python Operators
Operators are special symbols in Python that carry out arithmetic or logical computation.
The value that the operator operates on is called the operand.
For example:
>>> 2+3
5

Type of operators in
Python

 Arithmetic operators
 Comparison (Relational) operators
 Logical (Boolean) operators
Arithmetic operators
x = 15
y = 4
print('x + y =',x+y) # Output: x + y = 19

print('x - y =',x-y) # Output: x - y = 11

print('x * y =',x*y) # Output: x * y = 60

print('x / y =',x/y) # Output: x / y = 3.75

print('x // y =',x//y) # Output: x // y = 3

print('x ** y =',x**y)
# Output: x ** y = 50625
Comparison operators
It either returns True or False according to the condition.

x = 10
y = 12
print('x > y is',x>y)
# Output: x > y is False
print('x < y is',x<y)
# Output: x < y is True
print('x == y is',x==y)
# Output: x == y is False
print('x != y is',x!=y)
# Output: x != y is True
print('x >= y is',x>=y)
# Output: x >= y is False
print('x <= y is',x<=y)
# Output: x <= y is True
Logical operators
Logical operators are the and , or , not operators.

x = True
y = False

# Output: x and y is False


print('x and y is',x and y)
# Output: x or y is True
print('x or y is',x or y)
# Output: not x is False
print('not x is',not x)
>>>a,b= [int(x) for x in input(‘enter inputs with a space:’).split()]

enter inputs with a space:1 2

>>>print(a+b)

3
Python Statement
Decision making is required when we want to execute a code only if a certain condition is satisfied.
• The if…elif…else statement is used in Python for decision making.

Python if Statement Syntax


if test expression:
statement(s)

# If the number is positive, we print an appropriate message


num = 3
if num > 0:
print(num, "is a positive number.")
Python if...else Statement Syntax

if test expression:
Body of if
else:
Body of else

# Program checks if the number is positive or


negative

num = 3
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
Python if...elif...else Syntax

if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else

# In this program,we check if the number is


positive or negative or zero and display an
appropriate message
num = 3.4
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Python Nested if statements
# check if the number is positive or negative or
zero and display an appropriate message.

num = float(input("Enter a number: ")) # to insert


any number we use float
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
Python Loop
Syntax of for Loop:
 Loop continues until we reach the last item in the sequence. The body
of for loop is separated from the rest

# Program to find the sum of all numbers stored in a list

numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11] # List of numbers


sum = 0 # variable to store the sum
for val in numbers: # iterate over the list
sum = sum+val
print("The sum is", sum) # Output: The sum is 48
If with list
We can use the range() function in for loops to iterate through a sequence of numbers. It
can be combined with the len() function to iterate though a sequence using indexing.

# Program to iterate through a list using indexing

G = [‘apple', ‘orange', ‘chocolate'] # iterate over the list using index


for i in range(len(G)):
print("I like", G[i])

# Output: I like apple


# Output: I like orange
# Output: I like chocolate
for i in range(4, 10, 2):
print(i)

4
6
8
for loop with else
 A for loop can have an optional else block as well. The else part is executed if the items in the
sequence used in for loop exhausts. break statement can be used to stop a for loop. In such case,
the else part is ignored.
 Hence, a for loop's else part runs if no break occurs.

digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")

# Output :
0
1
5
No items left.
Python while Loop
The while loop in Python is used to iterate over a block of code as long as the test expression
(condition) is true.
Syntax of while Loop in Python

# Program to add all number (sum = 1+2+3+...+n)


# To take input from the user
(n = int(input("Enter n: "))
n = 10
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1 # update counter
print("The sum is", sum)

# Output : 55
Python break statement
The working of break statement in for loop and while loop is shown
below.

# Use of break statement inside


loop
for val in “mango":
if val == “g":
break
print(val)
print("The end")
# Output:
m
a
n
Python continue statement
The working of continue statement in for and while loop is shown
below.

# Program to show the use of continue


statement inside loops
for val in “mango":
if val == “n":
continue
print(val)
print("The end")
# Output:
m
a
g
o
Ex-1Write a program to input cost price and
selling price of a product and check profit or
loss. Also calculate total profit or loss.
cp=int(input("enter cost price:"))
sp=int(input("enter sale price:"))
if sp>cp:
print(‘profit=‘,sp-cp)
elif cp>sp:
print(‘loss=‘,cp-sp)
else:
print(“no profit…no loss…")
Ex-2Write a program to input your age and
your friend’s age and display the output
whether you are elder, younger or same age.
m=input("enter your age:")
f=input("enter friend’s age:")

while m>f:
print("m bigger")

break

while m==f:

print(“twins")

break

while m<f:

print("m smaller")

break
Ex-3Write a program to input a number and
determine whether it is an odd number or
even number.
Happy ! Coding...

You might also like