This document provides an outline and overview of key Python concepts including operators, data types, variables, functions, and program flow. It introduces Python as an interpreted programming language with a strict syntax. Operators like +, -, *, / perform actions on operands to produce new values. Data types include integers, floats, booleans and strings. Variables are used to store and reference data. Functions allow for code reuse and abstraction by defining reusable blocks of code. Program flow can be controlled using conditional statements like if/else.
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxpriestmanmable
ISTA 130: Lab 2
1 Turtle Review
Here are all of the turtle functions we have utilized so far in this course:
turtle.forward(distance) – Moves the turtle forward in the direction it is currently facing the distance
entered
turtle.backward(distance) – Same as forward but it moves in the opposite direction the turtle is facing
turtle.right(degrees) – Roates the turtle to the right by the degrees enteres
turtle.left(degrees) – Same as right, but it rotates the turtle to the left
turtle.pensize(size) – Adjusts the size of the line left by the turtle to whatever value is entered for size
turtle.home() – Moves the turtle to the default location and faces it to the right
turtle.clear() – Clears all the lines that were left by the turtle in the window.
turtle.penup() – Causes the turtle to stop leaving lines (until pen is placed back down)
turtle.pendown() – Places the pen back down to the turtle can continue leaving lines when forward and
backward are called.
turtle.pencolor(color string) – Changes the color of the lines left by the turtle to whatever color string
entered (so long as Python recognizes it).
turtle.bgcolor(color string) – Changes the background color for the window that the turtle draws in.
turtle.speed(new speed) – Changes the speed at which the turtle moves to whatever newSpeed is.
turtle.clearscreen() – Deletes all drawings and turtles from the screen, leaving it in its initial state
Note that abbreviations also exist for many of these functions; for example:
� turtle.fd(distance)
� turtle.rt(degrees)
� turtle.pu()
1
2 Functions and Parameters
Here is the square function we looked at yesterday:
def square(side_length):
’’’
Draws a square given a numerical side_length
’’’
turtle.forward(side_length)
turtle.right(90)
turtle.forward(side_length)
turtle.right(90)
turtle.forward(side_length)
turtle.right(90)
turtle.forward(side_length)
turtle.right(90)
return
square(50) # This would give side_length the value of 50
square(100) # This would give side_length the value of 100
print side_length # This will give an error because side_length
# only exists inside the function!
Try it out:
(1 pt.) Create a new file called lab02.py. In this file, create a simple function called rhombus. It
will take one parameter, side length. Using this parameter, have your function create a rhombus
using turtle graphics. Call your rhombus function in the script. What happens if you provide no
arguments to the function? Two or three arguments?
Then, modify your rhombus function so it takes another argument for the angle inside the
rhombus.
3 Data types
Python recognizes many different types of values when working with data. These can be numbers,
strings of characters, or even user defined objects. For the time being, however, were only going to
focus on three of the data types:
integer – These are whole numbers, both positive and negative. Examples are 5000, 0, and -25
float – These are numbers that are followed by a decimal poi ...
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxpriestmanmable
ISTA 130: Lab 2
1 Turtle Review
Here are all of the turtle functions we have utilized so far in this course:
turtle.forward(distance) – Moves the turtle forward in the direction it is currently facing the distance
entered
turtle.backward(distance) – Same as forward but it moves in the opposite direction the turtle is facing
turtle.right(degrees) – Roates the turtle to the right by the degrees enteres
turtle.left(degrees) – Same as right, but it rotates the turtle to the left
turtle.pensize(size) – Adjusts the size of the line left by the turtle to whatever value is entered for size
turtle.home() – Moves the turtle to the default location and faces it to the right
turtle.clear() – Clears all the lines that were left by the turtle in the window.
turtle.penup() – Causes the turtle to stop leaving lines (until pen is placed back down)
turtle.pendown() – Places the pen back down to the turtle can continue leaving lines when forward and
backward are called.
turtle.pencolor(color string) – Changes the color of the lines left by the turtle to whatever color string
entered (so long as Python recognizes it).
turtle.bgcolor(color string) – Changes the background color for the window that the turtle draws in.
turtle.speed(new speed) – Changes the speed at which the turtle moves to whatever newSpeed is.
turtle.clearscreen() – Deletes all drawings and turtles from the screen, leaving it in its initial state
Note that abbreviations also exist for many of these functions; for example:
� turtle.fd(distance)
� turtle.rt(degrees)
� turtle.pu()
1
2 Functions and Parameters
Here is the square function we looked at yesterday:
def square(side_length):
’’’
Draws a square given a numerical side_length
’’’
turtle.forward(side_length)
turtle.right(90)
turtle.forward(side_length)
turtle.right(90)
turtle.forward(side_length)
turtle.right(90)
turtle.forward(side_length)
turtle.right(90)
return
square(50) # This would give side_length the value of 50
square(100) # This would give side_length the value of 100
print side_length # This will give an error because side_length
# only exists inside the function!
Try it out:
(1 pt.) Create a new file called lab02.py. In this file, create a simple function called rhombus. It
will take one parameter, side length. Using this parameter, have your function create a rhombus
using turtle graphics. Call your rhombus function in the script. What happens if you provide no
arguments to the function? Two or three arguments?
Then, modify your rhombus function so it takes another argument for the angle inside the
rhombus.
3 Data types
Python recognizes many different types of values when working with data. These can be numbers,
strings of characters, or even user defined objects. For the time being, however, were only going to
focus on three of the data types:
integer – These are whole numbers, both positive and negative. Examples are 5000, 0, and -25
float – These are numbers that are followed by a decimal poi ...
learn how to program with python
from scratch to be an expert
use the link in the first slide to get the full course
here is the link if you want : https://oke.io/JdxdUl
the link of the documentation : https://oke.io/J6DeY3
link to download python : https://oke.io/BENgRLR2
This first assignment will focus on coding in Python, applying kno.docxabhi353063
This first assignment will focus on coding in Python, applying knowledge students should already have about programming with functions and arrays. When the assignment is complete, there will in fact be some indirect recursion, but that needs not complicate the assignment, if each function is allowed to assume that all other functions are implemented correctly.
Problem Description
Several years of experience in algebra probably yields a consistent interpretation of the expression
12 - 2 * 5 +3
Most would expect that the multiplication would be the first operation, followed by a subtraction, and then an addition, yielding a value of 5. Performing those three operations in any other order would yield very different results.
When a programmer places such an expression into a program, they would expect it to perform the same series of operations. The interpreter or compiler making sense of the expression then must be able to construct the correct meaning of the input. Often one will hear of this behavior called
parsing
.
Assignment Specifications
The input for this assignment will arrive as an instantiated
Python list
consisting of
tokens
, where each token is either an integer numeral or an operator. An additional symbol (such as a semicolon) will appear at the end of the list to mark the end of the input.
The Python list has a great deal in common with the C++ array, and this assignment will treat it as such. One will be able to use an integer subscript to examine each element of the list, just as one could examine consecutive array elements. The next assignment will use a different approach to visit the elements of the list.
Implementation Hints
One very simple method of parsing input is termed
predictive parsing
in which each function has an idea of what it expects to see next (or what alternatives it will encounter). For example, we would expect a numeric expression like the one above to include a series of values to be added or subtracted. Whether those values are explicit numbers (such as 12 and 3) or the results of other operations (such as 2*5) might sound like a complication, but that can just be addressed by some other function.
The pseudocode for parsing a sum expression would therefore look something like this:
to evaluate a sum expression (series of zero or more additions and subtractions): evaluate a product expression (zero or more multiplications and divisions) while the next token is a + or - operator evaluate the product expression that follows the operator perform the addition or subtraction
For the given example, the first product expression would simply be the value 12. This is followed by a minus sign, so the next product is evaluated to be 10, which is subtracted from 12 to yield 2. Since this is followed by a plus sign, the loop would repeat to evaluate and add the 3. No more operators appear, so the final result is 5.
The above specifications said that some other symbol would appear at the very end of the input. Thi ...
learn how to program with python
from scratch to be an expert
use the link in the first slide to get the full course
here is the link if you want : https://oke.io/JdxdUl
the link of the documentation : https://oke.io/J6DeY3
link to download python : https://oke.io/BENgRLR2
This first assignment will focus on coding in Python, applying kno.docxabhi353063
This first assignment will focus on coding in Python, applying knowledge students should already have about programming with functions and arrays. When the assignment is complete, there will in fact be some indirect recursion, but that needs not complicate the assignment, if each function is allowed to assume that all other functions are implemented correctly.
Problem Description
Several years of experience in algebra probably yields a consistent interpretation of the expression
12 - 2 * 5 +3
Most would expect that the multiplication would be the first operation, followed by a subtraction, and then an addition, yielding a value of 5. Performing those three operations in any other order would yield very different results.
When a programmer places such an expression into a program, they would expect it to perform the same series of operations. The interpreter or compiler making sense of the expression then must be able to construct the correct meaning of the input. Often one will hear of this behavior called
parsing
.
Assignment Specifications
The input for this assignment will arrive as an instantiated
Python list
consisting of
tokens
, where each token is either an integer numeral or an operator. An additional symbol (such as a semicolon) will appear at the end of the list to mark the end of the input.
The Python list has a great deal in common with the C++ array, and this assignment will treat it as such. One will be able to use an integer subscript to examine each element of the list, just as one could examine consecutive array elements. The next assignment will use a different approach to visit the elements of the list.
Implementation Hints
One very simple method of parsing input is termed
predictive parsing
in which each function has an idea of what it expects to see next (or what alternatives it will encounter). For example, we would expect a numeric expression like the one above to include a series of values to be added or subtracted. Whether those values are explicit numbers (such as 12 and 3) or the results of other operations (such as 2*5) might sound like a complication, but that can just be addressed by some other function.
The pseudocode for parsing a sum expression would therefore look something like this:
to evaluate a sum expression (series of zero or more additions and subtractions): evaluate a product expression (zero or more multiplications and divisions) while the next token is a + or - operator evaluate the product expression that follows the operator perform the addition or subtraction
For the given example, the first product expression would simply be the value 12. This is followed by a minus sign, so the next product is evaluated to be 10, which is subtracted from 12 to yield 2. Since this is followed by a plus sign, the loop would repeat to evaluate and add the 3. No more operators appear, so the final result is 5.
The above specifications said that some other symbol would appear at the very end of the input. Thi ...
A Strategic Approach: GenAI in EducationPeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
Introduction to AI for Nonprofits with Tapp NetworkTechSoup
Dive into the world of AI! Experts Jon Hill and Tareq Monaur will guide you through AI's role in enhancing nonprofit websites and basic marketing strategies, making it easy to understand and apply.
How to Make a Field invisible in Odoo 17Celine George
It is possible to hide or invisible some fields in odoo. Commonly using “invisible” attribute in the field definition to invisible the fields. This slide will show how to make a field invisible in odoo 17.
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
Biological screening of herbal drugs: Introduction and Need for
Phyto-Pharmacological Screening, New Strategies for evaluating
Natural Products, In vitro evaluation techniques for Antioxidants, Antimicrobial and Anticancer drugs. In vivo evaluation techniques
for Anti-inflammatory, Antiulcer, Anticancer, Wound healing, Antidiabetic, Hepatoprotective, Cardio protective, Diuretics and
Antifertility, Toxicity studies as per OECD guidelines
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...Levi Shapiro
Letter from the Congress of the United States regarding Anti-Semitism sent June 3rd to MIT President Sally Kornbluth, MIT Corp Chair, Mark Gorenberg
Dear Dr. Kornbluth and Mr. Gorenberg,
The US House of Representatives is deeply concerned by ongoing and pervasive acts of antisemitic
harassment and intimidation at the Massachusetts Institute of Technology (MIT). Failing to act decisively to ensure a safe learning environment for all students would be a grave dereliction of your responsibilities as President of MIT and Chair of the MIT Corporation.
This Congress will not stand idly by and allow an environment hostile to Jewish students to persist. The House believes that your institution is in violation of Title VI of the Civil Rights Act, and the inability or
unwillingness to rectify this violation through action requires accountability.
Postsecondary education is a unique opportunity for students to learn and have their ideas and beliefs challenged. However, universities receiving hundreds of millions of federal funds annually have denied
students that opportunity and have been hijacked to become venues for the promotion of terrorism, antisemitic harassment and intimidation, unlawful encampments, and in some cases, assaults and riots.
The House of Representatives will not countenance the use of federal funds to indoctrinate students into hateful, antisemitic, anti-American supporters of terrorism. Investigations into campus antisemitism by the Committee on Education and the Workforce and the Committee on Ways and Means have been expanded into a Congress-wide probe across all relevant jurisdictions to address this national crisis. The undersigned Committees will conduct oversight into the use of federal funds at MIT and its learning environment under authorities granted to each Committee.
• The Committee on Education and the Workforce has been investigating your institution since December 7, 2023. The Committee has broad jurisdiction over postsecondary education, including its compliance with Title VI of the Civil Rights Act, campus safety concerns over disruptions to the learning environment, and the awarding of federal student aid under the Higher Education Act.
• The Committee on Oversight and Accountability is investigating the sources of funding and other support flowing to groups espousing pro-Hamas propaganda and engaged in antisemitic harassment and intimidation of students. The Committee on Oversight and Accountability is the principal oversight committee of the US House of Representatives and has broad authority to investigate “any matter” at “any time” under House Rule X.
• The Committee on Ways and Means has been investigating several universities since November 15, 2023, when the Committee held a hearing entitled From Ivory Towers to Dark Corners: Investigating the Nexus Between Antisemitism, Tax-Exempt Universities, and Terror Financing. The Committee followed the hearing with letters to those institutions on January 10, 202
Embracing GenAI - A Strategic ImperativePeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
2. 2
Outline
Introduction to Python
Operators & Expressions
Data Types & Type Conversion
Variables: Names for data
Functions
Program Flow (Branching)
Input from the user
Iteration (Looping)
3. 3
Introduction to Python
Python is an interpreted programming language
A program is a set of instructions telling the computer what
to do.
It has a strict syntax, and will only recognize very specific
statements. If the interpreter does not recognize what you
have typed, it will complain until you fix it.
4. 4
Operators
Python has many operators. Some examples are:
+, -, *, /, %, >, <, ==
print
Operators perform an action on one or more operands.
Some operators accept operands before and after
themselves:
operand1 + operand2, or 3 + 5
Others are followed by one or more operands until the end
of the line, such as: print “Hi!”, 32, 48
When operators are evaluated, they perform action on
their operands, and produce a new value.
5. 5
Example Expression Evaluations
An expression is any set of values and operators that will
produce a new value when evaluated. Here are some
examples, along with the new value they produce when
evaluated:
5 + 10 produces 15
“Hi” + “ “ + “Jay!” produces “Hi Jay!”
10 / (2+3) produces 2
10 > 5 produces True
10 < 5 produces False
10 / 3.5 produces 2.8571428571
10 // 3 produces 3
10 % 3 produces 1
6. 6
List of Operators: +, -, *, /, <, >, <=, >=, ==, %, //
Some operators should be familiar from the world of
mathematics such as Addition (+), Subtraction (-),
Multiplication (*), and Division (/).
Python also has comparison operators, such as Less-
Than (<), Greater-Than (>), Less-Than-or-Equal(<=),
Greater-Than-or-Equal (>=), and Equality-Test (==). These
operators produce a True or False value.
A less common operator is the Modulo operator (%),
which gives the remainder of an integer division. 10
divided by 3 is 9 with a remainder of 1:
10 // 3 produces 3, while 10 % 3 produces 1
7. 7
DANGER! Operator Overloading!
NOTE! Some operators will work in a different way
depending upon what their operands are. For example,
when you add two numbers you get the expected result: 3
+ 3 produces 6.
But if you “add” two or more strings, the + operator
produces a concatenated version of the strings: “Hi” +
“Jay” produces “HiJay”
Multiplying strings by a number repeats the string!
“Hi Jay” * 3 produces “Hi JayHi JayHiJay”
The % sign also works differently with strings:
“test %f” % 34 produces “test 34”
8. 8
Data Types
In Python, all data has an associated data “Type”.
You can find the “Type” of any piece of data by using the
type() function:
type( “Hi!”) produces <type 'str'>
type( True ) produces <type 'bool'>
type( 5) produces <type 'int'>
type(5.0) produces <type 'float'>
Note that python supports two different types of numbers,
Integers (int) and Floating point numbers (float). Floating
Point numbers have a fractional part (digits after the
decimal place), while Integers do not!
9. 9
Effect of Data Types on Operator Results
Math operators work differently on Floats and Ints:
int + int produces an int
int + float or float + int produces a float
This is especially important for division, as integer division
produces a different result from floating point division:
10 // 3 produces 3
10 / 3 produces 3.3333
10.0 / 3.0 produces 3.3333333
Other operators work differently on different data types: +
(addition) will add two numbers, but concatenate strings.
10. 10
Simple Data types in Python
The simple data types in Python are:
Numbers
int – Integer: -5, 10, 77
float – Floating Point numbers: 3.1457, 0.34
bool – Booleans (True or False)
Strings are a more complicated data type (called
Sequences) that we will discuss more later. They are
made up of individual letters (strings of length 1)
11. 11
Type Conversion
Data can sometimes be converted from one type to
another. For example, the string “3.0” is equivalent to the
floating point number 3.0, which is equivalent to the
integer number 3
Functions exist which will take data in one type and return
data in another type.
int() - Converts compatible data into an integer. This
function will truncate floating point numbers
float() - Converts compatible data into a float.
str() - Converts compatible data into a string.
Examples:
int(3.3) produces 3 str(3.3) produces “3.3”
float(3) produces 3.0 float(“3.5”) produces 3.5
int(“7”) produces 7
int(“7.1”) throws an ERROR!
float(“Test”) Throws an ERROR!
12. 12
Variables
Variables are names that can point to data.
They are useful for saving intermediate results and
keeping data organized.
The assignment operator (=) assigns data to variables.
Don't confuse the assignment operator (single equal sign, =)
with the Equality-Test operator (double equal sign, ==)
Variable names can be made up of letters, numbers and
underscores (_), and must start with a letter.
13. 13
Variables
When a variable is evaluated, it produces the value of the
data that it points to.
For example:
myVariable = 5
myVariable produces 5
myVariable + 10 produces 15
You MUST assign something to a variable (to create the
variable name) before you try to use (evaluate) it.
14. 14
Program Example
Find the area of a circle given the radius:
Radius = 10
pi = 3.14159
area = pi * Radius * Radius
print( area )
will print 314.15 to the screen.
15. 15
Code Abstraction & Reuse Functions
If you want to do something (like calculate the area of a
circle) multiple times, you can encapsulate the code inside
of a Function.
A Function is a named sequence of statements that
perform some useful operation. Functions may or may not
take parameters, and may or may not return results.
Syntax:
def NAME( LIST OF PARAMETERS):
STATEMENTS
STATEMENTS
16. 16
How to use a function
You can cause a function to execute by “calling” it as
follows:
functionName( Parameters)
You can optionally assign any result that the function
returns to a variable using the assignment operator:
returnResult = functionName(Parameters)
17. 17
Indentation is IMPORTANT!
A function is made up of two main parts, the Header, and
the Body.
The function header consists of:
def funcName(param1,param2):
def keyword
function name
zero or more parameters, comma separated, inside of
parenthesis ()
A colon :
The function body consists of all statements in the block
that directly follows the header.
A block is made up of statements that are at the same
indentation level.
18. 18
findArea function naive example
def findArea( ):
Radius = 10
pi = 3.1459
area = pi * Radius * Radius
print(area)
This function will ONLY calculate the area of a circle with a
radius of 10!
This function will PRINT the area to the screen, but will
NOT return the value pointed to by the area variable.
19. 19
findArea function, with syntax error!
def findArea( ):
Radius = 10
pi = 3.1459
area = pi * Radius * Radius
print(area)
You can NOT mix indentation levels within the same block!
The above code will result in a syntax error!
20. 20
What's wrong with findArea – Limited Applicability
def findArea( ):
Radius = 10
pi = 3.1459
area = pi * Radius * Radius
print(area)
It will only work for circles of size 10!
We need to make this function more general!
Step 1: Use parameters to accept the radius of any sized
circle!
21. 21
findArea function better example
def findArea( Radius ):
pi = 3.1459
area = pi * Radius * Radius
print( area)
This function will work with any sized circle!
This function will PRINT the area to the screen, but will
NOT return the value pointed to by the area variable.
22. 22
What's wrong with findArea
findArea(10) prints 314.59 to the screen
findArea(15) prints 707.8275 to the screen
myArea = findArea(10) will assign “None” to the
myArea variable. (Due to the lack of an explicit return
statement, the function only prints the value, and does not
return it.)
We need to make this function return the value it
calculates!
Step 2: Use a return statement to return the calculated
area!
23. 23
findArea function best example
def findArea( Radius ):
pi = 3.1459
area = pi * Radius * Radius
return area
This function will work with any sized circle!
This function will return the area found, but will NOT print it
to the screen. If we want to print the value, we must print it
ourselves:
circleArea = findArea(15)
print circleArea
Note the use of the circleArea variable to hold the result of
our findArea function call.
24. 24
Keywords, Name-spaces & Scope
In Python, not all names are equal.
Some names are reserved by the system and are already
defined. Examples are things like: def, print, if, else, while,
for, in, and, or, not, return. These names are built in
keywords.
Names that are defined in a function are “local” to that
function.
Names that are defined outside of a function are “global”
to the module.
Local names overshadow global names when inside the
function that defined them.
If you want to access a global variable from inside of a
function, you should declare it “global”.
25. 25
Global vs Local example
myVariable = 7
myParam = 20
def func1(myParam):
myVariable = 20
print(myParam)
func1(5)
print(myVariable)
What gets printed? 5 and 7
The “local” myVariable inside func1 is separate from (and
overshadows) the “global” myVariable outside of func1
The “local” myParam inside func1 is different from the
“global” myParam defined at the top.
26. 26
Global vs Local example – part 2
myVariable = 7
myParam = 20
def func1(myParam):
global myVariable
myVariable = 20
print(myParam)
func1(5)
print(myVariable)
What gets printed? 5 and 20
The “local” myVariable inside func1 is separate from the
“global” myVariable outside of func1
The function assigns 20 to the “global” myVariable,
overwriting the 7 before it gets printed.
27. 27
Making Decisions – Controlling Program Flow
To make interesting programs, you must be able to make
decisions about data and take different actions based
upon those decisions.
The IF statement allows you to conditionally execute a
block of code.
The syntax of the IF statement is as follows:
if boolean_expression :
STATEMENT
STATEMENT
The indented block of code following an if statement is
executed if the boolean expression is true, otherwise it is
skipped.
28. 28
IF statement - example
numberOfWheels = 3
if ( numberOfWheels < 4):
print(“You don't have enough wheels!”)
print(“I'm giving you 4 wheels!”)
numberOfWheels = 4
print(“You now have”, numberOfWheels,
“wheels”)
The last print statement is executed no matter what. The
first two print statements and the assignment of 4 to the
numberOfWheels is only executed if numberOfWheels is
less than 4.
29. 29
IF/ELSE
If you have two mutually exclusive choices, and want to
guarantee that only one of them is executed, you can use
an IF/ELSE statement. The ELSE statement adds a
second block of code that is executed if the boolean
expression is false.
if boolean_expression :
STATEMENT
STATEMENT
else:
STATEMENT
STATEMENT
30. 30
IF/ELSE statement - example
numberOfWheels = 3
if ( numberOfWheels < 3):
print(“You are a motorcycle!”)
else:
print(“You are a Car!”)
print(“You have”, numberOfWheels, “wheels”)
The last print statement is executed no matter what. If
numberOfWheels is less than 3, it's called a motorcycle,
otherwise it's called a car!
31. 31
IF/ELIF/ELSE
If you have several mutually exclusive choices, and want
to guarantee that only one of them is executed, you can
use an IF/ELIF/ELSE statements. The ELIF statement
adds another boolean expression test and another block
of code that is executed if the boolean expression is true.
if boolean_expression :
STATEMENT
STATEMENT
elif 2nd_
boolean_expression ):
STATEMENT
STATEMENT
else:
STATEMENT
STATEMENT
32. 32
IF/ELSE statement - example
numberOfWheels = 3
if ( numberOfWheels == 1):
print(“You are a Unicycle!”)
elif (numberOfWheels == 2):
print(“You are a Motorcycle!”)
elif (numberOfWheels == 3):
print(“You are a Tricycle!”)
elif (numberOfWheels == 4):
print(“You are a Car!”)
else:
print(“That's a LOT of wheels!”)
Only the print statement from the first true boolean
expression is executed.
33. 33
IF/ELSE statement – example – Semantic error!
numberOfWheels = 3
if ( numberOfWheels == 1):
print(“You are a Unicycle!”)
elif (numberOfWheels > 1 ):
print(“You are a Motorcycle!”)
elif (numberOfWheels > 2):
print(“You are a tricycle!”)
elif (numberOfWheels > 3):
print(“You are a Car!”)
else:
print(“That's a LOT of wheels!”)
What's wrong with testing using the greater-than operator?
34. 34
Getting input from the User
Your program will be more interesting if we obtain some
input from the user.
But be careful! The user may not always give you the
input that you wanted, or expected!
A function that is useful for getting input from the user is:
input(<prompt string>) - always returns a string
You must convert the string to a float/int if you want to do
math with it!
35. 35
Input Example – possible errors from the input() function
userName = input(“What is your name?”)
userAge = int( input(“How old are you?”) )
birthYear = 2007 - userAge
print(“Nice to meet you, “ + userName)
print(“You were born in: “, birthYear)
input() is guaranteed to give us a string, no matter
WHAT the user enters.
But what happens if the user enters “ten” for their age
instead of 10?
36. 36
Input Example – possible errors from the input() function
userName = raw_input(“What is your name?”)
userAge = input(“How old are you?”)
try:
userAgeInt = int(userAge)
except:
userAgeInt = 0
birthYear = 2010 - userAgeInt
print(“Nice to meet you, “ + userName)
if userAgeInt != 0:
print(“You were born in: “, birthYear )
The try/except statements protects us if the user enters
something other than a number. If the int() function is
unable to convert whatever string the user entered, the
except clause will set the userIntAge variable to zero.
37. 37
Repetition can be useful!
Sometimes you want to do the same thing several times.
Or do something very similar many times.
One way to do this is with repetition:
print 1
print 2
print 3
print 4
print 5
print 6
print 7
print 8
print 9
print 10
38. 38
Looping, a better form of repetition.
Repetition is OK for small numbers, but when you have to
do something many, many times, it takes a very long time
to type all those commands.
We can use a loop to make the computer do the work for
us.
One type of loop is the “while” loop. The while loop
repeats a block of code until a boolean expression is no
longer true.
Syntax:
while boolean expression :
STATEMENT
STATEMENT
STATEMENT
39. 39
How to STOP looping!
It is very easy to loop forever:
while True :
print( “again, and again, and again”)
The hard part is to stop the loop!
Two ways to do that is by using a loop counter, or a
termination test.
A loop counter is a variable that keeps track of how many
times you have gone through the loop, and the boolean
expression is designed to stop the loop when a specific
number of times have gone bye.
A termination test checks for a specific condition, and when
it happens, ends the loop. (But does not guarantee that the
loop will end.)
40. 40
Loop Counter
timesThroughLoop = 0
while (timesThroughLoop < 10):
print(“This is time”, timesThroughLoop,
“in the loop.”)
timesThroughLoop = timesThroughLoop + 1
Notice that we:
Initialize the loop counter (to zero)
Test the loop counter in the boolean expression (is it smaller
than 10, if yes, keep looping)
Increment the loop counter (add one to it) every time we go
through the loop
If we miss any of the three, the loop will NEVER stop!
41. 41
While loop example, with a termination test
Keeps asking the user for their name, until the user types
“quit”.
keepGoing = True
while ( keepGoing):
userName = input(“Enter your name! (or
quit to exit)” )
if userName == “quit”:
keepGoing = False
else:
print(“Nice to meet you, “ + userName)
print(“Goodbye!”)
42. 42
The End!
Next up – Python Review 2 – Compound Data Types and
programming tricks..