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

Python Sonal

This document provides an introduction to programming with the Python language. It discusses that Python is an interpreted, interactive, object-oriented scripting language that is designed to be highly readable. The document also provides a brief history of Python, noting that it was invented in the 1990s in the Netherlands and is now widely used. It then covers some of the basics of Python, including using print statements, variables, expressions, data types, and operators.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
130 views

Python Sonal

This document provides an introduction to programming with the Python language. It discusses that Python is an interpreted, interactive, object-oriented scripting language that is designed to be highly readable. The document also provides a brief history of Python, noting that it was invented in the 1990s in the Netherlands and is now widely used. It then covers some of the basics of Python, including using print statements, variables, expressions, data types, and operators.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 127

Introduction to Programming

with Python

1
Which of these languages do you know?

• C or C++
• Java
• Perl
• Scala
• PHP
• Python
• Matlab
• Ruby
Python
 Python is a high-level, interpreted, interactive and object-oriented scripting language.
Python is designed to be highly readable. It uses English keywords frequently where
as other languages use punctuation, and it has fewer syntactical constructions than
other languages.

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

4
Brief History of Python
 Invented in the Netherlands, early 90s by Guido van
Rossum
 Named after Monty Python
 Open sourced from the beginning
 Considered a scripting language, but is much more
 high-level, interpreted, interactive and object-oriented
scripting language.
 Used by Google from the beginning
 Increasingly popular
The Python tutorial is good!
The Basics
Python Overview

• Programs are composed of modules


• Modules contain statements
• Statements contain expressions
• Expressions create and process objects
Running Python:

• Three different ways to start Python:


(1) Interactive Interpreter:
– Enter python and start coding right away in the
interactive interpreter by starting it from the
command line.
Running Python:

(2) Running by creating Script

(3) Integrated Development Environment


Hello World

•Open a terminal window and type “python”


•If on Windows open a Python IDE like IDLE
•At the prompt type ‘hello world!’

>>> 'hello world!'


'hello world!'
The Python Interpreter
•Python is an interpreted
language >>> 3 + 7
•The interpreter provides an 10
interactive environment to >>> 3 < 15
play with the language True
>>> 'print me'
•Results of expressions are 'print me'
printed on the screen >>> print 'print me'
print me
interpret
>>>
source code output
Hello.py
print
 print : Produces text output on the console.

 Syntax:
print "Message"
print Expression
 Prints the given text message or expression value on the console, and moves the cursor
down to the next line.

print Item1, Item2, ..., ItemN


 Prints several messages and/or expressions on the same line.

 Examples:
print "Hello, world!"
age = 45
print "You have", 65 - age, "years until retirement"
Output:
13
print
 print : Produces text output on the console.

 Syntax:
print "Message"
print Expression
 Prints the given text message or expression value on the console, and moves
the cursor down to the next line.

print Item1, Item2, ..., ItemN


 Prints several messages and/or expressions on the same line.
 Examples:
print "Hello, world!"
age = 45
print "You have", 65 - age, "years until retirement"
Output:
Hello, world!
14
You have 20 years until retirement
First Python Program:

 INTERACTIVE MODE PROGRAMMING:


 Type the following text to the right of the Python prompt and
press the Enter key:

 this will produce following result:


First Python Program:

 SCRIPT MODE PROGRAMMING:


 Let us write a simple Python program in a script.
 All python files will have extension .py.
 So put the following source code in a test.py file.
Documentation

The ‘#’ starts a line comment

>>> 'this will print'


'this will print'
>>> #'this will not'
>>>
Whitespace
Whitespace is meaningful in Python: especially
indentation and placement of newlines
•Use a newline to end a line of code
Use \ when must go to next line prematurely
•No braces {} to mark blocks of code, use
consistent indentation instead
• First line with less indentation is outside of the block
• First line with more indentation starts a nested block
•Colons start off a new block in many constructs,
e.g. function definitions, then clauses
Example
Example
Example
Variables
• Are not declared, just assigned
• The variable is created the first time you assign it
a value
• Are references to objects
• Type information is with the object, not the
reference
• Everything in Python is an object
Variables
◼ Syntax:

name = value >>> x = 7


