SlideShare a Scribd company logo
Python Basics:
Statements
Expressions
Loops
Strings
Functions
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.
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)
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
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.
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)
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
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
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!
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
Tokens
Keywords:
You are
prevented
from using
them in a
variable name
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
Reserved operators in Python (expressions):
+ - * ** / // %
<< >> & | ^ ~
< > <= >= == != <>
Python Punctuators
• Python punctuation/delimiters ($ and ? not
allowed).
‘ “ # 
( ) [ ] { } @
, : . ` = ;
+= -= *= /= //= %=
&= |= ^= >>= <<= **=
Operators
• Integer
– addition and subtraction: +, -
– multiplication: *
– division
• quotient: //
• remainder: %
• Floating point
– add, subtract, multiply, divide: +, -, *, /
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)
While and For Statements
• The for statement is useful
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 *
for count in
range(4):
forward(100)
left(90)
from turtle import *
count=1
while count<=4:
forward(100)
left(90)
count=count+1
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!)
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
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
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”””
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
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
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
Basic String Operations
• + is concatenation
newStr = ‘spam’ + ‘-’ + ‘spam-’
print newStr  spam-spam-
• * is repeat, the number is how many
times
newStr * 3 
spam-spam-spam-spam-spam-spam-
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
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.
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 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
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 basics
from turtle import *
def draw_square (size):
for i in range (4):
forward (size)
right(90)
draw_square(25)
draw_square(125)
draw_square(75)
draw_square(55)

More Related Content

What's hot (13)

PPTX
Python for Beginners(v2)
Panimalar Engineering College
 
PPTX
C
Jerin John
 
PPTX
Java 8 streams
Manav Prasad
 
PPTX
scripting in Python
Team-VLSI-ITMU
 
PPTX
Algorithm analysis and design
Megha V
 
DOCX
Type header file in c++ and its function
Frankie Jones
 
PPTX
Python programming
Ashwin Kumar Ramasamy
 
PPTX
Matlab Functions
Umer Azeem
 
PDF
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
PPTX
Python programming –part 3
Megha V
 
PPT
Strings v.1.1
BG Java EE Course
 
PPTX
Functions in advanced programming
VisnuDharsini
 
PPTX
Library functions in c++
Neeru Mittal
 
Python for Beginners(v2)
Panimalar Engineering College
 
Java 8 streams
Manav Prasad
 
scripting in Python
Team-VLSI-ITMU
 
Algorithm analysis and design
Megha V
 
Type header file in c++ and its function
Frankie Jones
 
Python programming
Ashwin Kumar Ramasamy
 
Matlab Functions
Umer Azeem
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
Python programming –part 3
Megha V
 
Strings v.1.1
BG Java EE Course
 
Functions in advanced programming
VisnuDharsini
 
Library functions in c++
Neeru Mittal
 

Viewers also liked (9)

PDF
2. funciones de los auxiliares de educacion(1)
Hans Padilla Valera
 
PDF
Plan estratégido del estado plurinacional
Magisterio De Bolivia
 
PPTX
2015 bioinformatics bio_python_partii
Prof. Wim Van Criekinge
 
PDF
INECUACIONES CUADRÁTICAS
innovalabcun
 
PDF
Scalable ABM for SMB
Marketo
 
PDF
Permen LHK no.70 2016 ttg baku mutu emisi usaha dan atau kegiatan pengolahan ...
Rizki Darmawan
 
PDF
ISO 9001改版的五十道問題 part2
Leadership 領導力企業管理顧問有限公司
 
DOCX
Tha price of a great pearl.pt.3.newer.html.doc
MCDub
 
PDF
Introduction to LDAP and Directory Services
Radovan Semancik
 
2. funciones de los auxiliares de educacion(1)
Hans Padilla Valera
 
Plan estratégido del estado plurinacional
Magisterio De Bolivia
 
2015 bioinformatics bio_python_partii
Prof. Wim Van Criekinge
 
INECUACIONES CUADRÁTICAS
innovalabcun
 
Scalable ABM for SMB
Marketo
 
Permen LHK no.70 2016 ttg baku mutu emisi usaha dan atau kegiatan pengolahan ...
Rizki Darmawan
 
ISO 9001改版的五十道問題 part2
Leadership 領導力企業管理顧問有限公司
 
Tha price of a great pearl.pt.3.newer.html.doc
MCDub
 
Introduction to LDAP and Directory Services
Radovan Semancik
 
Ad

Similar to Python basics (20)

PPTX
Python language data types
Harry Potter
 
PPTX
Python language data types
Luis Goldster
 
PPTX
Python language data types
Hoang Nguyen
 
PPTX
Python language data types
Fraboni Ec
 
PPTX
Python language data types
Young Alista
 
PPTX
Python language data types
Tony Nguyen
 
PPTX
Python language data types
James Wong
 
PDF
Python.pdf
Shivakumar B N
 
PPTX
Review of C programming language.pptx...
SthitaprajnaLenka1
 
PPTX
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
sangeeta borde
 
PPTX
CLASS-11 & 12 ICT PPT PYTHON PROGRAMMING.pptx
seccoordpal
 
PPTX
Functions, List and String methods
PranavSB
 
PPTX
Aggregate.pptx
Ramakrishna Reddy Bijjam
 
PPTX
Python Revision Tour.pptx class 12 python notes
student164700
 
PDF
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
lailoesakhan
 
PPT
functions modules and exceptions handlings.ppt
Rajasekhar364622
 
PPTX
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
DOCX
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
priestmanmable
 
PPTX
Basic concept of Python.pptx includes design tool, identifier, variables.
supriyasarkar38
 
PPTX
PPT_1_9102501a-a7a1-493e-818f-cf699918bbf6.pptx
myatminsoe180
 
Python language data types
Harry Potter
 
Python language data types
Luis Goldster
 
Python language data types
Hoang Nguyen
 
Python language data types
Fraboni Ec
 
Python language data types
Young Alista
 
Python language data types
Tony Nguyen
 
Python language data types
James Wong
 
Python.pdf
Shivakumar B N
 
Review of C programming language.pptx...
SthitaprajnaLenka1
 
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
sangeeta borde
 
CLASS-11 & 12 ICT PPT PYTHON PROGRAMMING.pptx
seccoordpal
 
Functions, List and String methods
PranavSB
 
Aggregate.pptx
Ramakrishna Reddy Bijjam
 
Python Revision Tour.pptx class 12 python notes
student164700
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
lailoesakhan
 
functions modules and exceptions handlings.ppt
Rajasekhar364622
 
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
priestmanmable
 
Basic concept of Python.pptx includes design tool, identifier, variables.
supriyasarkar38
 
PPT_1_9102501a-a7a1-493e-818f-cf699918bbf6.pptx
myatminsoe180
 
Ad

More from Harry Potter (20)

PDF
How to build a rest api.pptx
Harry Potter
 
PPTX
Business analytics and data mining
Harry Potter
 
PPTX
Big picture of data mining
Harry Potter
 
PPTX
Data mining and knowledge discovery
Harry Potter
 
PPTX
Cache recap
Harry Potter
 
PPTX
Directory based cache coherence
Harry Potter
 
PPTX
How analysis services caching works
Harry Potter
 
PPTX
Optimizing shared caches in chip multiprocessors
Harry Potter
 
PPTX
Hardware managed cache
Harry Potter
 
PPTX
Smm & caching
Harry Potter
 
PPTX
Data structures and algorithms
Harry Potter
 
PPT
Abstract data types
Harry Potter
 
PPTX
Abstraction file
Harry Potter
 
PPTX
Object model
Harry Potter
 
PPTX
Concurrency with java
Harry Potter
 
PPTX
Encapsulation anonymous class
Harry Potter
 
PPT
Abstract class
Harry Potter
 
PPTX
Object oriented analysis
Harry Potter
 
PPTX
Api crash
Harry Potter
 
PPTX
Rest api to integrate with your site
Harry Potter
 
How to build a rest api.pptx
Harry Potter
 
Business analytics and data mining
Harry Potter
 
Big picture of data mining
Harry Potter
 
Data mining and knowledge discovery
Harry Potter
 
Cache recap
Harry Potter
 
Directory based cache coherence
Harry Potter
 
How analysis services caching works
Harry Potter
 
Optimizing shared caches in chip multiprocessors
Harry Potter
 
Hardware managed cache
Harry Potter
 
Smm & caching
Harry Potter
 
Data structures and algorithms
Harry Potter
 
Abstract data types
Harry Potter
 
Abstraction file
Harry Potter
 
Object model
Harry Potter
 
Concurrency with java
Harry Potter
 
Encapsulation anonymous class
Harry Potter
 
Abstract class
Harry Potter
 
Object oriented analysis
Harry Potter
 
Api crash
Harry Potter
 
Rest api to integrate with your site
Harry Potter
 

Recently uploaded (20)

PDF
Draugnet: Anonymous Threat Reporting for a World on Fire
treyka
 
PDF
Hello I'm "AI" Your New _________________
Dr. Tathagat Varma
 
PPTX
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
PDF
Introducing and Operating FME Flow for Kubernetes in a Large Enterprise: Expe...
Safe Software
 
PPTX
CapCut Pro PC Crack Latest Version Free Free
josanj305
 
PDF
Understanding The True Cost of DynamoDB Webinar
ScyllaDB
 
PDF
FME in Overdrive: Unleashing the Power of Parallel Processing
Safe Software
 
PDF
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
PDF
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 
PPTX
Practical Applications of AI in Local Government
OnBoard
 
PPTX
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
PPTX
Securing Model Context Protocol with Keycloak: AuthN/AuthZ for MCP Servers
Hitachi, Ltd. OSS Solution Center.
 
PDF
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
PPTX
Wondershare Filmora Crack Free Download 2025
josanj305
 
PDF
GDG Cloud Southlake #44: Eyal Bukchin: Tightening the Kubernetes Feedback Loo...
James Anderson
 
PPTX
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
PDF
Kubernetes - Architecture & Components.pdf
geethak285
 
PPTX
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
PDF
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 
Draugnet: Anonymous Threat Reporting for a World on Fire
treyka
 
Hello I'm "AI" Your New _________________
Dr. Tathagat Varma
 
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
Introducing and Operating FME Flow for Kubernetes in a Large Enterprise: Expe...
Safe Software
 
CapCut Pro PC Crack Latest Version Free Free
josanj305
 
Understanding The True Cost of DynamoDB Webinar
ScyllaDB
 
FME in Overdrive: Unleashing the Power of Parallel Processing
Safe Software
 
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 
Practical Applications of AI in Local Government
OnBoard
 
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
Securing Model Context Protocol with Keycloak: AuthN/AuthZ for MCP Servers
Hitachi, Ltd. OSS Solution Center.
 
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
Wondershare Filmora Crack Free Download 2025
josanj305
 
GDG Cloud Southlake #44: Eyal Bukchin: Tightening the Kubernetes Feedback Loo...
James Anderson
 
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
Kubernetes - Architecture & Components.pdf
geethak285
 
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 

Python basics

  • 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.
  • 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)
  • 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
  • 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.
  • 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)
  • 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
  • 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
  • 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!
  • 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
  • 11. Python Tokens Keywords: You are prevented from using them in a variable name 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 Reserved operators in Python (expressions): + - * ** / // % << >> & | ^ ~ < > <= >= == != <>
  • 12. Python Punctuators • Python punctuation/delimiters ($ and ? not allowed). ‘ “ # ( ) [ ] { } @ , : . ` = ; += -= *= /= //= %= &= |= ^= >>= <<= **=
  • 13. Operators • Integer – addition and subtraction: +, - – multiplication: * – division • quotient: // • remainder: % • Floating point – add, subtract, multiply, divide: +, -, *, /
  • 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)
  • 15. While and For Statements • The for statement is useful 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 * for count in range(4): forward(100) left(90) from turtle import * count=1 while count<=4: forward(100) left(90) count=count+1
  • 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!)
  • 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
  • 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
  • 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”””
  • 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
  • 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
  • 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
  • 23. Basic String Operations • + is concatenation newStr = ‘spam’ + ‘-’ + ‘spam-’ print newStr  spam-spam- • * is repeat, the number is how many times newStr * 3  spam-spam-spam-spam-spam-spam-
  • 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
  • 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.
  • 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
  • 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
  • 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.
  • 30. from turtle import * def draw_square (size): for i in range (4): forward (size) right(90) draw_square(25) draw_square(125) draw_square(75) draw_square(55)