SlideShare una empresa de Scribd logo
1 de 44
K.LEELARANI AP/CSE
KAMARAJ COLLEGE OF ENGINEERING AND TECHNOLOGY
 What is Python
 History of Python
 Why do people use Python
 Applications of python
 Who uses python today
 Running Python
 Variable in python
 Python Data Types
 Input() function
 Conditional and looping Statements
 Python is a general purpose, high level ,object
oriented programming language.
 Python is also called as Interpreted language
 Invented in the Netherlands, early 90s by Guido
van Rossum •
 Guido Van Rossum is fan of ‘Monty Python’s
Flying Circus’, this is a famous TV show in
Netherlands •
 Named after Monty Python •
 Open sourced from the beginning
 Google makes extensive use of Python in its web
search system.
 Intel, Cisco and IBM use Python for hardware
testing.
 The YouTube video sharing service is largely
written in Python
 Facebook ,instagram…
 Free and Open Source
 Extensible and Embeddable
 High level ,interpreted language
 Large standard libraries to solve common tasks.
 Web Applications
 Scientific and Numeric Computing
> Earthpy
> Astropy
 Simple syntax (interactive mode ,script mode)
 >>> print 'Hello world’
Hello world
>>>2+3
>>> 5
 A Python variable is a reserved memory location
to store values.
 In other words, a variable in a python program
gives data to the computer for processing.
 Every value in Python has a datatype.
 >>> year =2019
>>>type(year)
<class 'int'>
 >>> department=“CSE”
>>>type(department)
<class ‘str’>
Python Data Types
Numeric String List Tuple Dictionary Boolean
 Python has three numeric types
> integer
> floating point numbers
> Complex numbers (a+bi)
Practice:
>>>a=15
>>>type(a)
>>>b=1.5
>>>type(b)
 A string in python can be a series or a sequence
of alphabets, numerals and special characters.
 Single quotes or double quotes are used to
represent strings
 The first character of a string has an index 0.
Practice:
>>>department=“cse”
>>>type(department)
<class ‘str’>
>>> string1=“Hi Friends”
>>>string1
Concatenation Operator (+) – Combine two or
more than two strings
>>> string1 + “How are You”
Repetition Operator (*) - Repeat the same
string several times
>>> string1 *2
 List:
The list is a most versatile Data type available
in Python which can be written as a list of
comma-separated values (items) between square
brackets. Important thing about a list is that
items in a list need not be of the same type.
Example:
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
s.no Function with description
1. cmp(list1, list2) #Compares elements of both lists
2. len(list) #Gives the total length of the list
3. max(list) # Returns item from the list with max value.
4. min(list) #Returns item from the list with min value.
Tuples:
A tuple is a sequence of immutable Python
objects. Tuples are sequences, just like lists. The
differences between tuples and lists are, the
tuples cannot be changed unlike lists and tuples
use parentheses, whereas lists use square
brackets.
Example:
tup1 = (1, 2, 3, 4, 5 )
tup2 = ("a", "b", "c", "d“)
SN Function with Description
1 cmp(tuple1, tuple2) #Compares
elements of both tuples.
2 len(tuple) #Gives the total length
of the tuple.
3 max(tuple) #Returns item from the
tuple with max value
4 min(tuple) # Returns item from
the tuple with min value
 Unordered collection of key-value pairs.
Keys and values can be of any type in dictionary
 Items in dictionaries are enclosed in the curly-
braces {},Separated by the comma (,)
 A colon is used to separate key from value
>>>dict1={1:”first”,”second”:2}
>>>dict1[3]=“third line” #add new item
>>>dict1
>>>dict1.keys() # display dictionary keys
>>>dict1.values() # display dictionary values
The True and False data is known as Boolean
Practice:
>>>A=True
>>>type(A)
>>>B=False
>>>type(B)
>>>name = input(“What is your name?”)
>>>print (“Hello”+name)
>>>age=input(“Enter your age?”)
>>>age
>>>hobbies=input(“What are your hobbies?”)
>>>hobbies
 Write a program to print your name, age,and
name of the school.
 Write a program to find the area of a
rectangle/square
 If
 If..else
 Nested if
if test expression:
statement(s)
• Here, the program evaluates the test expression and will
execute statement(s) only if the text expression is True.
• If the text expression is False, the statement(s) is not
executed.
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1
if num > 0:
print(num, "is a positive number.")
Syntax of if...else
if test expression:
Body of if
else:
Body of else
# Program checks if the number is positive or
negative
# And displays an appropriate message
num = 3
if num >0:
print("Positive number")
else:
print("Negative number")
Syntax of if...elif...else
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")
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
 Looping is defined as repeatedly executing block of
statements for certain number of times.
 Python has mainly 2 types of looping statements
> for loop
> while loop
 The for loop in Python is used to iterate over a
sequence (list, tuple, string) or other iterable objects.
Iterating over a sequence is called traversal.
for val in sequence:
Body of for
• Here, val is the variable that takes the value of the item
inside the sequence on each iteration.
• Loop continues until we reach the last item in the sequence.
The body of for loop is separated from the rest of the code
using indentation.
# Program to find the sum of all numbers
stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
print("The sum is", sum)
 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.
 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.")
The while loop in Python is used to iterate over a block of
code as long as the test expression (condition) is true.
while test_expression:
Body of while
• In while loop, test expression is checked first. The body of the loop
is entered only if the test_expression evaluates to True. After one
iteration, the test expression is checked again. This process
continues until the test_expression evaluates to False.
• In Python, the body of the while loop is determined through
indentation.
• Body starts with indentation and the first unindented line marks the
end.
# Program to add natural numbers upto sum = 1+2+3+...+n
# To take input from the user,
# n = int(input("Enter n: "))
n = 10
# initialize sum and counter
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
THANK YOU

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Python programming language
Python programming languagePython programming language
Python programming language
 
Python Basics
Python Basics Python Basics
Python Basics
 
PPT on Data Science Using Python
PPT on Data Science Using PythonPPT on Data Science Using Python
PPT on Data Science Using Python
 
Programming with Python
Programming with PythonProgramming with Python
Programming with Python
 
Python-The programming Language
Python-The programming LanguagePython-The programming Language
Python-The programming Language
 
A Gentle Introduction to Coding ... with Python
A Gentle Introduction to Coding ... with PythonA Gentle Introduction to Coding ... with Python
A Gentle Introduction to Coding ... with Python
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for Kids
 
Python
PythonPython
Python
 
Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3)
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
 