>>> x
◼ Examples: x = 5
gpa = 3.14
7
>>> x = 'hello'
x 5 gpa 3.14 >>> x
'hello'
◼ A variable that has been given a >>>
value can be used in expressions.
x + 4 is 9
Naming Rules
• Names are case sensitive and cannot start
with a number. They can contain letters,
numbers, and underscores.
bob Bob _bob _2_bob_ bob_2 BoB
• There are some reserved words:
and, assert, break, class, continue,
def, del, elif, else, except, exec,
finally, for, from, global, if,
import, in, is, lambda, not, or,
pass, print, raise, return, try,
while
Assignment
• You can assign to multiple names at the
same time
>>> x, y = 2, 3
>>> x
?
>>> y
?
Assignment
• You can assign to multiple names at the
same time
>>> x, y = 2, 3
>>> x
2
>>> y
3
This makes it easy to swap values
>>> x, y = y, x
• Assignments can be chained
>>> a = b = x = 2
Expressions
 expression: A data value or set of operations to
compute a value.
Examples: 10 + 4 * 3
OUTPUT ?????

28
Expressions
 expression: A data value or set of operations to
compute a value.
Examples: 10 + 4 * 3
22

 Arithmetic operators we will use:


 + - * / addition, subtraction/negation, multiplication, division
 % modulus, a.k.a. remainder
 ** exponentiation
 // floor division (5/2= 2)

1 + 3 * 4 is ??

29
Expressions
 expression: A data value or set of operations to
compute a value.
Examples: 10 + 4 * 3
22

 Arithmetic operators we will use:


 + - * / addition, subtraction/negation, multiplication, division
 % modulus, a.k.a. remainder
 ** exponentiation
 // floor division (5/2= 2)
 precedence: Order in which operations are computed.
 * / % ** have a higher precedence than + -
1 + 3 * 4 is 13

30
Expressions
 expression: A data value or set of operations to compute a
value.
Examples: 10 + 4 * 3
22

 Arithmetic operators we will use:


 + - * / addition, subtraction/negation, multiplication, division
 % modulus, a.k.a. remainder
 ** exponentiation
 // floor division (5/2= 2)
 precedence: Order in which operations are computed.
 * / % ** have a higher precedence than + -
1 + 3 * 4 is 13

 Parentheses can be used to force a certain order of evaluation.


(1 + 3) * 4 is 16

31
Logic
 Many logical expressions use relational operators:
Operator Meaning Example Result
== equals 1 + 1 == 2 True
!= OR <> does not equal 3.2 != 2.5 True
< less than 10 < 5 False
> greater than 10 > 5 True
<= less than or equal to 126 <= 100 False
>= greater than or equal to 5.0 >= 5.0 True

 Logical expressions can be combined with logical


operators: Operator Example Result
and 9 != 6 and 2 < 3 True
or 2 == 3 or -1 < 5 True
not not 7 > 0 False

32
Standard Data Types
• Python has five standard data types −
• Numbers – int, long, float, complex
• String
• List
• Tuple
• Dictionary

• Integers (default for numbers)


z = 5 / 2
• Floats
x = 3.456
• Strings
• Can use “” or ‘’ to specify with “abc” == ‘abc’
Numbers: Integers
• Integer – the equivalent of
a C long >>> 132224
• Long Integer – an 132224
unbounded integer value. >>> 132323 ** 2
17509376329L
>>>
• var1 = 1
• Var2 = 10

• We can delete a single object or multiple


objects by using the del statement.
• del var1
Numbers: Floating Point
• int(x) converts x to an >>> 1.23232
integer 1.2323200000000001
>>> print 1.23232
• float(x) converts x to a 1.23232
floating point >>> 1.3E7
• The interpreter shows 13000000.0
>>> int(2.0)
a lot of digits
2
>>> float(2)
2.0
Numbers: Complex
• Built into Python
• Same operations are >>> x = 3 + 2j
supported as integer and >>> y = -1j
>>> x + y
float
(3+1j)
>>> x * y
(2-3j)
String Literals

• Strings are immutable


• There is no char type like >>> x = 'hello'
>>> x = x + ' there'
in C++ or Java
>>> x
• + is overloaded to do 'hello there'
concatenation
Strings are immutable

• x[2]=‘a’
Error Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
a[1]='q'
TypeError: 'str' object does not support item
assignment
Strings
 string: A sequence of text characters in a program.
 Strings start and end with quotation mark " or apostrophe ' characters.
 Examples:
"hello"
"This is a string"
"This, too, is a string. It can be very long!"

 A string may not span across multiple lines or contain a " character.
"This is not
a legal String."
"This is not a "legal" String either."

 A string can represent characters by preceding them with a backslash.


 \t tab character
 \n new line character
 \" quotation mark character
 \\ backslash character

 Example: print "Hello\tthere\nHow are you?"

