SlideShare a Scribd company logo
1 of 30
Python Basics:
Statements
Expressions
Loops
Strings
Functions
Python training in Bangalore
Program
• A program is a sequence of instructions or
statements.
• To run a program is to:
– create the sequence of instructions according to
your design and the language rules
– turn that program into the binary commands the
processor understands
– give the binary code to the OS, so it can give it to
the processor
– OS tells the processor to run the program
– when finished (or it dies :-), OS cleans up.
Python training institute in Bangalore
Example Code Listing
# 1. prompt user for the radius,
# 2. apply the area formula
# 3. print the results
import math
radiusString = input("Enter the radius of your circle:")
radiusFloat = float(radiusString)
circumference = 2 * math.pi * radiusFloat
area = math.pi * radiusFloat * radiusFloat
print()
print("The cirumference of your circle is:",circumference,
", and the area is:",area)
Python training institute in Bangalore
Getting Input
The function: input(“Give me a value”)
• prints “Give me a value” on the screen and
waits until the user types something
(anything), ending with [Enter] key
• Warning! Input() returns a string (sequence
of characters), no matter what is given. (‘1’ is
not the same as 1, different types)
Convert from string to integer
• Python requires that you must convert a sequence
of characters to an integer
• Once converted, we can do math on the integers
Python training in Bangalore
Import of Math
• One thing we did was to import the math
module with import math
• This brought in python statements to
support math (try it in the python window)
• We precede all operations of math with
math.xxx
• math.pi, for example, is pi.
math.pow(x,y) raises x to the yth power.
Python training institute in Bangalore
Assignment Statement
The = sign is the assignment symbol
• The value on the right is associated with the
variable name on the left
• A variable is a named location that can store
values (information). A variable is somewhat like a
file, but is in memory not on the HD.
• = Does not stand for equality here!
• What “assignment” means is:
– evaluate all the “stuff” on the rhs (right-hand-side)
of the = and take the resulting value and
associate it with the name on the lhs (left-h-s)
Python training institute in Bangalore
Printing Output
myVar = 12
print(‘My var has a value of:’,myVar)
• print() function takes a list of elements to
print, separated by commas
– if the element is a string, prints it as is
– if the element is a variable, prints the value
associated with the variable
– after printing, moves on to a new line of output
Python training in Bangalore
Syntax
• Lexical components.
• A Python program is (like a hierarchy):.
– A module (perhaps more than one)
– A module is just a file of python commands
– Each module has python statements
– Statements may have expressions
– Statements are commands in Python.
– They perform some action, often called a side
effect, but do not return any values
– Expressions perform some operation and return
a value Python training institute in Bangalore
Side Effects and Returns
• Make sure you understand the difference.
What is the difference between a side
effect and a return?
• 1 + 2 returns a value (it’s an expression).
You can “catch” the return value.
However, nothing else changed as a result
• print “hello” doesn’t return anything, but
something else - the side effect - did
happen. Something printed!
Python training in Bangalore
Whitespace
• white space are characters that don’t print
(blanks, tabs, carriage returns etc.
• For the most part, you can place “white
space” (spaces) anywhere in your program
• use it to make a program more readable
• However, python is sensitive to end of line
stuff. To make a line continue, use the 
print “this is a test”, 
“ of continuation”
prints
this is a test of continuation
Python training institute in Bangalore
Python
Tokens
and del from not while
as elif global or with
assert else if pass yield
break except import print
class exec in raise
continue finally is return
def for lambda try
Keywords:
You are
prevented from
using them in a
variable name
Reserved operators in Python (expressions):
+ - * ** / // %
<< >> & | ^ ~
< > <= >= == != <> Python training in Bangalore
Python Punctuators
• Python punctuation/delimiters ($ and ? not
allowed).
‘ “ # 
( ) [ ] { } @
, : . ` = ;
+= -= *= /= //= %=
&= |= ^= >>= <<= **=
Python training institute in Bangalore
Operators
• Integer
– addition and subtraction: +, -
– multiplication: *
– division
• quotient: //
• remainder: %
• Floating point
– add, subtract, multiply, divide: +, -, *, /
Python training in Bangalore
Loops: Repeating Statements
from turtle
import *
forward(100)
left(90)
forward(100)
left(90)
forward(100)
left(90)
forward(100)
Draw Square:
Repeat the following steps 4 times:
• Draw a line
• Turn left
from turtle import *
for count in range(4):
forward(100)
left(90)
Python training institute in Bangalore
While and For Statements
for iteration, moving through
all the elements of data
structure, one at a time.
• The while statement is the
more general repetition
construct. It repeats a set of
statements while some
condition is True.
from turtle import *
• The for statement is useful for count in
range(4):
forward(100)
left(90)
from turtle import *
count=1
while count<=4:
forward(100)
left(90)
count=count+1
Python training in Bangalore
Range Function
• The range function generates a sequence
of integers
• range(5) => [0, 1, 2, 3, 4]
– assumed to start at 0
– goes up to, but does not include, the provided
number argument.
• range(3,10) => [3, 4, 5, 6, 7, 8, 9]
– first argument is the number to begin with
– second argument is the end limit (not included!)
Python training institute in Bangalore
Iterating Through the Sequence
for num in range(1,5):
print(num)
• range generates the sequence [1, 2, 3, 4]
• for loop assigns num each of the values in
the sequence, one at a time in sequence
• prints each number (one number per line)
• list(range(-5,5)) # in shell to show range
Python training in Bangalore
Sequence of Characters
• We’ve talked about strings being a
sequence of characters.
• A string is indicated between ‘ ‘ or “ “
• The exact sequence of characters is
maintained, including spaces.
• Does NOT include multiple lines
• Use backslash  for line continuation
Python training institute in Bangalore
And Then There is “““ ”””
• Triple quotes preserve both vertical
and horizontal formatting of the string
• Allow you to type tables, paragraphs,
whatever and preserve the formatting
(like <pre> tag in html)
“““this is
a test
of multiple lines”””
Python training in Bangalore
Strings
Can use single or double quotes:
•S = “spam”
•s = ‘spam’
Just don’t mix them!
•myStr = ‘hi mom”  ERROR
Inserting an apostrophe:
•A = “knight’s” # mix up the quotes
•B = ‘knight’s’ # escape single quote
Python training institute in Bangalore
The Index
• Because the elements of a string are a
sequence, we can associate each element
with an index, a location in the sequence:
– positive values count up from the left,
beginning with index 0
Python training in Bangalore
Accessing an Element
• A particular element of the string is accessed by
the index of the element surrounded by square
brackets [ ]
helloStr = ‘Hello World’
print helloStr[1] => prints ‘e’
print helloStr[-1] => prints ‘d’
print helloStr[11] => ERROR
Python training institute in Bangalore
Basic String Operations
• + isconcatenation
newStr = ‘spam’ + ‘-’ + ‘spam-’
print newStr  spam-spam-
• * is repeat, the number is how many
times
newStr * 3 
spam-spam-spam-spam-spam-spam-
Python training in Bangalore
String Function: len
• The len function takes as an
argument a string and returns an
integer, the length of a string.
myStr = ‘Hello World’
len(myStr)  11 # space counts
Python training in Bangalore
Example
• A method represents a special program (function) that
is applied in the context of a particular object.
• upper is the name of a string method. It generates a
new string of all upper case characters of the string it
was called with.
myStr = ‘Python Rules!’ myStr.upper() 
‘PYTHON RULES!’
• The string myStr called the upper() method, indicated by
the dot between them.
Python training institute in Bangalore
Functions
From mathematics we know that functions
perform some operation and return one value.
Why to use them?
• Support divide-and-conquer strategy
• Abstraction of an operation
• Reuse: once written, use again
• Sharing: if tested, others can use
• Security: if well tested, then secure for reuse
• Simplify code: more readable
Python training in Bangalore
Python Invocation
• Consider a function which converts temps. in
Celsius to temperatures in Fahrenheit:
–Formula: F = C * 1.8 + 32.0
• Math: f(C) = C*1.8 + 32.0
• Python
def celsius2Fahrenheit (C):
return C*1.8 + 32.0
Terminology: “C” is an argument to the
function Python training institute in Bangalore
Return Statement
• Functions can have input (also called
arguments) and output (optional)
• The return statement indicates the
value that is returned by the function.
• The return statement is optional (a
function can return nothing). If no
return, the function may be called a
procedure.
Python training in Bangalore
Python training institute in Bangalore
For More Query
+91 9513332301/02
BEST IT TRAINING INSTITUTE IN BANGALORE

More Related Content

What's hot (12)

Python numbers
Python numbersPython numbers
Python numbers
 
Python
PythonPython
Python
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
 
Python advance
Python advancePython advance
Python advance
 
DSA 103 Object Oriented Programming :: Week 3
DSA 103 Object Oriented Programming :: Week 3DSA 103 Object Oriented Programming :: Week 3
DSA 103 Object Oriented Programming :: Week 3
 
Python The basics
Python   The basicsPython   The basics
Python The basics
 
Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1
 
Python Programming - II. The Basics
Python Programming - II. The BasicsPython Programming - II. The Basics
Python Programming - II. The Basics
 
Python Session - 4
Python Session - 4Python Session - 4
Python Session - 4
 
Java chapter 3
Java chapter 3Java chapter 3
Java chapter 3
 
Python programming
Python  programmingPython  programming
Python programming
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 

Similar to Python Basics: Statements, Expressions, Loops, Strings, Functions

Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.supriyasarkar38
 
modul-python-all.pptx
modul-python-all.pptxmodul-python-all.pptx
modul-python-all.pptxYusuf Ayuba
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : PythonRaghu Kumar
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methodsPranavSB
 
Python Basics by Akanksha Bali
Python Basics by Akanksha BaliPython Basics by Akanksha Bali
Python Basics by Akanksha BaliAkanksha Bali
 
Python introduction
Python introductionPython introduction
Python introductionleela rani
 
Advanced Web Technology ass.pdf
Advanced Web Technology ass.pdfAdvanced Web Technology ass.pdf
Advanced Web Technology ass.pdfsimenehanmut
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developersJim Roepcke
 
Python Learn Function with example programs
Python Learn Function with example programsPython Learn Function with example programs
Python Learn Function with example programsGeethaPanneer
 

Similar to Python Basics: Statements, Expressions, Loops, Strings, Functions (20)

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
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
 
Unit - 2 CAP.pptx
Unit - 2 CAP.pptxUnit - 2 CAP.pptx
Unit - 2 CAP.pptx
 
Python.pdf
Python.pdfPython.pdf
Python.pdf
 
Python.pptx
Python.pptxPython.pptx
Python.pptx
 
modul-python-all.pptx
modul-python-all.pptxmodul-python-all.pptx
modul-python-all.pptx
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
 
Python Basics by Akanksha Bali
Python Basics by Akanksha BaliPython Basics by Akanksha Bali
Python Basics by Akanksha Bali
 
Python introduction
Python introductionPython introduction
Python introduction
 
Advanced Web Technology ass.pdf
Advanced Web Technology ass.pdfAdvanced Web Technology ass.pdf
Advanced Web Technology ass.pdf
 
unit1 python.pptx
unit1 python.pptxunit1 python.pptx
unit1 python.pptx
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
Python Learn Function with example programs
Python Learn Function with example programsPython Learn Function with example programs
Python Learn Function with example programs
 
02basics
02basics02basics
02basics
 

More from TIB Academy

Ios operating system
Ios operating systemIos operating system
Ios operating systemTIB Academy
 
CCNA Introducing
CCNA IntroducingCCNA Introducing
CCNA IntroducingTIB Academy
 
Hadoop training in bangalore
Hadoop training in bangaloreHadoop training in bangalore
Hadoop training in bangaloreTIB Academy
 
CCNA Introducing
CCNA IntroducingCCNA Introducing
CCNA IntroducingTIB Academy
 
Hadoop tutorial for Freshers,
Hadoop tutorial for Freshers, Hadoop tutorial for Freshers,
Hadoop tutorial for Freshers, TIB Academy
 
Selenium institute in bangalore
Selenium institute in bangaloreSelenium institute in bangalore
Selenium institute in bangaloreTIB Academy
 
Selenium Tutorial for Beginners - TIB Academy
Selenium Tutorial for Beginners - TIB AcademySelenium Tutorial for Beginners - TIB Academy
Selenium Tutorial for Beginners - TIB AcademyTIB Academy
 
Django framework
Django framework Django framework
Django framework TIB Academy
 
Core java tutorials
Core java  tutorialsCore java  tutorials
Core java tutorialsTIB Academy
 
Spring tutorials
Spring tutorialsSpring tutorials
Spring tutorialsTIB Academy
 
Oracle DBA Tutorial for Beginners -Oracle training institute in bangalore
Oracle DBA Tutorial for Beginners -Oracle training institute in bangaloreOracle DBA Tutorial for Beginners -Oracle training institute in bangalore
Oracle DBA Tutorial for Beginners -Oracle training institute in bangaloreTIB Academy
 
Python tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academyPython tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academyTIB Academy
 
Best Angularjs tutorial for beginners - TIB Academy
Best Angularjs tutorial for beginners - TIB AcademyBest Angularjs tutorial for beginners - TIB Academy
Best Angularjs tutorial for beginners - TIB AcademyTIB Academy
 

More from TIB Academy (17)

Msbi
MsbiMsbi
Msbi
 
Ios operating system
Ios operating systemIos operating system
Ios operating system
 
Salesforce
Salesforce  Salesforce
Salesforce
 
CCNA Introducing
CCNA IntroducingCCNA Introducing
CCNA Introducing
 
Hadoop training in bangalore
Hadoop training in bangaloreHadoop training in bangalore
Hadoop training in bangalore
 
CCNA Introducing
CCNA IntroducingCCNA Introducing
CCNA Introducing
 
Hadoop tutorial for Freshers,
Hadoop tutorial for Freshers, Hadoop tutorial for Freshers,
Hadoop tutorial for Freshers,
 
Hadoop training
Hadoop trainingHadoop training
Hadoop training
 
Selenium institute in bangalore
Selenium institute in bangaloreSelenium institute in bangalore
Selenium institute in bangalore
 
Selenium Tutorial for Beginners - TIB Academy
Selenium Tutorial for Beginners - TIB AcademySelenium Tutorial for Beginners - TIB Academy
Selenium Tutorial for Beginners - TIB Academy
 
Django framework
Django framework Django framework
Django framework
 
Core java tutorials
Core java  tutorialsCore java  tutorials
Core java tutorials
 
Spring tutorials
Spring tutorialsSpring tutorials
Spring tutorials
 
78
7878
78
 
Oracle DBA Tutorial for Beginners -Oracle training institute in bangalore
Oracle DBA Tutorial for Beginners -Oracle training institute in bangaloreOracle DBA Tutorial for Beginners -Oracle training institute in bangalore
Oracle DBA Tutorial for Beginners -Oracle training institute in bangalore
 
Python tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academyPython tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academy
 
Best Angularjs tutorial for beginners - TIB Academy
Best Angularjs tutorial for beginners - TIB AcademyBest Angularjs tutorial for beginners - TIB Academy
Best Angularjs tutorial for beginners - TIB Academy
 

Recently uploaded

“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 

Recently uploaded (20)

“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 

Python Basics: Statements, Expressions, Loops, Strings, Functions

  • 2. Program • A program is a sequence of instructions or statements. • To run a program is to: – create the sequence of instructions according to your design and the language rules – turn that program into the binary commands the processor understands – give the binary code to the OS, so it can give it to the processor – OS tells the processor to run the program – when finished (or it dies :-), OS cleans up. Python training institute in Bangalore
  • 3. Example Code Listing # 1. prompt user for the radius, # 2. apply the area formula # 3. print the results import math radiusString = input("Enter the radius of your circle:") radiusFloat = float(radiusString) circumference = 2 * math.pi * radiusFloat area = math.pi * radiusFloat * radiusFloat print() print("The cirumference of your circle is:",circumference, ", and the area is:",area) Python training institute in Bangalore
  • 4. Getting Input The function: input(“Give me a value”) • prints “Give me a value” on the screen and waits until the user types something (anything), ending with [Enter] key • Warning! Input() returns a string (sequence of characters), no matter what is given. (‘1’ is not the same as 1, different types) Convert from string to integer • Python requires that you must convert a sequence of characters to an integer • Once converted, we can do math on the integers Python training in Bangalore
  • 5. Import of Math • One thing we did was to import the math module with import math • This brought in python statements to support math (try it in the python window) • We precede all operations of math with math.xxx • math.pi, for example, is pi. math.pow(x,y) raises x to the yth power. Python training institute in Bangalore
  • 6. Assignment Statement The = sign is the assignment symbol • The value on the right is associated with the variable name on the left • A variable is a named location that can store values (information). A variable is somewhat like a file, but is in memory not on the HD. • = Does not stand for equality here! • What “assignment” means is: – evaluate all the “stuff” on the rhs (right-hand-side) of the = and take the resulting value and associate it with the name on the lhs (left-h-s) Python training institute in Bangalore
  • 7. Printing Output myVar = 12 print(‘My var has a value of:’,myVar) • print() function takes a list of elements to print, separated by commas – if the element is a string, prints it as is – if the element is a variable, prints the value associated with the variable – after printing, moves on to a new line of output Python training in Bangalore
  • 8. Syntax • Lexical components. • A Python program is (like a hierarchy):. – A module (perhaps more than one) – A module is just a file of python commands – Each module has python statements – Statements may have expressions – Statements are commands in Python. – They perform some action, often called a side effect, but do not return any values – Expressions perform some operation and return a value Python training institute in Bangalore
  • 9. Side Effects and Returns • Make sure you understand the difference. What is the difference between a side effect and a return? • 1 + 2 returns a value (it’s an expression). You can “catch” the return value. However, nothing else changed as a result • print “hello” doesn’t return anything, but something else - the side effect - did happen. Something printed! Python training in Bangalore
  • 10. Whitespace • white space are characters that don’t print (blanks, tabs, carriage returns etc. • For the most part, you can place “white space” (spaces) anywhere in your program • use it to make a program more readable • However, python is sensitive to end of line stuff. To make a line continue, use the print “this is a test”, “ of continuation” prints this is a test of continuation Python training institute in Bangalore
  • 11. Python Tokens and del from not while as elif global or with assert else if pass yield break except import print class exec in raise continue finally is return def for lambda try Keywords: You are prevented from using them in a variable name Reserved operators in Python (expressions): + - * ** / // % << >> & | ^ ~ < > <= >= == != <> Python training in Bangalore
  • 12. Python Punctuators • Python punctuation/delimiters ($ and ? not allowed). ‘ “ # ( ) [ ] { } @ , : . ` = ; += -= *= /= //= %= &= |= ^= >>= <<= **= Python training institute in Bangalore
  • 13. Operators • Integer – addition and subtraction: +, - – multiplication: * – division • quotient: // • remainder: % • Floating point – add, subtract, multiply, divide: +, -, *, / Python training in Bangalore
  • 14. Loops: Repeating Statements from turtle import * forward(100) left(90) forward(100) left(90) forward(100) left(90) forward(100) Draw Square: Repeat the following steps 4 times: • Draw a line • Turn left from turtle import * for count in range(4): forward(100) left(90) Python training institute in Bangalore
  • 15. While and For Statements for iteration, moving through all the elements of data structure, one at a time. • The while statement is the more general repetition construct. It repeats a set of statements while some condition is True. from turtle import * • The for statement is useful for count in range(4): forward(100) left(90) from turtle import * count=1 while count<=4: forward(100) left(90) count=count+1 Python training in Bangalore
  • 16. Range Function • The range function generates a sequence of integers • range(5) => [0, 1, 2, 3, 4] – assumed to start at 0 – goes up to, but does not include, the provided number argument. • range(3,10) => [3, 4, 5, 6, 7, 8, 9] – first argument is the number to begin with – second argument is the end limit (not included!) Python training institute in Bangalore
  • 17. Iterating Through the Sequence for num in range(1,5): print(num) • range generates the sequence [1, 2, 3, 4] • for loop assigns num each of the values in the sequence, one at a time in sequence • prints each number (one number per line) • list(range(-5,5)) # in shell to show range Python training in Bangalore
  • 18. Sequence of Characters • We’ve talked about strings being a sequence of characters. • A string is indicated between ‘ ‘ or “ “ • The exact sequence of characters is maintained, including spaces. • Does NOT include multiple lines • Use backslash for line continuation Python training institute in Bangalore
  • 19. And Then There is “““ ””” • Triple quotes preserve both vertical and horizontal formatting of the string • Allow you to type tables, paragraphs, whatever and preserve the formatting (like <pre> tag in html) “““this is a test of multiple lines””” Python training in Bangalore
  • 20. Strings Can use single or double quotes: •S = “spam” •s = ‘spam’ Just don’t mix them! •myStr = ‘hi mom”  ERROR Inserting an apostrophe: •A = “knight’s” # mix up the quotes •B = ‘knight’s’ # escape single quote Python training institute in Bangalore
  • 21. The Index • Because the elements of a string are a sequence, we can associate each element with an index, a location in the sequence: – positive values count up from the left, beginning with index 0 Python training in Bangalore
  • 22. Accessing an Element • A particular element of the string is accessed by the index of the element surrounded by square brackets [ ] helloStr = ‘Hello World’ print helloStr[1] => prints ‘e’ print helloStr[-1] => prints ‘d’ print helloStr[11] => ERROR Python training institute in Bangalore
  • 23. Basic String Operations • + isconcatenation newStr = ‘spam’ + ‘-’ + ‘spam-’ print newStr  spam-spam- • * is repeat, the number is how many times newStr * 3  spam-spam-spam-spam-spam-spam- Python training in Bangalore
  • 24. String Function: len • The len function takes as an argument a string and returns an integer, the length of a string. myStr = ‘Hello World’ len(myStr)  11 # space counts Python training in Bangalore
  • 25. Example • A method represents a special program (function) that is applied in the context of a particular object. • upper is the name of a string method. It generates a new string of all upper case characters of the string it was called with. myStr = ‘Python Rules!’ myStr.upper()  ‘PYTHON RULES!’ • The string myStr called the upper() method, indicated by the dot between them. Python training institute in Bangalore
  • 26. Functions From mathematics we know that functions perform some operation and return one value. Why to use them? • Support divide-and-conquer strategy • Abstraction of an operation • Reuse: once written, use again • Sharing: if tested, others can use • Security: if well tested, then secure for reuse • Simplify code: more readable Python training in Bangalore
  • 27. Python Invocation • Consider a function which converts temps. in Celsius to temperatures in Fahrenheit: –Formula: F = C * 1.8 + 32.0 • Math: f(C) = C*1.8 + 32.0 • Python def celsius2Fahrenheit (C): return C*1.8 + 32.0 Terminology: “C” is an argument to the function Python training institute in Bangalore
  • 28. Return Statement • Functions can have input (also called arguments) and output (optional) • The return statement indicates the value that is returned by the function. • The return statement is optional (a function can return nothing). If no return, the function may be called a procedure. Python training in Bangalore
  • 30. For More Query +91 9513332301/02 BEST IT TRAINING INSTITUTE IN BANGALORE