This document provides an introduction to Python programming using the Raspberry Pi. It covers basic Python syntax like variables, strings, lists and loops. It shows how to perform calculations and manipulate data. Lists can store multiple values and items can be accessed by index. Loops allow automated repetition, like printing each item in a grocery list. Overall, the document teaches Python fundamentals like data types, variables, operators, functions and basic programming structures.
Teaching Notes (extremely technical) detailing my Raspberry Pi program. This is for the third set of classes, where we taught the Python coding language along with logic structure. This is the first class, showing the basics of Python.
Python 101++: Let's Get Down to Business!Paige Bailey
You've started the Codecademy and Coursera courses; you've thumbed through Zed Shaw's "Learn Python the Hard Way"; and now you're itching to see what Python can help you do. This is the workshop for you!
Here's the breakdown: we're going to be taking you on a whirlwind tour of Python's capabilities. By the end of the workshop, you should be able to easily follow any of the widely available Python courses on the internet, and have a grasp on some of the more complex aspects of the language.
Please don't forget to bring your personal laptop!
Audience: This course is aimed at those who already have some basic programming experience, either in Python or in another high level programming language (such as C/C++, Fortran, Java, Ruby, Perl, or Visual Basic). If you're an absolute beginner -- new to Python, and new to programming in general -- make sure to check out the "Python 101" workshop!
Python is a high-level, interpreted programming language that is designed to be easy to read and write. It has a clear syntax using English keywords and its code is often shorter than languages like C++ and Java. Python is widely used for web development, software development, science, and machine learning. It has a large standard library and can be extended through modules. Some key data structures in Python include lists, tuples, and dictionaries.
The basics of Python are rather straightforward. In a few minutes you can learn most of the syntax. There are some gotchas along the way that might appear tricky. This talk is meant to bring programmers up to speed with Python. They should be able to read and write Python.
This document provides an introduction to Python programming using PyCharm. It discusses downloading and installing Python and PyCharm, creating and running simple Python scripts that use print statements and variables, taking user input, and introducing conditional logic using if/else statements and while loops. Examples include printing ASCII art, basic math operations, and building a text-based choose your own adventure game. Further exercises are suggested to improve the game by adding dice rolls and more options.
Python was created in the late 1980s by Guido van Rossum and first released in 1991. It gained popularity and saw new releases in 2000 and 2008. Python is an open source, general purpose, interpreted, object-oriented programming language used widely for web development, science, and more due to its large community and support. Performance depends more on frameworks and architecture than language alone.
This document provides an overview of the Python programming language in 3 paragraphs. It discusses that Python is a high-level, interpreted, interactive and object-oriented scripting language. It was created by Guido van Rossum in the late 1980s and derived from languages like C and C++. The document then covers some key features of Python, including that it is easy to learn and read, portable, extensible and supports object-oriented programming. It provides examples of Python's basic syntax including indentation, variables, data types, operators and more.
Teaching Notes (extremely technical) detailing my Raspberry Pi program. This is for the third set of classes, where we taught the Python coding language along with logic structure. This is the first class, showing the basics of Python.
Python 101++: Let's Get Down to Business!Paige Bailey
You've started the Codecademy and Coursera courses; you've thumbed through Zed Shaw's "Learn Python the Hard Way"; and now you're itching to see what Python can help you do. This is the workshop for you!
Here's the breakdown: we're going to be taking you on a whirlwind tour of Python's capabilities. By the end of the workshop, you should be able to easily follow any of the widely available Python courses on the internet, and have a grasp on some of the more complex aspects of the language.
Please don't forget to bring your personal laptop!
Audience: This course is aimed at those who already have some basic programming experience, either in Python or in another high level programming language (such as C/C++, Fortran, Java, Ruby, Perl, or Visual Basic). If you're an absolute beginner -- new to Python, and new to programming in general -- make sure to check out the "Python 101" workshop!
Python is a high-level, interpreted programming language that is designed to be easy to read and write. It has a clear syntax using English keywords and its code is often shorter than languages like C++ and Java. Python is widely used for web development, software development, science, and machine learning. It has a large standard library and can be extended through modules. Some key data structures in Python include lists, tuples, and dictionaries.
The basics of Python are rather straightforward. In a few minutes you can learn most of the syntax. There are some gotchas along the way that might appear tricky. This talk is meant to bring programmers up to speed with Python. They should be able to read and write Python.
This document provides an introduction to Python programming using PyCharm. It discusses downloading and installing Python and PyCharm, creating and running simple Python scripts that use print statements and variables, taking user input, and introducing conditional logic using if/else statements and while loops. Examples include printing ASCII art, basic math operations, and building a text-based choose your own adventure game. Further exercises are suggested to improve the game by adding dice rolls and more options.
Python was created in the late 1980s by Guido van Rossum and first released in 1991. It gained popularity and saw new releases in 2000 and 2008. Python is an open source, general purpose, interpreted, object-oriented programming language used widely for web development, science, and more due to its large community and support. Performance depends more on frameworks and architecture than language alone.
This document provides an overview of the Python programming language in 3 paragraphs. It discusses that Python is a high-level, interpreted, interactive and object-oriented scripting language. It was created by Guido van Rossum in the late 1980s and derived from languages like C and C++. The document then covers some key features of Python, including that it is easy to learn and read, portable, extensible and supports object-oriented programming. It provides examples of Python's basic syntax including indentation, variables, data types, operators and more.
This document summarizes basic operations in Matlab and Python, including programming paradigms, object-oriented fundamentals, arrays/lists, cells/structures, functions, and loops. It provides examples of classes, objects, and inheritance in both languages. Examples are also given for arrays, lists, cells, structures, functions, and loops. The document outlines the key differences between Matlab and Python for arrays, lists, and cells/structures. It concludes with references used in preparing the content.
This document provides an overview and introduction to Python programming. It covers setting up Python, background on the language, basic syntax like printing, variables, operators, control structures, functions, and data structures. It encourages participation and practicing the concepts by following along. The goal is to teach the fundamentals of Python in an interactive class format.
The document discusses dictionaries in Python. It explains that dictionaries are a mapping type that store key-value pairs, with keys being immutable types and values being any type. It provides examples of creating, accessing, updating, removing entries from, and accessing properties of dictionaries. It also covers functions, control flow statements like if/else and while loops, and list comprehensions.
This document provides an introduction to the Python language and discusses Python data types. It covers how to install Python, interact with the Python interpreter through command line and IDLE modes, and learn basic Python parts like data types, operators, functions, and control structures. The document discusses numeric, string, and other data types in Python and how to manipulate them using built-in functions and operators. It also introduces Python library modules and the arcpy package for geoprocessing in ArcGIS.
Provides an introductory level understanding of the Python Programming Language and language features. Serves as a guide for beginners and a reference to Python basics and language use cases.
This document provides an introduction to the Python programming language. It covers Python's background, syntax, types, operators, control flow, functions, classes, tools, and IDEs. Key points include that Python is a multi-purpose, object-oriented language that is interpreted, strongly and dynamically typed. It focuses on readability and has a huge library of modules. Popular Python IDEs include Emacs, Vim, Komodo, PyCharm, and Eclipse.
This document provides an introduction and overview of the Python programming language. It discusses Python's origins, philosophy, features, and uses. Key points covered include Python's simplicity, power, object-oriented approach, and wide portability. Examples are provided of basic Python syntax and constructs like strings, lists, functions, modules, and dictionaries.
The document introduces Python modules and importing. It discusses three formats for importing modules: import somefile, from somefile import *, and from somefile import className. It describes commonly used Python modules like sys, os, and math. It also covers defining your own modules, directories for module files, object-oriented programming in Python including defining classes, creating and deleting instances, methods and self, accessing attributes and methods, attributes, inheritance, and redefining methods.
Introduction to Python Language and Data TypesRavi Shankar
This document provides information about the Python programming language. It discusses that Python was invented in the 1990s in the Netherlands by Guido van Rossum and was named after Monty Python. It is an open source, general-purpose, interpreted programming language that is widely used. The document then covers various Python implementations, popular Python editors and IDEs, tips for getting started with Python, basic syntax, data types, operators, and lists.
The document discusses types in Haskell, explaining that Haskell is strongly typed and describing basic types like Int, Char, and Bool as well as more complex types like tuples, lists, and functions. It also covers type inference, polymorphism, and how to infer the behavior of functions from their types.
Introduction to the basics of Python programming (part 3)Pedro Rodrigues
This is the 3rd part of a multi-part series that teaches the basics of Python programming. It covers list and dict comprehensions, functions, modules and packages.
Python 101: Python for Absolute Beginners (PyTexas 2014)Paige Bailey
If you're absolutely new to Python, and to programming in general, this is the place to start!
Here's the breakdown: by the end of this workshop, you'll have Python downloaded onto your personal machine; have a general idea of what Python can help you do; be pointed in the direction of some excellent practice materials; and have a basic understanding of the syntax of the language.
Please don't forget to bring your laptop!
Audience: "Python 101" is geared toward individuals who are new to programming. If you've had some programming experience (shell scripting, MATLAB, Ruby, etc.), then you'll probably want to check out the more intermediate workshop, "Python 101++".
This document provides an introduction and overview of various Python programming concepts including print statements, math operations, variables, selection using if/else statements, and iteration using while and for loops. Examples are given for basic "Hello World" programs, math calculations, variables, checking if a number is odd or even, and finding the largest of three numbers. Loops are demonstrated for printing ranges of numbers, calculating sums and factorials. The document also discusses data types and operations in Python.
This document provides information on Python code structures, including if/else statements, loops (while and for), functions, and arguments. It explains the basic syntax and usage of these structures. Key points covered include:
- How to write if/else statements and the use of conditions like ==, !=, <, >, etc.
- The syntax of while and for loops, and how to use break, continue, else blocks
- What functions are in Python and how to define them with def, pass arguments, and return values
- The basics of calling functions, optional arguments, and nested structures like if/else in loops
Python quickstart for programmers: Python Kung Fuclimatewarrior
The document provides an overview of key Python concepts including data types, operators, control flow statements, functions, objects and classes. It discusses lists in depth, covering creation, iteration, searching and common list methods. It also briefly touches on modules, exceptions, inheritance and other advanced topics.
basic of desicion control statement in pythonnitamhaske
it consists if-else, nested if, if-elif-else, for loop, while loop with flowchart and examples. also continue ,pass and break statement.
and else with for and while loop
Introduction to the Python programming language (version 2.x)
Ambient intelligence: technology and design
http://bit.ly/polito-ami
Politecnico di Torino, 2015
1. Python can be used to automate repetitive tasks like data entry, file processing, report generation etc. This saves time and reduces human errors.
2. Python has many libraries for machine learning, data analysis and visualization which can be used to analyze patent data, identify trends, cluster similar technologies etc.
3. Web scraping and web development frameworks like Django can be used to build internal tools and dashboards to manage workflows more efficiently.
4. Python scripts can be written to extract and process data from various sources, perform calculations, format reports in a standardized way reducing manual efforts.
The Story of XerographyThe Story of XerographyTania Niкolova
Chester Carlson invented xerography in 1938 while working as a patent attorney. He created the first xerographic image, marking the date and location, on October 22, 1938 in a makeshift laboratory in Astoria, New York. Carlson struggled for over 10 years to find a company to develop his invention into a useful product. Eventually, the Haloid Company in Rochester, New York took on developing xerography, which led to them becoming the multinational Xerox Corporation.
This document summarizes basic operations in Matlab and Python, including programming paradigms, object-oriented fundamentals, arrays/lists, cells/structures, functions, and loops. It provides examples of classes, objects, and inheritance in both languages. Examples are also given for arrays, lists, cells, structures, functions, and loops. The document outlines the key differences between Matlab and Python for arrays, lists, and cells/structures. It concludes with references used in preparing the content.
This document provides an overview and introduction to Python programming. It covers setting up Python, background on the language, basic syntax like printing, variables, operators, control structures, functions, and data structures. It encourages participation and practicing the concepts by following along. The goal is to teach the fundamentals of Python in an interactive class format.
The document discusses dictionaries in Python. It explains that dictionaries are a mapping type that store key-value pairs, with keys being immutable types and values being any type. It provides examples of creating, accessing, updating, removing entries from, and accessing properties of dictionaries. It also covers functions, control flow statements like if/else and while loops, and list comprehensions.
This document provides an introduction to the Python language and discusses Python data types. It covers how to install Python, interact with the Python interpreter through command line and IDLE modes, and learn basic Python parts like data types, operators, functions, and control structures. The document discusses numeric, string, and other data types in Python and how to manipulate them using built-in functions and operators. It also introduces Python library modules and the arcpy package for geoprocessing in ArcGIS.
Provides an introductory level understanding of the Python Programming Language and language features. Serves as a guide for beginners and a reference to Python basics and language use cases.
This document provides an introduction to the Python programming language. It covers Python's background, syntax, types, operators, control flow, functions, classes, tools, and IDEs. Key points include that Python is a multi-purpose, object-oriented language that is interpreted, strongly and dynamically typed. It focuses on readability and has a huge library of modules. Popular Python IDEs include Emacs, Vim, Komodo, PyCharm, and Eclipse.
This document provides an introduction and overview of the Python programming language. It discusses Python's origins, philosophy, features, and uses. Key points covered include Python's simplicity, power, object-oriented approach, and wide portability. Examples are provided of basic Python syntax and constructs like strings, lists, functions, modules, and dictionaries.
The document introduces Python modules and importing. It discusses three formats for importing modules: import somefile, from somefile import *, and from somefile import className. It describes commonly used Python modules like sys, os, and math. It also covers defining your own modules, directories for module files, object-oriented programming in Python including defining classes, creating and deleting instances, methods and self, accessing attributes and methods, attributes, inheritance, and redefining methods.
Introduction to Python Language and Data TypesRavi Shankar
This document provides information about the Python programming language. It discusses that Python was invented in the 1990s in the Netherlands by Guido van Rossum and was named after Monty Python. It is an open source, general-purpose, interpreted programming language that is widely used. The document then covers various Python implementations, popular Python editors and IDEs, tips for getting started with Python, basic syntax, data types, operators, and lists.
The document discusses types in Haskell, explaining that Haskell is strongly typed and describing basic types like Int, Char, and Bool as well as more complex types like tuples, lists, and functions. It also covers type inference, polymorphism, and how to infer the behavior of functions from their types.
Introduction to the basics of Python programming (part 3)Pedro Rodrigues
This is the 3rd part of a multi-part series that teaches the basics of Python programming. It covers list and dict comprehensions, functions, modules and packages.
Python 101: Python for Absolute Beginners (PyTexas 2014)Paige Bailey
If you're absolutely new to Python, and to programming in general, this is the place to start!
Here's the breakdown: by the end of this workshop, you'll have Python downloaded onto your personal machine; have a general idea of what Python can help you do; be pointed in the direction of some excellent practice materials; and have a basic understanding of the syntax of the language.
Please don't forget to bring your laptop!
Audience: "Python 101" is geared toward individuals who are new to programming. If you've had some programming experience (shell scripting, MATLAB, Ruby, etc.), then you'll probably want to check out the more intermediate workshop, "Python 101++".
This document provides an introduction and overview of various Python programming concepts including print statements, math operations, variables, selection using if/else statements, and iteration using while and for loops. Examples are given for basic "Hello World" programs, math calculations, variables, checking if a number is odd or even, and finding the largest of three numbers. Loops are demonstrated for printing ranges of numbers, calculating sums and factorials. The document also discusses data types and operations in Python.
This document provides information on Python code structures, including if/else statements, loops (while and for), functions, and arguments. It explains the basic syntax and usage of these structures. Key points covered include:
- How to write if/else statements and the use of conditions like ==, !=, <, >, etc.
- The syntax of while and for loops, and how to use break, continue, else blocks
- What functions are in Python and how to define them with def, pass arguments, and return values
- The basics of calling functions, optional arguments, and nested structures like if/else in loops
Python quickstart for programmers: Python Kung Fuclimatewarrior
The document provides an overview of key Python concepts including data types, operators, control flow statements, functions, objects and classes. It discusses lists in depth, covering creation, iteration, searching and common list methods. It also briefly touches on modules, exceptions, inheritance and other advanced topics.
basic of desicion control statement in pythonnitamhaske
it consists if-else, nested if, if-elif-else, for loop, while loop with flowchart and examples. also continue ,pass and break statement.
and else with for and while loop
Introduction to the Python programming language (version 2.x)
Ambient intelligence: technology and design
http://bit.ly/polito-ami
Politecnico di Torino, 2015
1. Python can be used to automate repetitive tasks like data entry, file processing, report generation etc. This saves time and reduces human errors.
2. Python has many libraries for machine learning, data analysis and visualization which can be used to analyze patent data, identify trends, cluster similar technologies etc.
3. Web scraping and web development frameworks like Django can be used to build internal tools and dashboards to manage workflows more efficiently.
4. Python scripts can be written to extract and process data from various sources, perform calculations, format reports in a standardized way reducing manual efforts.
The Story of XerographyThe Story of XerographyTania Niкolova
Chester Carlson invented xerography in 1938 while working as a patent attorney. He created the first xerographic image, marking the date and location, on October 22, 1938 in a makeshift laboratory in Astoria, New York. Carlson struggled for over 10 years to find a company to develop his invention into a useful product. Eventually, the Haloid Company in Rochester, New York took on developing xerography, which led to them becoming the multinational Xerox Corporation.
This document provides instructions for building basic LED circuits on a breadboard and enhancing the circuits. It instructs the reader to build a simple circuit with one LED and resistor, then expand it to include a second LED. The reader is then instructed to add a button to the circuit so that one LED only lights up when the button is pressed. Finally, it provides details on experimenting with a four-pole white LED that can display different colors depending on how its poles are wired.
Presentation slides from Genrequeer: Smashing the Closet presentation by Katelyn Browne, Christie Gibrich, Malinda Lo, Robin Talley, & Kristin Clark at the 2014 YALSA Lit Symposium in Austin, TX.
Teaching Notes (extremely technical) detailing my Raspberry Pi program. This is for the third set of classes, where we taught the Python coding language along with logic structure. This is the second class, showing the basics of computer program logic by using grocery shopping and recipes as examples.
If Xerox pays no dividends, it could reinvest $272.7 million more in the current year. Xerox could use a granular approach to analyze thousands of fine market segments to identify growth opportunities. This would involve dividing the business into geographic, customer, and product slices. Xerox would also need to develop a team of 200+ top leaders to implement the granular growth strategy. Paying no dividends and pursuing a granular growth strategy could allow Xerox to make more profitable investments and develop more customized products for local markets.
The document discusses a presentation on accessing customer satisfaction and market dynamics for document management devices. The objectives are to understand customer usage, strengthen the Xerox brand image, and determine customer preferences and satisfaction levels. A survey found that HP has the largest market share for copiers and MFDs. Customers prioritize quality over other factors like price and service. While most customers are satisfied, Xerox needs to better distinguish its brand and provide solutions for all business sizes.
The Raspberry Pi is a credit-card sized computer that plugs into a TV and keyboard. It functions like a desktop computer, capable of tasks like word processing, spreadsheets, and games. Setup involves connecting a monitor via HDMI, keyboard and mouse via USB, and an SD card containing the operating system. Power is applied last to turn on the Raspberry Pi and access the Linux-based Raspbian operating system through a graphical user interface. Proper shutdown involves using commands to sync data and safely powering off all components.
1. The document provides instructions for building a simple circuit with a Raspberry Pi to light an LED. Key steps include connecting the GPIO ribbon cable, breadboard interface, 3.3V power source, 160-ohm resistor, and LED with the long leg to one row and short leg to another.
2. Troubleshooting tips are provided if the LED does not light, including checking that all components are firmly connected in the proper rows and orientation and that the ribbon cable and breadboard are properly seated.
3. After testing the lit LED, the document instructs shutting down the Pi via command line and observing that the LED remains lit, demonstrating that the hardware remains powered even after shutdown of the
This document provides an overview of a global document solutions provider called E-Servizi S.p.A. In 3 sentences:
E-Servizi S.p.A. was founded in 1991 in Rome and has since grown to be a leading provider of office and graphic printing equipment, technical support, and document management solutions. It has over 95 employees and consultants and provides solutions to over 13,200 customers annually. The company aims to establish strategic partnerships with customers to help them improve their business and work processes through innovative document solutions.
Teaching Notes (extremely technical) detailing my Raspberry Pi program. This is for the third set of classes, where we taught the Python coding language along with logic structure. This is the last class, putting the logic of computer language structure with the basics of Python, and creating a magic 8 ball prediction program.
Xerox was founded in 1906 and is headquartered in Norwalk, Connecticut. It has faced challenges in recent years due to failing to commercialize new technologies and misguided CEO priorities. To succeed, Xerox needs to focus on business process management, asset sales, cost cutting, and following advisor recommendations. It also needs to better integrate its marketing plan by defining its mission, setting objectives, analyzing its situation, developing strategy, and monitoring results. With the right focus and leadership, Xerox has the opportunity to be fixed.
Xerox Corporation engaged in accounting fraud from 1997 to 2001 by improperly classifying $6 billion in revenue to artificially inflate earnings. This was done through two main methods - storing revenue off-balance sheet and accelerating revenue from short-term rentals by treating them as long-term leases. This allowed Xerox to meet earnings targets and enabled top executives to profit from inflated stock prices. The fraud went undetected by auditor KPMG. The SEC investigation found that Xerox top management compensation was tied to meeting earnings targets, providing motivation for the fraud.
This document provides a cheat sheet for Python basics. It begins with an introduction to Python and its advantages. It then covers key Python data types like strings, integers, floats, lists, tuples, and dictionaries. It explains how to define variables, functions, conditional statements, and loops. The document also demonstrates built-in functions, methods for manipulating common data structures, and other Python programming concepts in a concise and easy to understand manner.
This document discusses basic data types in Python, including numeric, sequence, boolean, and dictionary types. It provides examples and explanations of integer, float, complex, string, list, tuple, set, and dictionary data types. Numeric types represent numeric values, sequence types organize ordered sequences, boolean represents True or False, and dictionary stores key-value pairs. Python assigns data types dynamically based on values and allows flexible conversion between types.
This document provides an introduction to Python programming through examples. It begins with a "Hello World" program typed directly into the Python interpreter. It then demonstrates how to calculate with Python, use variables to store and retrieve values, take input from the user using the raw_input function, and print output. The document provides guidance on Python syntax, strings, comments, and choosing identifiers for variables.
This document discusses Python loops and string manipulation. It covers while loops, using a loop counter to repeat code a specified number of times. It also discusses slicing strings to access characters or substrings, checking if a string contains a character, and calling string methods like lower(), upper(), and replace() to manipulate strings.
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
Python
Language
is uesd in engineeringStory adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they s
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 ...
This document provides an agenda and overview for a Python 3 beginner workshop. The agenda covers topics like numbers, strings, lists, tuples, dictionaries, control statements, functions, classes and in-built functions. For each topic, there are examples provided to demonstrate Python syntax and how to use various features. The workshop is intended to give attendees a hands-on introduction to common Python concepts through examples in the interactive terminal.
A Gentle Introduction to Coding ... with PythonTariq Rashid
A gentle introduction to coding (programming) for complete beginners. Starting from then basics - electrical wires - proceeding through variables, data structures, loops, functions, and exploring libraries for visualisation and specialist tools. Finally we use flask to make a very simple twitter clone web application.
The document provides an introduction and tutorial to the Python programming language. It covers 13 chapters that introduce very basic Python concepts up to more advanced topics like classes and CGI programming. The chapters include variables, data types, operators, conditionals, functions, iteration, strings, collection data types, exception handling, modules, files, documentation, and classes. The document also notes several sources that were used to create the tutorial and provides example code snippets throughout to demonstrate the concepts discussed.
This document provides an overview of Python programming concepts including the basics of Python, strings, control structures like if/else statements and loops, and input/output functions. It discusses what a program and programming are, gives an introduction to Python including its uses and installation. It then covers key Python concepts like variables, data types, operators, functions, modules and object-oriented programming.
This document discusses strings in Python. It shows how to create strings, concatenate strings using the + operator, use print() to output strings, and run Python scripts. It also covers string slicing to access parts of a string, string indices, the len() function, and calculating string halfway points using integer division.
A for loop is probably the most common type of loop in Python. A for loop will select items from any iterable. In Python an iterable is any container (list, tuple, set, dictionary), as well as many other important objects such as generator function, generator expressions, the results of builtin functions such as filter, map, range and many other items.
This presentation about Python Interview Questions will help you crack your next Python interview with ease. The video includes interview questions on Numbers, lists, tuples, arrays, functions, regular expressions, strings, and files. We also look into concepts such as multithreading, deep copy, and shallow copy, pickling and unpickling. This video also covers Python libraries such as matplotlib, pandas, numpy,scikit and the programming paradigms followed by Python. It also covers Python library interview questions, libraries such as matplotlib, pandas, numpy and scikit. This video is ideal for both beginners as well as experienced professionals who are appearing for Python programming job interviews. Learn what are the most important Python interview questions and answers and know what will set you apart in the interview process.
Simplilearn’s Python Training Course is an all-inclusive program that will introduce you to the Python development language and expose you to the essentials of object-oriented programming, web development with Django and game development. Python has surpassed Java as the top language used to introduce U.S. students to programming and computer science. This course will give you hands-on development experience and prepare you for a career as a professional Python programmer.
What is this course about?
The All-in-One Python course enables you to become a professional Python programmer. Any aspiring programmer can learn Python from the basics and go on to master web development & game development in Python. Gain hands on experience creating a flappy bird game clone & website functionalities in Python.
What are the course objectives?
By the end of this online Python training course, you will be able to:
1. Internalize the concepts & constructs of Python
2. Learn to create your own Python programs
3. Master Python Django & advanced web development in Python
4. Master PyGame & game development in Python
5. Create a flappy bird game clone
The Python training course is recommended for:
1. Any aspiring programmer can take up this bundle to master Python
2. Any aspiring web developer or game developer can take up this bundle to meet their training needs
Learn more at https://www.simplilearn.com/mobile-and-software-development/python-development-training
This document discusses Python lists and loops. It begins by explaining how lists allow storing multiple values in a single variable, unlike separate variables. Lists can hold any data types and values can be accessed by index like strings. The document then demonstrates how to create and manipulate lists using various methods like append, sort, and join. It also introduces for loops, which are commonly used to iterate through lists. Range functions are described that can generate integer sequences to loop over. In the last section, some additional string methods are covered like startswith, endswith, strip, and find.
This document provides instructions and sample code for Exercise 4 of Learn Python the Hard Way. The exercise introduces variables and variable names in Python.
The sample code defines several variables like cars, drivers, passengers, and uses them to calculate things like empty cars, carpool capacity, and average passengers per car. It prints the results.
The document provides extra credit tasks like adding comments to explain each line, reading the file backwards, finding typing errors, and researching floating point numbers. It also shows an example error when a variable is undefined.
The document discusses algorithmic complexity and the RAM model for analyzing computational efficiency. It explains that the RAM model treats memory as contiguous words that can be accessed and stored values in primitive operations. Common data structures like lists can be modeled in this way. The complexity of operations like concatenating lists, deleting elements, or extending lists is analyzed based on the number of primitive operations required. The document also covers analyzing best, average, and worst-case complexity and discusses common complexity classes like constant, logarithmic, linear, and quadratic time.
Code Like Pythonista
Beautifully made PPT.
Ref. http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html
Image ref : https://pixabay.com/ko/ and https://morguefile.com/
licensed under a Creative Commons Attribution/Share-Alike (BY-SA) license.
The document provides an overview of the Python programming language. It discusses what Python is, its history and origins, why it is popular, common applications, and who uses it. It then covers running Python, variables, data types, input/output functions, conditional and looping statements. Specific Python concepts explained in more detail include variables, common data types (numeric, string, list, tuple, dictionary, Boolean), functions for lists and tuples, and if/else and for/while loop statements. The document is intended as an introductory guide to Python.
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...amit kuraria
This document provides a summary of techniques for coding in a Pythonic way. It discusses negative indexing in Python to access elements from the end of a sequence, using the length of a container to check if it is empty, creating lists of strings using the split() method, using ternary expressions for conditional assignments, opening files using the with statement for automatic closing, chaining comparisons and using the in keyword to test for multiple equality conditions. The document provides examples of each technique and explains how they make for more concise and Pythonic code.
Python is a programming language developed in 1989 that is still actively developed. It draws influences from languages like Perl, Java, C, C++, and others. Python code is portable, free, and recommended for tasks like system administration scripts, web development, scientific computing, and rapid prototyping. It has a simple syntax and is optionally object-oriented and multi-threaded. Python has extensive libraries for tasks like string manipulation, web programming, databases, and interface design. Popular applications of Python include web development, data analysis, scientific computing, and scripting.
Level 3 NCEA - NZ: A Nation In the Making 1872 - 1900 SML.pptHenry Hollis
The History of NZ 1870-1900.
Making of a Nation.
From the NZ Wars to Liberals,
Richard Seddon, George Grey,
Social Laboratory, New Zealand,
Confiscations, Kotahitanga, Kingitanga, Parliament, Suffrage, Repudiation, Economic Change, Agriculture, Gold Mining, Timber, Flax, Sheep, Dairying,
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...EduSkills OECD
Andreas Schleicher, Director of Education and Skills at the OECD presents at the launch of PISA 2022 Volume III - Creative Minds, Creative Schools on 18 June 2024.
Gender and Mental Health - Counselling and Family Therapy Applications and In...PsychoTech Services
A proprietary approach developed by bringing together the best of learning theories from Psychology, design principles from the world of visualization, and pedagogical methods from over a decade of training experience, that enables you to: Learn better, faster!
This presentation was provided by Racquel Jemison, Ph.D., Christina MacLaughlin, Ph.D., and Paulomi Majumder. Ph.D., all of the American Chemical Society, for the second session of NISO's 2024 Training Series "DEIA in the Scholarly Landscape." Session Two: 'Expanding Pathways to Publishing Careers,' was held June 13, 2024.
How Barcodes Can Be Leveraged Within Odoo 17Celine George
In this presentation, we will explore how barcodes can be leveraged within Odoo 17 to streamline our manufacturing processes. We will cover the configuration steps, how to utilize barcodes in different manufacturing scenarios, and the overall benefits of implementing this technology.
This document provides an overview of wound healing, its functions, stages, mechanisms, factors affecting it, and complications.
A wound is a break in the integrity of the skin or tissues, which may be associated with disruption of the structure and function.
Healing is the body’s response to injury in an attempt to restore normal structure and functions.
Healing can occur in two ways: Regeneration and Repair
There are 4 phases of wound healing: hemostasis, inflammation, proliferation, and remodeling. This document also describes the mechanism of wound healing. Factors that affect healing include infection, uncontrolled diabetes, poor nutrition, age, anemia, the presence of foreign bodies, etc.
Complications of wound healing like infection, hyperpigmentation of scar, contractures, and keloid formation.
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxEduSkills OECD
Iván Bornacelly, Policy Analyst at the OECD Centre for Skills, OECD, presents at the webinar 'Tackling job market gaps with a skills-first approach' on 12 June 2024
A Visual Guide to 1 Samuel | A Tale of Two HeartsSteve Thomason
These slides walk through the story of 1 Samuel. Samuel is the last judge of Israel. The people reject God and want a king. Saul is anointed as the first king, but he is not a good king. David, the shepherd boy is anointed and Saul is envious of him. David shows honor while Saul continues to self destruct.
1. Raspberry Pi: a class in several parts
III: Software
3-1: Introduction to Python
Objectives:
Basic familiarity with the IDLE tool
Basic data manipulation using Python syntax
All the software for this sequence should already be on the Pi, as part of Raspbian.
Verify that the IDLE tool is available in the X Windows System.
What's the point? Giving the computer instructions, to tell it to do exactly what you
want. It can't do what it doesn't know, so we humans have to decide how to teach
it, and craft our programs appropriately. Games, web, documents, security, music,
virtually anything is possible.
Basic data manipulation:
Type a number into IDLE and press enter. It examines what you told it, does it, and tell
you the result. In this case, it tells you what number you entered...because there is
nothing else to do.
Try some basic math, e.g. 1 + 1. It tells you the answer is 2. Some basic operators are
as follows:
+ (addition)
- (subtraction)
* (multiplication)
/ (division)
% (modulo or remainder, as in 10 mod 3 == 1)
** (power, as in 4**2 = 4 squared = 16)
Try 10 / 3. Notice that the answer is 3. Now try 10 / 3.0. Notice that the answer is
3.3333333. If you tell it that you care about decimal places, you get decimal
numbers. Otherwise, you get integers.
Take a few minutes to use Python as a calculator. There are some editing shortcuts
that might also help at this point.
Ctrl-End will always get you back to the current prompt, if you move the cursor
elsewhere.
Alt-p will put the previous entry at the prompt again. If you hit it again, it will
cycle through entries previous to that as well.
Alt-n will go to the next entry. This is particularly useful if you are looking for
something in particular with Alt-p, but you pass it.
2. Ctrl-c will interrupt what is currently happening, clear the current programming
entry, and put your cursor at the prompt. If you don't know what is happening,
this can help you reset to a known state.
Copy and paste do work. Be careful of indentation if you choose to paste, and
also be careful of the >>> characters.
Variables:
(Attendees who have done some algebra will find this much easier.)
In its basic form, a variable is a box. You can put things in the box, you can take
things out of the box, you can forget what's inside, and then look to see what it is.
When you carry it around, though, it's still a box. Boxes come in different shapes and
sizes, but all of ours are going to be the same size for now.
Let's put the number 12 in a variable, by telling Python “x = 12” – notice that Python
responds by telling us absolutely nothing. Now, let's ask Python what x is:
>>> x
12
>>>
Next, let's use our variable in some arithmetic expressions. Try things like x + 1, x**x, 42
/ x, etc. Notice that it works just like the number 12.
Now, let's change x to something else. Try the following:
>>> x = x - 3
>>>
We can change what's in the box without actually looking at it, which is convenient.
Have a look to see what its value currently is.
>>> x
9
>>>
You can call variables pretty much whatever you like, as long as you use letters and
no spaces. Numbers are okay within a variable name, and multi-word variable
names are usually distinguished by capitalizing all but the first one. So, the following
are all valid: x, y, xy, george, john, paul, ringo, octopus,
thisIsAVeryLongVariableName, theSong, grocerylist. Be descriptive, and try to label
your boxes so you know what's inside them.
3. Strings:
We've seen how Python can act as a calculator with numbers, and how we can use
words to name variables. What if we want Python to talk to us? If you try to tell it
“hello” you get a nasty-looking error:
>>> hello
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
hello
NameError: name 'hello' is not defined
>>>
Such errors are commonplace and not to be feared. They simply indicate that
something went wrong, and usually provide useful information for fixing the problem.
In this case, Python doesn't know anything about hello – it is trying to interpret it as a
variable or other identifier. We want it to be treated as a literal string of characters,
so we have to put it inside quotation marks:
>>> "hello"
'hello'
>>>
Notice that when Python tells us 'hello' it is between a pair of apostrophes, also called
single quotes. Either single or double quotation marks are acceptable, as long as
they match.
We can also add strings together, and we can put them in variables. For example:
>>> y = 'hello'
>>> y
'hello'
>>> y + " world”
4. 'hello world'
Remember how we have the number 9 in x at the moment? It is often useful to insert
the values of numeric variables into strings, but to do so we must use a different
character: the backtick. It points toward the right, while the apostrophe On US
keyboards, it is usually on the same key as the tilde.
>>> y + " " + 'world' + `x`
'hello world9'
>>>
This may be a reasonable stopping point – the attention to detail required for success
throughout these examples may take some effort for attendees, especially if you
have some who do not have experience with algebra. Pack up the Pi kits as normal.
3-2: Structures
Objectives:
Learn how to manipulate lists (arrays)
Learn how to automate repetitive actions (loops)
Learn how to make decisions in code (conditionals)
Set up the Pi kits. Start the X Windows System (startx)and launch IDLE.
Briefly review the syntax from the last session. We will make use of variables and
strings, especially.
Most of the time we don't deal with just one thing. Consider a trip to the grocery
store: does the shopping list contain only one item? Sometimes, but most of the time
it is rather longer than that. Python lets us represent lists of things easily. We put them
between square brackets [].
>>> groceries = ['milk', 'french fries', 'TACOS', 'ketchup', "lettuce", 'penguins', 'MORE
TACOS']
>>> groceries
['milk', 'french fries', 'TACOS', 'ketchup', 'lettuce', 'penguins', 'MORE TACOS']
>>>
Notice that they are in the same order as they were when you entered them. How
many are there? In order to find out, we can use a function of Python called len (for
length).
Functions are repeatable actions. If you hand a box of stuff to somebody and ask
5. them to count what's inside, they can do that, and tell you the number. The len
function follows exactly the same principles. We give the len function a list – or a
variable that contains a list – and it tells us how many things are inside it. We do the
giving by putting it inside parentheses ().
>>> len(groceries)
7
>>>
Okay, so we have seven items on the list. Can we get the second item on the list?
Yes! But Python does a weird counting thing. The first item is number zero, the second
item is number one, and so on. The last item on this grocery list is number six. Many
programming languages start counting at zero, so as strange as this might be, it is a
useful thing to remember.
In order to get an item from the list, we enclose the item we want after the variable
name. For the third item, we do the following:
>>> groceries[2]
'TACOS'
>>>
Remember that we start counting from zero, so the third item is at position number
two. This is commonly pronounced “groceries sub two” because we are finding an
item with a particular subscript in the array.
Now, what if we want to alphabetize the grocery list? For this task, we can ask the list
to go off and sort itself. We do so with a dot, and since it already knows what to do,
we don't have to give the sort function anything in particular, so we give it just an
empty parameter list – that is, nothing between the parentheses.
>>> groceries.sort()
>>> groceries
['MORE TACOS', 'TACOS', 'french fries', 'ketchup', 'lettuce', 'milk', 'penguins']
>>>
This idea of asking a thing to do something is very, very powerful: it allows us to model
the world around us. What if we were to write a dog, and then we could ask it to
bark(quietly)and fetch(newspaper)? After receiving the newspaper, could we ask it
if it isCoveredInSlobber()or if it isCurrent()?
At any rate, what if we want to print each item in the grocery list on a separate line?
First of all, we can print something using the print()function:
>>> print("hello")
hello
6. >>>
This is important because it can be used in virtually any program, not just the
interactive IDLE environment. So now we can print each item in turn.
>>> groceries[0]
'MORE TACOS'
>>> groceries[1]
'TACOS'
>>> groceries[2]
'french fries'
>>> groceries[3]
'ketchup'
I don't know about you, but I'm getting tired of typing “groceries” over and over
again. Let's take a short cut and tell the computer to do that for us. The way we go
about this is using a loop:
for item in groceries:
print(item)
This is a fairly readable syntax. Python will go through the list of groceries, and for
each thing on the list it will call it an “item” and then it will print it.
At this stage it is critical to point out a couple of syntactic elements. First of all, the
colon (:) indicates that we are not done with what we are doing. Second,
indent ation matters. Although it is simply whitespace, many of the most common
errors result from misaligned or missing indentation within program structures.
Let's do the same thing another way. Instead of iterating over some items, let's iterate
over some numbers. The following syntax lets us do this:
>>> for index in range(0, 5):
print(index)
0
1
2
3
4
>>>
Notice that the first number of the range (0) is included, but the last number of the
range (5) is excluded. Remember how len(groceries) told us there are 7 items in the
list? This works out nicely for us, because the zero-based counting scheme means
that item 6 is the last one in the list, and a range from 0 to 7 will include 6 but not 7.
7. Let's put the pieces together.
>>> for index in range(0, len(groceries)):
print(groceries[index])
MORE TACOS
TACOS
french fries
ketchup
lettuce
milk
penguins
>>>
Now let's number the items.
>>> for index in range(0, len(groceries)):
print(`index` + ": " + groceries[index])
0: MORE TACOS
1: TACOS
2: french fries
3: ketchup
4: lettuce
5: milk
6: penguins
That's great, but wouldn't it be nice (for humans) to start the list at 1? We could do
the following:
>>> for index in range(0, len(groceries)):
print(`index + 1` + ": " + groceries[index])
1: MORE TACOS
2: TACOS
3: french fries
4: ketchup
5: lettuce
6: milk
7: penguins
>>>
This is starting to get complicated. Let's simplify a little bit by splitting up the print
8. statement.
>>> for index in range(0, len(groceries)):
num = index + 1
print(`num` +": " + groceries[index])
1: MORE TACOS
2: TACOS
3: french fries
4: ketchup
5: lettuce
6: milk
7: penguins
>>>
We can take the “index + 1” from the print and put that into num, then use num in the
print instead. Notice that both lines in the loop are indented. If the indentation does
not match, Python will complain.
Decision making:
There are lots of times when we need to make a decision in a program. If you're
playing tic-tac-toe and get three in a row, then the game is over. If the damage your
character receives is less than your current hit points, then your character lives. If the
user enters invalid input, print a message that indicates what was wrong. If the train is
carrying carrots, then give it top priority; otherwise, give the train priority just behind
Amtrak. (Nobody likes spoiled carrots, after all.)
Of course, in order to make a decision, we have to be able to test things. We do this
using Boolean operators. Here is a brief list of the most common operators:
== true if two things are equal
!= true if two things are not equal
> true if the thing on the left is greater than the thing on the right
< true if the thing on the left is less than the thing on the right
>= true if the thing on the left is greater than or equal to the thing on the
right
<= true if the thing on the left is less than or equal to the thing on the right
&& true if the thing on the left AND the thing on the right are both true
|| true if either the thing on the left OR the thing on the right is true
In Python, we can make make decisions using the if/elif/else construct.
if <condition>:
do something important
if <condition>:
9. do something important
else:
do something less important
if <condition>:
do something important
elif <different condition>:
do something cool
else
do something normal
For example, let's consider the numbers from 0 to 9, and determine whether they are
even or odd.
>>> for x in range(0, 10):
if x == 0:
print(`x` +": found zero!")
elif x % 2 == 0:
print(`x` +": even!")
else:
print(`x` +": odd.")
0: found zero!
1: odd.
2: even!
3: odd.
4: even!
5: odd.
6: even!
7: odd.
8: even!
9: odd.
>>>
Feel free to play with loops, lists, conditionals – these basic constructs can represent
the decision making process for a lot of problems. It's also fun to find the limits of what
Python can do. How many things can you put in a list? How long does it take to
count to a million? How long does it take if you don't print each number?
When you're satisfied, or your brains hurt, or you're out of time, pack up the Pi kits, as
normal.
3-3: Project
10. Objectives:
Learn how to handle input
Learn how to define a function
Put together a program that acts as a “magic 8-ball”
Set up the Pi kits as normal. Start the X Windows System and open IDLE.
It can be useful to interact with a user. We have seen how to create output, but
what about handling input from the keyboard?
There are two related ways to do this. The first is the input function, which handles
numbers well:
>>> input("Number -->")
Number -->12
12
>>>
Notice how Python prints whatever you tell the input function to use, and waits for
you to type something and press enter. If you enter anything other than a number,
you will get some kind of error. [Exception: it is possible to enter valid Python code
that evaluates to a number. For example, if you type len(“hello”) at the prompt, it will
be accepted and return the number 5.]
That's great, but what if you want to hold on to what the user entered? Use the
input()function as part of a variable assignment.
>>> x = input("What is x? ")
What is x? 42
>>> x
42
>>>
Being limited to numbers only is pretty restrictive. If you want to accept anything the
user enters, you can use the raw_input function instead.
>>> x = raw_input("What is x? ")
What is x? The quick brown fox jumped over the lazy dogs.
>>> x
'The quick brown fox jumped over the lazy dogs.'
>>>
Notice, however, that if you provide a number to raw_input, it is still interpreted as a
string, so you cannot directly perform operations like “x + 1” meaningfully.
11. Functions:
We have seen several cases where we ask something like len() or sort()or input()to
do a task for us, repeatedly. We can define our own such tasks, and they are called
functions. In a basic sense, they have a name, they may accept some input, and
they may return a value. The easiest way to define a function is with the def keyword,
and we use the return keyword to indicate what comes back.
>>> def plus(a, b):
return a + b
As usual, when we put the colon on the end of the first line, we're saying “I'm not
done” and the subsequent lines are consistently indented. Python allows us to do just
about anything we like within a function definition, including calling (or even
creating) other functions. Now we can call our function just like any other:
>>> plus(3, 2)
5
>>>
There are lots of functions that are already defined for us, but sometimes we have to
tell Python where to find them. There is a random number generator, for example,
that we can use if we ask Python to load it:
>>> import random
The random() function gives us a decimal number between 0 and 1:
>>> random.random()
0.09922611904874357
>>> random.random()
0.5130440719955642
>>> random.random()
0.2534538950733807
>>> random.random()
0.8071376093891092
More frequently, however, we will use random numbers that are integers – consider a
die roll (1d6), for example. The function randint(min, max)helps us with that.
>>> random.randint(1, 6)
5
>>> random.randint(1, 6)
4
>>> random.randint(1, 6)
3
>>> random.randint(1, 6)
12. 6
>>> random.randint(1, 6)
3
>>> random.randint(1, 6)
1
>>>
Now we have all the tools we need to solve some real-world problems. How about
creating a program that acts as a “Magic 8-ball” for us? Ask a question, shake the
Magic 8-ball, and it reveals to us an answer.
First, we need some answers that it can give us. Define them as a list called
“answers.”
>>> answers = ['Yes', 'No', 'Maybe', 'Ask again', '73% chance', 'Orange', "Batman", 42]
Now we need a way to pick one of the answers, randomly. We will do this
repeatedly, so define a function to do this. The input will be the answer list, and the
output will be one of the answers. We will choose a random number between 0 and
the highest index of a list item, which is len(list) – 1. Notice that the name of what we
use in the function does not have to match any existing variable name, and might
well be clearer if it purposely doesn't.
>>> def pickAnAnswer(answerList):
highest = len(answerList) - 1
index = random.randint(0, highest)
return answerList[index]
We also need a way to reveal the answer, which some appropriate print statements.
Optionally, you can make the program appear to be thinking for some period of time
(perhaps for dramatic tension?), and if you choose to do so, be sure to load the time-
related functions.
>>> import time
>>> def delay(howLong):
for x in range(0, howLong):
print('...thinking...')
time.sleep(1)
>>> def revealAnswer(question, answer, thinkingTime):
print('Considering your question: ' + question)
delay(thinkingTime)
print('The Magic 8-ball has spoken! The answer you seek is this:')
print(answer)
Next, we need a way to allow the user to ask a question. We want to be able to do
13. this over and over again, so another function is in order. This one will be simple.
>>> def askAQuestion(prompt):
return raw_input(prompt + ' --> ')
We have all the components in place. Now we need a loop that will allow us to keep
asking as many questions as we like, or a certain number of questions. We also need
to make sure that we initialize the question to something, so the program knows it
exists.
>>> question = 'none yet'
>>> while (question != 'exit'):
question = askAQuestion("What is your question? ")
if question != "exit":
answer = pickAnAnswer(answers)
revealAnswer(question, answer, 1)
What is your question? --> Should I exit?
Considering your question: Should I exit?
...thinking...
The Magic 8-ball has spoken! The answer you seek is this:
Ask again
What is your question? --> Should I exit?
Considering your question: Should I exit?
...thinking...
The Magic 8-ball has spoken! The answer you seek is this:
Maybe
What is your question? --> How about now?
Considering your question: How about now?
...thinking...
The Magic 8-ball has spoken! The answer you seek is this:
Orange
What is your question? --> Um, should I exit now?
Considering your question: Um, should I exit now?
...thinking...
The Magic 8-ball has spoken! The answer you seek is this:
73% chance
What is your question? --> Okay, how about now?
Considering your question: Okay, how about now?
...thinking...
The Magic 8-ball has spoken! The answer you seek is this:
Yes
What is your question? --> exit
>>>
14. Here is the complete text of the program.
import random
import time
answers = ['Yes', 'No', 'Maybe', 'Ask again', '73% chance', 'Orange', “Batman”, 42]
def askAQuestion(prompt):
return raw_input(prompt + ' --> ')
def pickAnAnswer(answerList):
highest = len(answerList) - 1
index = random.randint(0, highest)
return answerList[index]
def delay(howLong):
for x in range(0, howLong):
print('...thinking...')
time.sleep(1)
def revealAnswer(question, answer, thinkingTime):
print('Considering your question: ' + question)
delay(thinkingTime)
print('The Magic 8-ball has spoken! The answer you seek is this:')
print(answer)
question = 'none yet'
while (question != 'exit'):
question = askAQuestion("What is your question? ")
15. if question != “exit”:
answer = pickAnAnswer(answers)
revealAnswer(question, answer, 1)
The answers list can be customized, of course, and can also be modified between
runs of the program. Have some fun with it!
Pack up the kits, and revel in the knowledge that you have begun to take full control
of a Raspberry Pi.