40
Indexes
 Characters in a string are numbered with indexes starting at 0:
 Example:
name = "P. Diddy"
>>> s = '012345'
index 0 1 2 3 4 5 6 7 >>> s[3]
character P . D i d d y '3'
>>> s[1:4]
 Accessing an individual character of a string: '123'
variableName [ index ] >>> s[2:]
 Example:
'2345'
print name, "starts with", name[0] >>> s[:4]
'0123'
Output:
P. Diddy starts with P
>>> s[-2]
'4'
41
• str = 'Hello World!'
• print str
• print str[0]
• print str[2:5]
• print str[2:]
• print str * 2
• print str + "TEST”
• Hello World!
• H
• llo
• llo World!
• Hello World!Hello World!
• Hello World!TEST
String properties
 len(string) - number of characters in a string
(including spaces)
 str.lower(string) - lowercase version of a string
 str.upper(string) - uppercase version of a string

 Example:
name = "Martin Douglas Stepp"
length = len(name)
big_name = str.upper(name)
print big_name, "has", length,
"characters"
Output:
MARTIN DOUGLAS STEPP has 20 characters

44
String Literals: Many Kinds
 Can use single or double quotes, and three double
quotes for a multi-line string
>>> 'I am a string'
'I am a string'
>>> "So am I!"
'So am I!'
>>> s = """And me too!
though I am much longer
than the others :)"""
'And me too!\nthough I am much longer\nthan the others :)‘
>>> print s
And me too!
though I am much longer
than the others :)‘
Basic Datatypes
 Integers (default for numbers)
z = 5 / 2 # Answer 2, integer division
 Floats
x = 3.456
 Strings
 Can use “” or ‘’ to specify with “abc” == ‘abc’
 Unmatched can occur within the string: “matt’s”
 Use triple double-quotes for multi-line strings or
strings that contain both ‘ and “ inside of them:
“““a‘b“c”””
>>word = 'word'
>>word
Output=?

>>sentence = "This is a sentence."


>>sentence
Output=?

>>paragraph = """This is a paragraph.


>>It is made up of multiple lines and sentences."""
>>paragraph
Output=?
>>word = 'word'
>>word
Output=word

>>sentence = "This is a sentence."


>>sentence
Output= This is a sentence.

>>paragraph = """This is a paragraph.


>>It is made up of multiple lines and sentences."""
>>paragraph
Output= This is a paragraph. It is made up of multiple lines
and sentences
Data Type Summary

• Lists, Tuples, and Dictionaries can store any type


