SlideShare a Scribd company logo
1 of 30
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.
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

Algorithm analysis and design
Algorithm analysis and designAlgorithm analysis and design
Algorithm analysis and designMegha V
 
Type header file in c++ and its function
Type header file in c++ and its functionType header file in c++ and its function
Type header file in c++ and its functionFrankie Jones
 
Matlab Functions
Matlab FunctionsMatlab Functions
Matlab FunctionsUmer Azeem
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Edureka!
 
Python programming –part 3
Python programming –part 3Python programming –part 3
Python programming –part 3Megha V
 
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programmingVisnuDharsini
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++Neeru Mittal
 

What's hot (13)

Python for Beginners(v2)
Python for Beginners(v2)Python for Beginners(v2)
Python for Beginners(v2)
 
C
CC
C
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
 
scripting in Python
scripting in Pythonscripting in Python
scripting in Python
 
Algorithm analysis and design
Algorithm analysis and designAlgorithm analysis and design
Algorithm analysis and design
 
Type header file in c++ and its function
Type header file in c++ and its functionType header file in c++ and its function
Type header file in c++ and its function
 
Python programming
Python  programmingPython  programming
Python programming
 
Matlab Functions
Matlab FunctionsMatlab Functions
Matlab Functions
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
Python programming –part 3
Python programming –part 3Python programming –part 3
Python programming –part 3
 
Strings v.1.1
Strings v.1.1Strings v.1.1
Strings v.1.1
 
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programming
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
 

Viewers also liked

Η Αφαλάτωση Νερού Ως Συνειδητή Επιλογή | aqualifegreece.gr
Η Αφαλάτωση Νερού Ως Συνειδητή Επιλογή | aqualifegreece.grΗ Αφαλάτωση Νερού Ως Συνειδητή Επιλογή | aqualifegreece.gr
Η Αφαλάτωση Νερού Ως Συνειδητή Επιλογή | aqualifegreece.grAqualife Gr
 
Camino de Arboles
Camino de ArbolesCamino de Arboles
Camino de Arbolesma_19robles
 
Data mining maximumlikelihood
Data mining maximumlikelihoodData mining maximumlikelihood
Data mining maximumlikelihoodJames Wong
 
4 Things to Consider When Choosing a Payroll Provider
4 Things to Consider When Choosing a Payroll Provider4 Things to Consider When Choosing a Payroll Provider
4 Things to Consider When Choosing a Payroll ProviderInfinisource
 
3de3.Metodos en la investigación científica. Enfoque cualitativo
3de3.Metodos en la investigación científica. Enfoque cualitativo3de3.Metodos en la investigación científica. Enfoque cualitativo
3de3.Metodos en la investigación científica. Enfoque cualitativoEdison Coimbra G.
 
2.Recolección y analisis de datos cualitativos
2.Recolección y analisis de datos cualitativos2.Recolección y analisis de datos cualitativos
2.Recolección y analisis de datos cualitativosEdison Coimbra G.
 
Estructura del proyecto de grado
Estructura del proyecto de gradoEstructura del proyecto de grado
Estructura del proyecto de gradoEdison Coimbra G.
 

Viewers also liked (13)

Moamen CV final eng
Moamen CV final engMoamen CV final eng
Moamen CV final eng
 
Kerry's Resume4
Kerry's Resume4Kerry's Resume4
Kerry's Resume4
 
Foros
Foros Foros
Foros
 
Η Αφαλάτωση Νερού Ως Συνειδητή Επιλογή | aqualifegreece.gr
Η Αφαλάτωση Νερού Ως Συνειδητή Επιλογή | aqualifegreece.grΗ Αφαλάτωση Νερού Ως Συνειδητή Επιλογή | aqualifegreece.gr
Η Αφαλάτωση Νερού Ως Συνειδητή Επιλογή | aqualifegreece.gr
 
Camino de Arboles
Camino de ArbolesCamino de Arboles
Camino de Arboles
 
