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

Presentation on python
Presentation on pythonPresentation on python
Presentation on pythonwilliam john
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in PythonSumit Satam
 
Python Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | EdurekaPython Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | EdurekaEdureka!
 
Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming KrishnaMildain
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programmingSrinivas Narasegouda
 
Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Learn Python Programming | Python Programming - Step by Step | Python for Beg...Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Learn Python Programming | Python Programming - Step by Step | Python for Beg...Edureka!
 
python Function
python Function python Function
python Function Ronak Rathi
 
Python Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaPython Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaEdureka!
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in pythonRaginiJain21
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptxAkshayAggarwal79
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide shareDevashish Kumar
 
Programming in Python
Programming in Python Programming in Python
Programming in Python Tiji Thomas
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in pythonLifna C.S
 
File Handling Python
File Handling PythonFile Handling Python
File Handling PythonAkhil Kaushik
 

What's hot (20)

Presentation on python
Presentation on pythonPresentation on python
Presentation on python
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in Python
 
Python Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | EdurekaPython Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | Edureka
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Learn Python Programming | Python Programming - Step by Step | Python for Beg...Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Learn Python Programming | Python Programming - Step by Step | Python for Beg...
 
python Function
python Function python Function
python Function
 
Python Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaPython Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | Edureka
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in python
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptx
 
Python ppt
Python pptPython ppt
Python ppt
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Programming in Python
Programming in Python Programming in Python
Programming in Python
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in python
 
Python made easy
Python made easy Python made easy
Python made easy
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
 

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 basics
Python basicsPython basics
Python basics
 
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
 
Python ppt
Python pptPython ppt
Python ppt
 
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
 

More from Hoang Nguyen

Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your siteHoang Nguyen
 
How to build a rest api
How to build a rest apiHow to build a rest api
How to build a rest apiHoang Nguyen
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsHoang Nguyen
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching worksHoang Nguyen
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cacheHoang Nguyen
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherenceHoang Nguyen
 
Python your new best friend
Python your new best friendPython your new best friend
Python your new best friendHoang Nguyen
 
Programming for engineers in python
Programming for engineers in pythonProgramming for engineers in python
Programming for engineers in pythonHoang Nguyen
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with pythonHoang Nguyen
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and pythonHoang Nguyen
 
Object oriented programming using c++
Object oriented programming using c++Object oriented programming using c++
Object oriented programming using c++Hoang Nguyen
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysisHoang Nguyen
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsHoang Nguyen
 
Data abstraction the walls
Data abstraction the wallsData abstraction the walls
Data abstraction the wallsHoang Nguyen
 
Data abstraction and object orientation
Data abstraction and object orientationData abstraction and object orientation
Data abstraction and object orientationHoang Nguyen
 

More from Hoang Nguyen (20)

Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your site
 
How to build a rest api
How to build a rest apiHow to build a rest api
How to build a rest api
 
Api crash
Api crashApi crash
Api crash
 
Smm and caching
Smm and cachingSmm and caching
Smm and caching
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
 
Cache recap
Cache recapCache recap
Cache recap
 
Python your new best friend
Python your new best friendPython your new best friend
Python your new best friend
 
Programming for engineers in python
Programming for engineers in pythonProgramming for engineers in python
Programming for engineers in python
 
Learning python
Learning pythonLearning python
Learning python
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with python
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
 
Object oriented programming using c++
Object oriented programming using c++Object oriented programming using c++
Object oriented programming using c++
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
 
Object model
Object modelObject model
Object model
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Data abstraction the walls
Data abstraction the wallsData abstraction the walls
Data abstraction the walls
 
Data abstraction and object orientation
Data abstraction and object orientationData abstraction and object orientation
Data abstraction and object orientation
 

Recently uploaded

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
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
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
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
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
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
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 

Recently uploaded (20)

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
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
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
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
 
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
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
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
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
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...
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 

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)