(including other lists, tuples, and dictionaries!)
• All variables are references
Lists
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
• print list
# Prints complete list
• print list[0]
# Prints first element of the list
• print list[1:3]
# Prints elements starting from 2nd till 3rd
• print list[2:]
# Prints elements starting from 3rd element
• print tinylist * 2
# Prints list two times print
• list + tinylist
# Prints concatenated lists
This produce the following result −
•['abcd', 786, 2.23, 'john', 70.200000000000003]
•abcd
•[786, 2.23]
•[2.23, 'john', 70.200000000000003]
•[123, 'john', 123, 'john']
•['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']
Counting in a list
lst=[1,1,2,2,4,5,6]
x=2
count = 0
for ele in lst:
if (ele == x):
count = count + 1
print (count)
Printing even numbers in a list
for n in lst:
if n % 2 == 0:
print (n)
Removing duplicates from a list
emp=[]
for n in lst:
if n not in emp:
emp.append(n)
print (emp)
Tuples
• A tuple is another sequence data type that is similar to the
list.
• The main differences between lists and tuples are: Lists are
enclosed in brackets [] and their elements and size can be
changed, while tuples are enclosed in parentheses ( ) and
cannot be updated.
• Tuples can be thought of as read-only lists.
Python Dictionary
• Python's dictionaries are kind of hash table
type. Consist of key-value pairs.
• A dictionary key can be almost any Python
type, but are usually numbers or strings.
Values, on the other hand, can be any
arbitrary Python object.
• Dictionaries are enclosed by curly braces
and values can be assigned and accessed
using square braces []
thisdict =
{"apple":"green","banana":"yellow","cherry
":"red"}
print(thisdict)
thisdict["apple"] ="red"
print(thisdict)

O/P
{'cherry': 'red', 'apple': 'green', 'banana':
'yellow'}
{'cherry': 'red', 'apple': 'red', 'banana': 'yellow'}
thisdict =
{"apple":"green","banana":"yellow","cherry
":"red"}
print(thisdict.keys())
print(thisdict.values())
O/P:
['cherry', 'apple', 'banana']
['red', 'green', 'yellow']
Data Type Summary

• Integers: 2323, 3234L


• Floating Point: 32.3, 3.1E2
• Complex: 3 + 2j, 1j
• Lists: l = [ 1,2,3]
• Dictionaries: d = {‘hello’ : ‘there’, 2 : 15}
User Input
• The raw_input(string) method returns a line of
user input as a string
• The parameter is used as a prompt
• The string can be converted by using the
conversion methods int(string), float(string), etc.
Input: Example
name = input("What's your name? ")

birthyear = int(input("What's your birth year? "))

print "Hi %s! You are %d years old!" % (name, 2015 - birthyear)

~: python input.py
What's your name?
> Michael
What year were you born?
>1980
Hi Michael! You are 35 years old!
WAP to take two numbers as input
from user and perform all binary
operations.
• Addition
• Subtraction
• Multiplication
• Division
• Floor division
• exponentiation
No Braces
• Python uses indentation instead of braces to determine
the scope of expressions
• All lines must be indented the same amount to be part
of the scope (or indented more if part of an inner
scope)
• This forces the programmer to use proper indentation
since the indenting is part of the program!
Control Flow
Things that are False
• The boolean value False
• The numbers 0 (integer), 0.0 (float) and 0j (complex).
• The empty string "".
Things that are True
• The boolean value True
• All non-zero numbers.
• Any string containing at least one character.
• A non-empty data structure.
Control Flow: if
 if statement: Executes a group of statements only if a
certain condition is true. Otherwise, the statements are
skipped.
 Syntax:
if condition:
statements

69
A Code Sample (in IDLE)
x = 34 - 23 # A comment.
y = “Hello” # Another one.
z = 3.45
if z == 3.45 or y == “Hello”:
x = x + 1
y = y + “ World” # String concat.
print x
print y
12
HelloWorld
A Code Sample (in IDLE)
x = 34 - 23 # A comment.
y = “Hello” # Another one.
z = 3.45
if z == 4.45 or y == “Hello”:
x = x + 1
y = y + “ World” # String concat.
print x
print y
A Code Sample (in IDLE)
x = 34 - 23 # A comment.
y = “Hello” # Another one.
z = 3.45
if z == 4.45 and y == “Hello”:
x = x + 1
y = y + “ World” # String concat.
print x
print y
if/else
 if/else statement: Executes one block of statements if a certain condition is
True, and a second block of statements if it is False.
 Syntax:
if condition:
statements
else:
statements

74
• Draw a flowchart to take student total marks
as input and print whether student is
pass(>50) or fail.
Marks = int(input(" enter your marks: "))
print Marks
if Marks > 50:
print "PASS"
else:
print "FAIL"
WAP in python to find max
between two numbers
number1 = int(input ("Enter number 1: "))
number2 = int(input ("Enter number 2: "))
if number1 > number2:
largest = number1
else:
largest = number2
print("Largest of entered two numbers is",
largest,"\n")
if/else
 Multiple conditions can be chained with elif ("else if"):
if condition:
statements
elif condition:
statements
else:
statements

79
 WAP in python to find max between three numbers.
num1 = int(input ("Enter number 1: "))
num2 = int(input ("Enter number 2: "))
num3 = int(input ("Enter number 2: "))
if (num1 >= num2):
if(num1>=num3):
largest=num1
else:
largest=num3
else:
if(num2>=num3):
largest=num2
else:
largest=num3
print("The largest number between",num1,",",num2,"and",num3,"is",largest)

80
Range Test

if (3 <= Time <= 5):


print “Office Hour"
WAP to print the grade accordingly:
A is >90
B is 80-90
C is 60-80
D is 40-60
F is < 40
WAP to find number entered by
user is even or odd
while True:
print("Enter 'x' for exit.")
num = input("Enter any number: ")
if num == 'x':
break
else:
check = num%2
if check == 0:
print(int(num), "is even number.\n")
elif check == 1:
print(int(num), "is odd number.\n")
else:
print(num, "is strange.\n")
Questions
• Write a python program to ask from user to
enter any character to find whether it is a
vowel or not.
• Write a python program to ask from user to
enter any number to check whether it is a
prime number or not:
• # Python Program - Check Leap Year or
Not
while
 while loop: Executes a group of statements as long as a condition is True.
 good for indefinite loops (repeat an unknown number of times)

 Syntax:
while condition:
statements

86
While Loops
>>> execfile(‘whileloop.py’)
1
2
3
4
5
6
7
8
9
>>>
In interpreter
While Loops
>>> execfile(‘whileloop.py’)
x=1 1
while x < 10 : 2
print x 3
x=x+1 4
5
whileloop.py
6
7
8
9
>>>
In interpreter
 WAP to print this series
 1 2 4 8 16 32 64

89
while
number = 1
while number < 65:
print number,
number = number * 2

 Output:
1 2 4 8 16 32 64

90
The Loop Else Clause
• The optional else clause runs only if the loop exits
normally (not by break)

x=1
1 2 hello
while x < 3 :
print x,
x=x+1
else:
print 'hello'
The Loop Else Clause
• The optional else clause runs only if the loop exits
normally (not by break)

x=1
1
while x < 3 : 2
print x hello
x=x+1
else:
print 'hello'
The Loop Else Clause

x=1
while x < 5 :
print x
x=x+1
break
else :
print 'i got here'

whileelse2.py
The Loop Else Clause

x=1
while x < 5 :
print x
x=x+1
break 1
else :
print 'i got here'

whileelse2.py
WAP in python to check string is palindrome or not
string = "naman"
str=string[len(string)-1]
i=len(string)-2
while i>=0:
str=str+string[i]
i=i-1
print str
print string
if str==string:
print "success"
95
The for loop
 for loop: Repeats a set of statements over a group of values.
 Syntax:

for variableName in groupOfValues:


statements

 We indent the statements to be repeated with tabs or spaces.


 variableName gives a name to each value, so you can refer to it in the statements.
 groupOfValues can be a range of integers, specified with the range function.

 Example:
for x in (1,2,3,4,5):
print x, "squared is", x * x

96
The for loop
 for loop: Repeats a set of statements over a group of values.
 Syntax:

for variableName in groupOfValues:


statements
 We indent the statements to be repeated with tabs or spaces.
 variableName gives a name to each value, so you can refer to it in the statements.
 groupOfValues can be a range of integers, specified with the range function.

 Example:
for x in (1,2,3,4,5):
print x, "squared is", x * x

Output:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25

97
Program to add n natural numbers
n = int(input("Enter n: "))
sum= 0
i=1
while i <= n:
sum = sum + i
i = i+1
print("The sum is", sum)
Example to illustrate the use of else statement
with the while loop

counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
Example: Using For loop

computer_brands = ["Apple", "Asus", "Dell", "Samsung"]


for brands in computer_brands:
print brands

Using While loop


computer_brands = ["Apple", "Asus", "Dell", "Samsung"]
i=0
while i < len(computer_brands):
print computer_brands[i]
i=i+1 >>>
Apple
Asus
Dell
Samsung
>>>
range
 The range function specifies a range of integers:
 range(start, stop) - the integers between start (inclusive)
and stop (exclusive)
 It can also accept a third value specifying the change between values.
 range(start, stop, step) - the integers between start (inclusive)
and stop (exclusive) by step

 Example:
for x in range(5, 0, -1):
print x
print "Blastoff!"

101
range
 The range function specifies a range of integers:
 range(start, stop) - the integers between start (inclusive)
and stop (exclusive)
 It can also accept a third value specifying the change between values.
 range(start, stop, step) - the integers between start (inclusive)
and stop (exclusive) by step
 Example:
for x in range(5, 0, -1):
print x
print "Blastoff!"
Output:
5
4
3
2
1
Blastoff!

102
 WAP in python to find sum of squares of first 10
numbers.

103
Cumulative loops
 Some loops incrementally compute a value that is
initialized outside the loop. This is sometimes called a
cumulative sum.
sum = 0
for i in range(1, 11):
sum = sum + (i * i)
print "sum of first 10 squares is", sum

Output:
sum of first 10 squares is 385

 Exercise: Write a Python program that computes the


factorial of an integer.
104
WAP to find Even numbers
n = int(input("Enter a number: "))
print("List of Even numbers is")
for i in range(1,n):
if (i%2 ==0) :
print(i)
factorial
fact =1
i=1
n=input("Enter a number: ")

while i<=n :
fact=fact*i
i=i+1
else:
print("Factorial of ", n, " is ", fact)
Practice Question
 Write a python program that searches for prime numbers
from 10 through 20.
lower = 10
upper = 20

print("Prime numbers between",lower,"and",upper,"are:")

for num in range(lower, upper + 1):

if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
 Sum of digits of numbers

n=int(input("Enter a number:"))
tot=0
while(n>0):
dig=n%10
tot=tot+dig
n=n//10
print("The total sum of digits
is:",tot)

109
 Reverse a number

x = int(input("Please Enter a
number to reverse: "))
reverse = 0

while(x):
reverse = reverse * 10
reverse = reverse + x % 10
x = int(x/10)

print(reverse)

110
Reverse a string
str = input("Enter string ")
str1=""
for i in str:
str1 = i + str1
print (str1)

111
 Palindrome

str = input("Enter any string: ")


hl=int(len(str)/2)

for i in range(0, hl):


if str[i] != str[len(str)-i-1]:
print("is not palindrome")
break
else:
print("is palindrome")

112
 Sum of digits of a number

n=156
tot=0
while(n>0):
dig=n%10
tot=tot+dig
n=n//10
print("The total sum of digits is:",tot)

113
 Fibonacci series

a=1
b=1
n=10
print(a)
print(b)
while(n-2):
c=a+b
a=b
b=c
print(c)
n=n-1
114
 Armstrong number
num=int(input("enter number: "))
sum = 0

temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp /= 10

if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
115
Loop Control

Break
Continue
pass
The break Statement:

 The break statement in Python terminates the current


loop and resumes execution at the next statement.

 The most common use for break is when some external


condition is triggered requiring a hasty exit from a loop.

 The break statement can be used in


both while and for loops.
for i in range(1,10):
if i == 3:
break
print i

for i in range(1,10):
if i == 3:
break
print i
The continue statement
 The continue statement in Python returns the control
to the beginning of the while loop.

 The continue statement rejects all the remaining


statements in the current iteration of the loop and moves
the control back to the top of the loop.

 The continue statement can be used in


both while and for loops.
for i in range(1,10):
if i == 3:
continue
print i >>>
1
2
4
5
6
7
8
9
>>>
Pass statement
 The pass statement in Python is used when a statement
is required syntactically but you do not want any
command or code to execute.
 The pass statement is a null operation; nothing happens
when it executes.
 The pass is also useful in places where your code will
eventually go, but has not been written yet (e.g., in stubs
for example):
for letter in 'Python':
if letter == 'h':
pass
else:
print ('Current Letter :', letter)

122
Modules
• When a Python program starts it only has
access to a basic functions and classes.
(“int”, “dict”, “len”, “sum”, “range”, ...)
• “Modules” contain additional functionality.
• Use “import” to tell Python to load a module.
>>> import math
>>> import nltk
• Use ”from module import *” to import
everything.
Pattern Printing
n=5 *
for i in range(1,n+1): **
for j in range(1,i+1): ***
print ('* ', end="") ****
print('') *****
Pattern Printing
n=5 1
for i in range(1,n+1): 12
for j in range(1,i+1): 123
print (j, end="") 1234
print('') 12345
print ('')
Pattern Printing
n=5 *****
for i in range(1,n+1): ****
for j in range(n,i-1,-1): ***
print ('* ', end="") **
print('') *
Pattern Printing
n=5 54321
for i in range(1,n+1): 5432
for j in range(n,i-1,-1): 543
print (j, end="") 54
print('') 5
Pattern Printing
n=5 1 2 3 4 5
num=1 6 7 8 9
for i in range(1,n+1): 10 11 12
for j in range(n,i-1,-1): 13 14
#print ('%3d' %(num),end="") 15
print ('{:3d}'.format(num),
end="")
num+=1
print('')
Pattern Printing
n=5 5
for i in range(1,n+1): 45
for j in range(1,n-i+1): 345
print (end=" ") 2345
for k in range(n-i+1,n+1): 12345
print (k, end="")
print('')
Pattern Printing
n=5 1
for i in range(1,n+1): 12
for j in range(1,n-i+1): 123
print (end=" ") 1234
for k in range(1,i+1): 12345
print (k, end="")
print('')
Pattern Printing
k=0 *
rows = 10 ***
for i in range(1, rows+1): *****
for space in range(1, (rows-i)+1): *******
print(end=" ") *********
while k != (2*i-1): ***********
print("* ", end="") *************
k=k+1 ***************
k=0 *****************
print() *******************

You might also like