Diamonds 57010836 and 57011272
Diamonds 57010836 and 57011272Diamonds 57010836 and 57011272
Diamonds 57010836 and 57011272
 
Arquitectura barroca
Arquitectura barrocaArquitectura barroca
Arquitectura barroca
 
Data mining maximumlikelihood
Data mining maximumlikelihoodData mining maximumlikelihood
Data mining maximumlikelihood
 
4 Things to Consider When Choosing a Payroll Provider
4 Things to Consider When Choosing a Payroll Provider4 Things to Consider When Choosing a Payroll Provider
4 Things to Consider When Choosing a Payroll Provider
 
24280
2428024280
24280
 
3de3.Metodos en la investigación científica. Enfoque cualitativo
3de3.Metodos en la investigación científica. Enfoque cualitativo3de3.Metodos en la investigación científica. Enfoque cualitativo
3de3.Metodos en la investigación científica. Enfoque cualitativo
 
2.Recolección y analisis de datos cualitativos
2.Recolección y analisis de datos cualitativos2.Recolección y analisis de datos cualitativos
2.Recolección y analisis de datos cualitativos
 
Estructura del proyecto de grado
Estructura del proyecto de gradoEstructura del proyecto de grado
Estructura del proyecto de grado
 

Similar to Python basics

Python language data types
Python language data typesPython language data types
Python language data typesHarry Potter
 
Python language data types
Python language data typesPython language data types
Python language data typesHoang Nguyen
 
Python language data types
Python language data typesPython language data types
Python language data typesFraboni Ec
 
Python language data types
Python language data typesPython language data types
Python language data typesJames Wong
 
Python language data types
Python language data typesPython language data types
Python language data typesYoung Alista
 
Python language data types
Python language data typesPython language data types
Python language data typesTony Nguyen
 
Python language data types
Python language data typesPython language data types
Python language data typesLuis Goldster
 
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptxsangeeta borde
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methodsPranavSB
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdflailoesakhan
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptRajasekhar364622
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
 
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.docxpriestmanmable
 
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
 
Unit I - 1R introduction to R program.pptx
Unit I - 1R introduction to R program.pptxUnit I - 1R introduction to R program.pptx
Unit I - 1R introduction to R program.pptxSreeLaya9
 

Similar to Python basics (20)

Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python.pdf
Python.pdfPython.pdf
Python.pdf
 
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
 
Aggregate.pptx
Aggregate.pptxAggregate.pptx
Aggregate.pptx
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
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
 
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 I - 1R introduction to R program.pptx
Unit I - 1R introduction to R program.pptxUnit I - 1R introduction to R program.pptx
Unit I - 1R introduction to R program.pptx
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Python
PythonPython
Python
 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
 

More from James Wong

Multi threaded rtos
Multi threaded rtosMulti threaded rtos
Multi threaded rtosJames Wong
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data miningJames Wong
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discoveryJames Wong
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data miningJames Wong
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching worksJames Wong
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsJames Wong
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherenceJames Wong
 
Abstract data types
Abstract data typesAbstract data types
Abstract data typesJames Wong
 
Abstraction file
Abstraction fileAbstraction file
Abstraction fileJames Wong
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cacheJames Wong
 
Abstract class
Abstract classAbstract class
Abstract classJames Wong
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysisJames Wong
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaJames Wong
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsJames Wong
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and pythonJames Wong
 

More from James Wong (20)

Data race
Data raceData race
Data race
 
Multi threaded rtos
Multi threaded rtosMulti threaded rtos
Multi threaded rtos
 
Recursion
RecursionRecursion
Recursion
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data mining
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discovery
 
Cache recap
Cache recapCache recap
Cache recap
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data mining
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
 
Object model
Object modelObject model
Object model
 
Abstract class
Abstract classAbstract class
Abstract class
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
 
Inheritance
InheritanceInheritance
Inheritance
 

Recently uploaded

"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsAndrey Dotsenko
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 

Recently uploaded (20)

"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 

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.
  • 29.
  • 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)