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

Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data miningTony Nguyen
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with pythonTony Nguyen
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and pythonTony 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 siteTony Nguyen
 
Python your new best friend
Python your new best friendPython your new best friend
Python your new best friendTony Nguyen
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsTony Nguyen
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching worksTony Nguyen
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsTony Nguyen
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data miningTony Nguyen
 
How to build a rest api
How to build a rest apiHow to build a rest api
How to build a rest apiTony Nguyen
 
Encapsulation anonymous class
Encapsulation anonymous classEncapsulation anonymous class
Encapsulation anonymous classTony Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaTony Nguyen
 
Abstract data types
Abstract data typesAbstract data types
Abstract data typesTony Nguyen
 

Viewers also liked (19)

Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data mining
 
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
 
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
 
Python your new best friend
Python your new best friendPython your new best friend
Python your new best friend
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
 
Inheritance
InheritanceInheritance
Inheritance
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
 
Learning python
Learning pythonLearning python
Learning python
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data mining
 
Api crash
Api crashApi crash
Api crash
 
Abstract class
Abstract classAbstract class
Abstract class
 
How to build a rest api
How to build a rest apiHow to build a rest api
How to build a rest api
 
Encapsulation anonymous class
Encapsulation anonymous classEncapsulation anonymous class
Encapsulation anonymous class
 
Cache recap
Cache recapCache recap
Cache recap
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Poo java
Poo javaPoo java
Poo java
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 

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 Tony Nguyen

Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysisTony Nguyen
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherenceTony Nguyen
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discoveryTony Nguyen
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cacheTony Nguyen
 
Abstraction file
Abstraction fileAbstraction file
Abstraction fileTony Nguyen
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_javaTony Nguyen
 
Programming for engineers in python
Programming for engineers in pythonProgramming for engineers in python
Programming for engineers in pythonTony Nguyen
 
Data preprocessing
Data preprocessingData preprocessing
Data preprocessingTony Nguyen
 

More from Tony Nguyen (10)

Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discovery
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Object model
Object modelObject model
Object model
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_java
 
Programming for engineers in python
Programming for engineers in pythonProgramming for engineers in python
Programming for engineers in python
 
Smm and caching
Smm and cachingSmm and caching
Smm and caching
 
Data preprocessing
Data preprocessingData preprocessing
Data preprocessing
 

Recently uploaded

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
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
 
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
 
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
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
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
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
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
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
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
 
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
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
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
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
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
 
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
 

Recently uploaded (20)

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic 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
 
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
 
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
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
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
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
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
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
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...
 
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
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
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
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
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
 
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)
 
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
 

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)