Python advance
Python advancePython advance
Python advance
 
Python
PythonPython
Python
 
Python made easy
Python made easy Python made easy
Python made easy
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
 
Python ppt
Python pptPython ppt
Python ppt
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Two
 
python codes
python codespython codes
python codes
 
Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python
 
Fundamentals of Python Programming
Fundamentals of Python ProgrammingFundamentals of Python Programming
Fundamentals of Python Programming
 

Similar a Python introduction

Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
priestmanmable
 

Similar a Python introduction (20)

Python cheat-sheet
Python cheat-sheetPython cheat-sheet
Python cheat-sheet
 
Python programming
Python  programmingPython  programming
Python programming
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Pythonintro
PythonintroPythonintro
Pythonintro
 
Basic of Python- Hands on Session
Basic of Python- Hands on SessionBasic of Python- Hands on Session
Basic of Python- Hands on Session
 
Day2
Day2Day2
Day2
 
Python basics
Python basicsPython basics
Python basics
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
 
Python lab basics
Python lab basicsPython lab basics
Python lab basics
 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
 
Python slide.1
Python slide.1Python slide.1
Python slide.1
 
manish python.pptx
manish python.pptxmanish python.pptx
manish python.pptx
 

Último

notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
MsecMca
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
dharasingh5698
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 

Último (20)

22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 

Python introduction

  • 1. K.LEELARANI AP/CSE KAMARAJ COLLEGE OF ENGINEERING AND TECHNOLOGY
  • 2.  What is Python  History of Python  Why do people use Python  Applications of python  Who uses python today  Running Python  Variable in python  Python Data Types  Input() function  Conditional and looping Statements
  • 3.  Python is a general purpose, high level ,object oriented programming language.  Python is also called as Interpreted language
  • 4.  Invented in the Netherlands, early 90s by Guido van Rossum •  Guido Van Rossum is fan of ‘Monty Python’s Flying Circus’, this is a famous TV show in Netherlands •  Named after Monty Python •  Open sourced from the beginning
  • 5.  Google makes extensive use of Python in its web search system.  Intel, Cisco and IBM use Python for hardware testing.  The YouTube video sharing service is largely written in Python  Facebook ,instagram…
  • 6.  Free and Open Source  Extensible and Embeddable  High level ,interpreted language  Large standard libraries to solve common tasks.
  • 7.  Web Applications  Scientific and Numeric Computing > Earthpy > Astropy
  • 8.  Simple syntax (interactive mode ,script mode)  >>> print 'Hello world’ Hello world >>>2+3 >>> 5
  • 9.  A Python variable is a reserved memory location to store values.  In other words, a variable in a python program gives data to the computer for processing.  Every value in Python has a datatype.
  • 10.  >>> year =2019 >>>type(year) <class 'int'>  >>> department=“CSE” >>>type(department) <class ‘str’>
  • 11. Python Data Types Numeric String List Tuple Dictionary Boolean
  • 12.  Python has three numeric types > integer > floating point numbers > Complex numbers (a+bi) Practice: >>>a=15 >>>type(a) >>>b=1.5 >>>type(b)
  • 13.  A string in python can be a series or a sequence of alphabets, numerals and special characters.  Single quotes or double quotes are used to represent strings  The first character of a string has an index 0. Practice: >>>department=“cse” >>>type(department) <class ‘str’>
  • 14. >>> string1=“Hi Friends” >>>string1 Concatenation Operator (+) – Combine two or more than two strings >>> string1 + “How are You” Repetition Operator (*) - Repeat the same string several times >>> string1 *2
  • 15.  List: The list is a most versatile Data type available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type. Example: list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2, 3, 4, 5 ];
  • 16. s.no Function with description 1. cmp(list1, list2) #Compares elements of both lists 2. len(list) #Gives the total length of the list 3. max(list) # Returns item from the list with max value. 4. min(list) #Returns item from the list with min value.
  • 17. Tuples: A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets. Example: tup1 = (1, 2, 3, 4, 5 ) tup2 = ("a", "b", "c", "d“)
  • 18. SN Function with Description 1 cmp(tuple1, tuple2) #Compares elements of both tuples. 2 len(tuple) #Gives the total length of the tuple. 3 max(tuple) #Returns item from the tuple with max value 4 min(tuple) # Returns item from the tuple with min value
  • 19.  Unordered collection of key-value pairs. Keys and values can be of any type in dictionary  Items in dictionaries are enclosed in the curly- braces {},Separated by the comma (,)  A colon is used to separate key from value
  • 20. >>>dict1={1:”first”,”second”:2} >>>dict1[3]=“third line” #add new item >>>dict1 >>>dict1.keys() # display dictionary keys >>>dict1.values() # display dictionary values
  • 21. The True and False data is known as Boolean Practice: >>>A=True >>>type(A) >>>B=False >>>type(B)
  • 22. >>>name = input(“What is your name?”) >>>print (“Hello”+name) >>>age=input(“Enter your age?”) >>>age >>>hobbies=input(“What are your hobbies?”) >>>hobbies
  • 23.  Write a program to print your name, age,and name of the school.  Write a program to find the area of a rectangle/square
  • 24.
  • 26.
  • 27. if test expression: statement(s) • Here, the program evaluates the test expression and will execute statement(s) only if the text expression is True. • If the text expression is False, the statement(s) is not executed.
  • 28. num = 3 if num > 0: print(num, "is a positive number.") print("This is always printed.") num = -1 if num > 0: print(num, "is a positive number.")
  • 29.
  • 30. Syntax of if...else if test expression: Body of if else: Body of else
  • 31. # Program checks if the number is positive or negative # And displays an appropriate message num = 3 if num >0: print("Positive number") else: print("Negative number")
  • 32.
  • 33. Syntax of if...elif...else if test expression: Body of if elif test expression: Body of elif else: Body of else
  • 34. # 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")
  • 35. num = float(input("Enter a number: ")) if num >= 0: if num == 0: print("Zero") else: print("Positive number") else: print("Negative number")
  • 36.  Looping is defined as repeatedly executing block of statements for certain number of times.  Python has mainly 2 types of looping statements > for loop > while loop  The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal.
  • 37. for val in sequence: Body of for • Here, val is the variable that takes the value of the item inside the sequence on each iteration. • Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.
  • 38. # Program to find the sum of all numbers stored in a list # List of numbers numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11] # variable to store the sum sum = 0 # iterate over the list for val in numbers: sum = sum+val print("The sum is", sum)
  • 39.  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.  A for loop's else part runs if no break occurs.
  • 40. digits = [0, 1, 5] for i in digits: print(i) else: print("No items left.")
  • 41. The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true.
  • 42. while test_expression: Body of while • In while loop, test expression is checked first. The body of the loop is entered only if the test_expression evaluates to True. After one iteration, the test expression is checked again. This process continues until the test_expression evaluates to False. • In Python, the body of the while loop is determined through indentation. • Body starts with indentation and the first unindented line marks the end.
  • 43. # Program to add natural numbers upto sum = 1+2+3+...+n # To take input from the user, # n = int(input("Enter n: ")) n = 10 # initialize sum and counter sum = 0 i = 1 while i <= n: sum = sum + i i = i+1 # update counter # print the sum print("The sum is", sum)