The document provides a recap of topics covered in Week 0 of a coding initiative for adults, including comments, variables, assignment, operators, statements, and expressions in Python. It defines each concept and provides examples. Comments are explained as a way to document code and "disable" sections. Variables are described as buckets that hold data. Various types of operators are listed and precedence is discussed. Statements are defined as executable instructions, while expressions are combinations of values and operations. Key points are brought together using an example that demonstrates comments, statements, variables, and expressions with assignment and operators.
CPAP.com Introduction to Coding: Part 1johnnygoodman
This document provides an introduction to coding concepts. It discusses storing values in variables and data types like strings and integers. Key coding concepts covered include comments, running code, comparisons, arrays, and if/else statements. The document outlines what future sessions will cover, including loops, classes, methods, connecting to databases, and using other people's code.
This document discusses regular expressions and their use in defining the syntax and tokens of a programming language. It provides examples of regular expressions for numeric literals and identifiers. Regular expressions allow the formal definition of the valid strings that make up the tokens in a language by using operators like concatenation, union, closure and more. They are used by scanners in compilers to extract tokens from source code.
This slide is presented at RubyKaigi 2014 on Sep 18.
We have designed and implemented the library that realizes non-linear pattern matching against unfree data types. We can directly express pattern-matching against lists, multisets, and sets using this library.
The library is already released via RubyGems.org as one of gems.
The expressive power of this gem derives from the theory behind the Egison programming language and is so strong that we can write poker-hands analyzer in a single pattern matching expression. This is impossible even in any other state-of-the-art programming language.
Pattern matching is one of the most important features of programming language for intuitive representation of algorithms.
Our library simplifies code by replacing not only complex conditional branches but also nested loops with an intuitive pattern-matching expression.
El documento explica el sistema de licencias Creative Commons, el cual permite que autores compartan sus obras intelectuales y permitan su uso, distribución y modificación bajo diferentes condiciones configuradas a través de las licencias. Creative Commons ofrece seis tipos de licencias que combinan cuatro condiciones principales: reconocimiento de la autoría, uso no comercial, prohibición de obras derivadas y compartir bajo la misma licencia. Estas licencias buscan establecer un equilibrio entre los derechos de los autores y el acceso público al conocimiento.
The document is a scanned receipt from a grocery store purchase on January 15th, 2023 for $58.46. It lists the items bought which include milk, eggs, bread, cereal, orange juice, bananas, and ground beef. The payment was made with a credit card ending in 4321.
This document provides an overview of collections in computer science and Python. It defines a collection as a grouping of variable data items that need to be operated on together. Collections include common data structures like arrays, lists, sets, trees and graphs. In Python, built-in collection types include lists, sets, dictionaries and tuples, while the collections module provides additional types like deque. The document discusses lists and arrays in detail, covering how to access and modify elements, basic operations, and when each type is best suited depending on the needs of the problem.
Our Corporate Credentials with our business model and approach to the market, updated at 2016. We use Digital PR and Digital Marketing Approach, thanks to a wide range of Influencers.
Data. Insight. Action. Infographics. Where are companies going wrong with dat...Conduit2Loyalty
Data Strategy is a key issue at the moment with the rise of big data. We have prepared two infographics for you to share with colleagues and look over.
They show you where companies are going wrong with data strategy at the moment, how to use data to create insight and form a data strategy from that insight.
CPAP.com Introduction to Coding: Part 1johnnygoodman
This document provides an introduction to coding concepts. It discusses storing values in variables and data types like strings and integers. Key coding concepts covered include comments, running code, comparisons, arrays, and if/else statements. The document outlines what future sessions will cover, including loops, classes, methods, connecting to databases, and using other people's code.
This document discusses regular expressions and their use in defining the syntax and tokens of a programming language. It provides examples of regular expressions for numeric literals and identifiers. Regular expressions allow the formal definition of the valid strings that make up the tokens in a language by using operators like concatenation, union, closure and more. They are used by scanners in compilers to extract tokens from source code.
This slide is presented at RubyKaigi 2014 on Sep 18.
We have designed and implemented the library that realizes non-linear pattern matching against unfree data types. We can directly express pattern-matching against lists, multisets, and sets using this library.
The library is already released via RubyGems.org as one of gems.
The expressive power of this gem derives from the theory behind the Egison programming language and is so strong that we can write poker-hands analyzer in a single pattern matching expression. This is impossible even in any other state-of-the-art programming language.
Pattern matching is one of the most important features of programming language for intuitive representation of algorithms.
Our library simplifies code by replacing not only complex conditional branches but also nested loops with an intuitive pattern-matching expression.
El documento explica el sistema de licencias Creative Commons, el cual permite que autores compartan sus obras intelectuales y permitan su uso, distribución y modificación bajo diferentes condiciones configuradas a través de las licencias. Creative Commons ofrece seis tipos de licencias que combinan cuatro condiciones principales: reconocimiento de la autoría, uso no comercial, prohibición de obras derivadas y compartir bajo la misma licencia. Estas licencias buscan establecer un equilibrio entre los derechos de los autores y el acceso público al conocimiento.
The document is a scanned receipt from a grocery store purchase on January 15th, 2023 for $58.46. It lists the items bought which include milk, eggs, bread, cereal, orange juice, bananas, and ground beef. The payment was made with a credit card ending in 4321.
This document provides an overview of collections in computer science and Python. It defines a collection as a grouping of variable data items that need to be operated on together. Collections include common data structures like arrays, lists, sets, trees and graphs. In Python, built-in collection types include lists, sets, dictionaries and tuples, while the collections module provides additional types like deque. The document discusses lists and arrays in detail, covering how to access and modify elements, basic operations, and when each type is best suited depending on the needs of the problem.
Our Corporate Credentials with our business model and approach to the market, updated at 2016. We use Digital PR and Digital Marketing Approach, thanks to a wide range of Influencers.
Data. Insight. Action. Infographics. Where are companies going wrong with dat...Conduit2Loyalty
Data Strategy is a key issue at the moment with the rise of big data. We have prepared two infographics for you to share with colleagues and look over.
They show you where companies are going wrong with data strategy at the moment, how to use data to create insight and form a data strategy from that insight.
The document discusses Python programming concepts like variables, data types, operators, conditional statements and indentation. It explains that variables store and label data in memory, common data types like integers, floats and strings, basic arithmetic and assignment operators, if/else conditional statements and how Python uses indentation to group blocks of code. It also provides examples of type casting between different data types and prompts for writing Python programs to perform various comparisons and calculations.
This document introduces an introductory Python programming class called ACM init(). It will meet once a week for several weeks and teach beginners Python programming with no prior experience required. It covers why learning computer science and Python is useful for careers and problem solving skills. It demonstrates running a simple Python program to calculate factorials and introduces some basic Python concepts like data types, variables, strings, math operators, and comments.
Introduction to the Python programming language (version 2.x)
Ambient intelligence: technology and design
http://bit.ly/polito-ami
Politecnico di Torino, 2015
Variables
Variable names
Assignment statements
Expressions and statements
Script mode
Order of operations
String operations
Comments
Input from userVariables
Variable names
Assignment statements
Expressions and statements
Script mode
Order of operations
String operations
Comments
Input from user
Variables
Variable names
Assignment statements
Expressions and statements
Script mode
Order of operations
String operations
Comments
Input from user
This presentation is a part of the COP2271C college level course taught at the Florida Polytechnic University located in Lakeland Florida. The purpose of this course is to introduce Freshmen students to both the process of software development and to the Python language.
The course is one semester in length and meets for 2 hours twice a week. The Instructor is Dr. Jim Anderson.
A video of Dr. Anderson using these slides is available on YouTube at:https://www.youtube.com/watch?feature=player_embedded&v=_fdNoErxjBw
The document discusses data-oriented design principles for game engine development in C++. It emphasizes understanding how data is represented and used to solve problems, rather than focusing on writing code. It provides examples of how restructuring code to better utilize data locality and cache lines can significantly improve performance by reducing cache misses. Booleans packed into structures are identified as having extremely low information density, wasting cache space.
Finding concurrency problems in core ruby librarieslouisadunne
During the development of an internal deployment tool we hit the type of problem we all dread – a deadlock triggered in a core Ruby module. This talk covers how this specific bug was identified, some general advice on how to find these kinds of issues and what Ruby could learn from other languages in this area.
Lec2_cont.pptx galgotias University questionsYashJain47002
This document discusses key concepts in Python including variables, data types, expressions, and statements. It covers defining variables and constants, using operators in expressions, and handling different data types. Comments are introduced as a way to document code. Examples demonstrate taking user input, performing calculations, and displaying output. Mnemonic variable names are recommended to improve readability.
This document contains notes from a Python class covering functions, lists, strings, and their methods. It discusses built-in functions like len(), range(), and type conversions. It also covers control flow structures like if/else, for loops, exceptions, modules, and functions in more detail including defining functions, parameters, arguments, returning values, docstring, and variable scopes. Assignments include writing functions to process lists and check for palindromes in strings.
The document provides an introduction to C programming, covering topics such as what a program is, programming languages, the history of C, and the development stages of a C program. It discusses the key components of a C program including preprocessing directives, the main function, and program layout. Examples are provided to illustrate C code structure and the use of variables, keywords, operators, input/output functions, and formatting output with printf.
- The document provides an overview of topics to be covered in a coding session, including while loops, string manipulation, ASCII codes, and for loops.
- It discusses infinite while loops and provides examples of converting data types to strings.
- Various string methods are demonstrated, like combining operations and using chr and ord to convert between characters and ASCII codes.
The document provides instructions for downloading and installing Python and PyCharm on Mac and Windows systems. It outlines the steps to download each program from their respective websites, then guides the user through installing Python and PyCharm on their device by navigating folders and clicking through installation windows. It also briefly introduces some basic programming concepts that will be covered in an upcoming Python tutorial, such as variables, data types, conditional statements, and loops.
This document provides an introduction to C++ programming including problem solving skills, software evolution, procedural and object oriented programming concepts, basic C++ programs, operators, header files, conditional statements, loops, functions, pointers, structures and arrays. It discusses topics such as analyzing problems, planning algorithms, coding solutions, evaluating results, procedural and object oriented paradigms, inheritance, polymorphism, flowcharts, basic syntax examples, and more. Various examples are provided to illustrate key concepts in C++.
introduction to Python by Mohamed Hegazy , in this slides you will find some code samples , these slides first presented in TensorFlow Dev Summit 2017 Extended by GDG Helwan
Python is an interpreted scripting language created in 1991 by Guido van Rossum. It is useful for small to medium sized projects and is used by many companies like Google, Yahoo, and YouTube. Python can be installed on Windows, Mac OS, and Linux operating systems by downloading the appropriate version from its website. It is an interpreted language, meaning code is executed directly without compilation. Python uses static typing where the type of a value determines how it behaves in expressions. It provides many built-in functions for common operations like math, converting between types, and rounding numbers. Functions allow code reuse and make programs more readable.
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.
This presentation is a part of the COP2271C college level course taught at the Florida Polytechnic University located in Lakeland Florida. The purpose of this course is to introduce Freshmen students to both the process of software development and to the Python language.
The course is one semester in length and meets for 2 hours twice a week. The Instructor is Dr. Jim Anderson.
A video of Dr. Anderson using these slides is available on YouTube at:
http://youtu.be/XWz0oIbzIpY
This PPT contains A to Z topics of C programming language. It makes learners to find it easy to learn C. Tutors also can use the PPT for better presentation.
This document provides an overview of different collection data types in Python including tuples, dictionaries, and sets. It discusses the key properties and uses of each type. Tuples are immutable sequences, dictionaries store key-value pairs and allow fast lookup by key, and sets only allow unique elements and support mathematical set operations. The document also covers performance considerations and recommends sets for fast membership checking of hashable elements.
The document discusses Python programming concepts like variables, data types, operators, conditional statements and indentation. It explains that variables store and label data in memory, common data types like integers, floats and strings, basic arithmetic and assignment operators, if/else conditional statements and how Python uses indentation to group blocks of code. It also provides examples of type casting between different data types and prompts for writing Python programs to perform various comparisons and calculations.
This document introduces an introductory Python programming class called ACM init(). It will meet once a week for several weeks and teach beginners Python programming with no prior experience required. It covers why learning computer science and Python is useful for careers and problem solving skills. It demonstrates running a simple Python program to calculate factorials and introduces some basic Python concepts like data types, variables, strings, math operators, and comments.
Introduction to the Python programming language (version 2.x)
Ambient intelligence: technology and design
http://bit.ly/polito-ami
Politecnico di Torino, 2015
Variables
Variable names
Assignment statements
Expressions and statements
Script mode
Order of operations
String operations
Comments
Input from userVariables
Variable names
Assignment statements
Expressions and statements
Script mode
Order of operations
String operations
Comments
Input from user
Variables
Variable names
Assignment statements
Expressions and statements
Script mode
Order of operations
String operations
Comments
Input from user
This presentation is a part of the COP2271C college level course taught at the Florida Polytechnic University located in Lakeland Florida. The purpose of this course is to introduce Freshmen students to both the process of software development and to the Python language.
The course is one semester in length and meets for 2 hours twice a week. The Instructor is Dr. Jim Anderson.
A video of Dr. Anderson using these slides is available on YouTube at:https://www.youtube.com/watch?feature=player_embedded&v=_fdNoErxjBw
The document discusses data-oriented design principles for game engine development in C++. It emphasizes understanding how data is represented and used to solve problems, rather than focusing on writing code. It provides examples of how restructuring code to better utilize data locality and cache lines can significantly improve performance by reducing cache misses. Booleans packed into structures are identified as having extremely low information density, wasting cache space.
Finding concurrency problems in core ruby librarieslouisadunne
During the development of an internal deployment tool we hit the type of problem we all dread – a deadlock triggered in a core Ruby module. This talk covers how this specific bug was identified, some general advice on how to find these kinds of issues and what Ruby could learn from other languages in this area.
Lec2_cont.pptx galgotias University questionsYashJain47002
This document discusses key concepts in Python including variables, data types, expressions, and statements. It covers defining variables and constants, using operators in expressions, and handling different data types. Comments are introduced as a way to document code. Examples demonstrate taking user input, performing calculations, and displaying output. Mnemonic variable names are recommended to improve readability.
This document contains notes from a Python class covering functions, lists, strings, and their methods. It discusses built-in functions like len(), range(), and type conversions. It also covers control flow structures like if/else, for loops, exceptions, modules, and functions in more detail including defining functions, parameters, arguments, returning values, docstring, and variable scopes. Assignments include writing functions to process lists and check for palindromes in strings.
The document provides an introduction to C programming, covering topics such as what a program is, programming languages, the history of C, and the development stages of a C program. It discusses the key components of a C program including preprocessing directives, the main function, and program layout. Examples are provided to illustrate C code structure and the use of variables, keywords, operators, input/output functions, and formatting output with printf.
- The document provides an overview of topics to be covered in a coding session, including while loops, string manipulation, ASCII codes, and for loops.
- It discusses infinite while loops and provides examples of converting data types to strings.
- Various string methods are demonstrated, like combining operations and using chr and ord to convert between characters and ASCII codes.
The document provides instructions for downloading and installing Python and PyCharm on Mac and Windows systems. It outlines the steps to download each program from their respective websites, then guides the user through installing Python and PyCharm on their device by navigating folders and clicking through installation windows. It also briefly introduces some basic programming concepts that will be covered in an upcoming Python tutorial, such as variables, data types, conditional statements, and loops.
This document provides an introduction to C++ programming including problem solving skills, software evolution, procedural and object oriented programming concepts, basic C++ programs, operators, header files, conditional statements, loops, functions, pointers, structures and arrays. It discusses topics such as analyzing problems, planning algorithms, coding solutions, evaluating results, procedural and object oriented paradigms, inheritance, polymorphism, flowcharts, basic syntax examples, and more. Various examples are provided to illustrate key concepts in C++.
introduction to Python by Mohamed Hegazy , in this slides you will find some code samples , these slides first presented in TensorFlow Dev Summit 2017 Extended by GDG Helwan
Python is an interpreted scripting language created in 1991 by Guido van Rossum. It is useful for small to medium sized projects and is used by many companies like Google, Yahoo, and YouTube. Python can be installed on Windows, Mac OS, and Linux operating systems by downloading the appropriate version from its website. It is an interpreted language, meaning code is executed directly without compilation. Python uses static typing where the type of a value determines how it behaves in expressions. It provides many built-in functions for common operations like math, converting between types, and rounding numbers. Functions allow code reuse and make programs more readable.
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.
This presentation is a part of the COP2271C college level course taught at the Florida Polytechnic University located in Lakeland Florida. The purpose of this course is to introduce Freshmen students to both the process of software development and to the Python language.
The course is one semester in length and meets for 2 hours twice a week. The Instructor is Dr. Jim Anderson.
A video of Dr. Anderson using these slides is available on YouTube at:
http://youtu.be/XWz0oIbzIpY
This PPT contains A to Z topics of C programming language. It makes learners to find it easy to learn C. Tutors also can use the PPT for better presentation.
Similar to Brixton Library Technology Initiative Week0 Recap (20)
This document provides an overview of different collection data types in Python including tuples, dictionaries, and sets. It discusses the key properties and uses of each type. Tuples are immutable sequences, dictionaries store key-value pairs and allow fast lookup by key, and sets only allow unique elements and support mathematical set operations. The document also covers performance considerations and recommends sets for fast membership checking of hashable elements.
The document provides information about software development lifecycles and project management. It discusses requirements gathering, domain modeling, coding, testing at various stages, deployment, and managing projects using agile methodologies like Scrum. Specifically, it outlines the development lifecycle from requirements to deployment, emphasizing good management processes, developer skills, and tools are needed to build quality software. It also describes how Scrum is used to manage projects through prioritized backlogs, sprints, daily standups, and retrospectives to continuously improve.
This document provides an introduction to event driven programming and user interface (UI) development. It discusses event driven programming concepts like handling events from the operating system in real time. It also covers UI design topics such as using widgets, working with window managers, and designing intuitive user flows. Examples are given of tiered application architectures and how events are processed asynchronously in an event driven program. Tools for UI development like Glade and integrated development environments are also mentioned.
This document recaps topics covered in Week 1 of a coding initiative, including functions, modules, boolean expressions, relational operators, and conditional statements in Python. It provides examples and explanations of each topic, such as how functions have a header, body and can take parameters; how to import and use modules; how boolean expressions work with logical operators; and how to write conditional statements using if/elif/else.
Welcome to the Brixton Library Technology InitiativeBasil Bibi
This document introduces a Python coding initiative at the Brixton Library for adults. It provides information about meeting times and contacts, as well as a detailed overview of the Python programming language, its history and uses. Participants are encouraged to register for an associated free online Coursera course and attend Saturday sessions at the library for assistance and collaboration.
3. # Comments
# A comment starts with a #
# Very useful for you to focus your mind on the problem and
# for the person who has to maintain your code
# Makes it easier to understand your program later – it might
# surprise you but you will forget exactly how your own code works
# especially if it’s complex or non obvious.
# if your code changes be sure to update your comments !
# A stale comment (one that contradicts the code) is worse than no comment at all.
# 01232456789012345678901234567890123456789012345678901234567890123456789012
# Try to make comment lines shorter than 50 characters per line.
# It’s easier to read than very long lines of text.
# Anything after the # is ignored by python e.g.
print "I could code like this." # and the comment after is ignored – use sparingly
# You can also use a comment to "disable" or comment out a piece of code:
# print "This won't run."
print "This will run."
4. What Are Variables?
• Variables are buckets that hold data.
• They have a name.
• Makes it easier to work with your data.
• print 3.141 * 100
• Intention of the above becomes clear when we use variables with
meaningful names – we were calculating and displaying the
circumference as this self documenting code shows:
diameter = 100
PI = 3.141
circumference = PI * diameter
print circumference
5. Variables : Valid Characters
• You can use any letter, the special underscore character “_” and every
number provided you do not start with a number.
• 1stThingsFirst
• _valid
• notPoss-ible # python thinks this means notPoss - ible
• *noWayMatey
• Make your variable names meaningful
increases readability – self documenting code.
• a = 52
• studentAge = 52
• student_Age=52
• dontmakeyourvariablehaveridiculouslylongnames = “!”
• dontMakeYourVariableHaveRidiculouslyLongNames = “!”
6. Naming Variables
• Recommended reading – the Python Style guide
https://www.python.org/dev/peps/pep-0008/
• Examples of naming conventions.
• Single character names :
• B
• lowercase
• lower_case_with_underscores
• UPPERCASE
• UPPER_CASE_WITH_UNDERSCORES
• Throughout the standard library, the most common way to define constants as module-level variables is using
UPPER_CASE_WITH_UNDERSCORES – hence PI in my previous example.
# CapWords, or CamelCase -- so named because of the bumpy look of its letters
# This is also sometimes known as StudlyCaps.
• CapitalizedWords
# When using abbreviations in CapWords, capitalize all the letters of the abbreviation.
# Thus HTTPServerError is better than HttpServerError.
• mixedCase # differs from CapitalizedWords by initial lowercase character!
• Capitalized_Words_With_Underscores # (ugly!)
7. Variables : Reserved Words
• Must not be one of the reserved keywords.
• and assert break class continue
def del elif else except exec finally for
from global if import in is lambda not
or pass print raise return try while yield
8. Assignment
• Put some data into a variable.
• “Setting a variable’s value“
• my_integer_var = 25
• my_string_var = “Hello World”
9. Operators
• They act on variables.
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
+ - * /
= += -= *= /=
== != < > <> <= >=
and or not
10. Operator Precedence
• From latin praecedere "go before"
• PEMDAS
"Please Excuse My Dear Aunt Sally".
It stands for "Parentheses, Exponents, Multiplication
and Division, Addition and Subtraction".
• BODMAS
B=brackets first
O=orders(like power and square etc.,)
D=division(/) M=multiplication(*)
A=addition(+) S=subtraction(-)
11. Operator Precedence
• PE MD AS
"Please Excuse My Dear Aunt Sally".
Parentheses,
Exponents,
Multiplication . Division,
Addition .Subtraction“.
• () a**2 a*a a/2 a+1 a-1
13. Operator Precedence
• PEMDAS
"Parentheses, Exponents, Multiplication and Division, and
Addition and Subtraction“.
• 5 * 3 + 2 - 4
• 13
• Use brackets to force evaluation
• 5 * ((3 + 2) – 4)
• 5
14. Operator Precedence
• Very few people remember operator precedence so use brackets to show
exactly what you mean.
• Everyone remembers that brackets come first so use them to force python to
evaluate in the way you intend. This also makes your code easier to
understand.
• mortgage_amount + arrears / years
• 120 +12 /10
• 121
• (mortgage_amount + arrears) / years
• (120 + 12) /10
• 13
• NB – because we are using int in the calculations we end up with the decimal
places being discarded – “truncated“
• Truncation is explained later in this slide deck.
15. Python Primitive Types
• These are the basic types of data you work with.
e.g. numbers, strings, true/false
• Numeric Types — int, long, float
-5 0 1 2 3 etc
• String
• Boolean – True False
• A whole host of other built in types that we will cover later.
16. Python int
• Whole numbers both positive and negative i.e Integers
• Remember, integers do not have a decimal or fractional part
-5 0 1 2 3 etc
• 3.141 – this is not an integer it is a floating point number.
print type(42)
<type 'int'>
• On a 64 bit machine running a 64 bit version of python
sys.maxint = 9,223,372,036,854,775,807 = 264 – 1
9 * 1019
• On a 32 bit version of python
2,147,483,647 = 232 -1
2*107
• Range –sys.maxint to sys.maxint
17. Python Integer “Rounding Down” - Truncation
• Beware – if you use int or long in a calculation that yields a decimal you
lose all of the decimal places – a feature known as truncation.
• Python just drops the decimal places, it’s not really a rounding process it just discards the data.
• Rounding is a different process that follows certain rules. The overall effect of truncation is the
same as rounding down.
• # should be 3.333… but python returns 3
# we have lost the 0.3333 part - it was discarded
• print 10 / 3
3
• # resulting is some subtle bugs
• print (10 / 3) * 3
9
• Look at these further examples :
• print (10 / 3) * 2
• 6
• print (10 / 3) * 2.0 # the 10/3 part has already lost precision so this is 3 * 0.2
• 6.0
• print (10 / 3.0) * 2.0 # now we get the decimal parts because 10/3.0 is 0.3333…
• 6.66666666667
Rules for negative truncation:
3.3333 => 3
-3.3333 => -4
18. Python long
• Any Integer larger or smaller than int.
print type (sys.maxint+1)
<type 'long'>
• Unlimited - actually limited to the amount of memory you have.
• Absolutely huge numbers - truly mind boggling.
• e.g. 128 bytes = 1024 bits
• 21024 =
`
1797693134862315907729305190789024733617976978942306572734300811577326758055009631
3270847732075360211201138798713933576587897688144166224928474306394741243777678934
2486548527630221960124609411945308295208500576883815068234246288147391311054082723
7163350510684586298239947245938479716304835356329624224137216
• That number is 1.79*10308
• There are ‘only’ around 1080 atoms in the visible universe.
19. Python Float
• Any number with a decimal place.
• “Floating point”
print type(3.141)
<type ‘float’>
• Again a huge range of numbers.
• Smallest
sys.float_info.min (2.2250738585072014e-308)
2.2250738585072014 * 10 -308
• Largest
sys.float_info.max (1.7976931348623157e+308).
1.7976931348623157 * 10 308
20. Python Primitive Types
• String – use double or single quotes to delimit the text.
• Can contain double or single quotes inside.
• Must match at the ends.
• “Mary had a little lamb, she also had some gravy”
• ‘Mary had a little lamb, she also had some gravy’
• “Mary had a ‘little’ lamb, she also had some gravy”
• ‘Mary had a “little” lamb, she also had some gravy‘
• boolean – hold value for True or False
• True and False are reserved words.
• Type of boolean is ‘bool’
21. Statements
• A statement is an instruction or command that Python will execute.
• We have seen two kinds of statements so far : print and assignment.
• When you declare a print statement in your code, Python executes it.
It puts characters on the screen.
Assignment statements don't produce a result.
• A script usually contains a sequence of statements which are
processed one at a time in the order they were written.
• For example, the script
• print 1
x = 2
print x
• produces the output
• 1
2
• Again, the assignment statement produces no output.
22. Expressions
• An expression is a combination of values, variables, and operators that are the calculations or logic you
want to execute.
• 1 + 1
• b + c
• PI * diameter
• Although expressions contain values, variables, and operators, not every expression contains all of these
elements. A value all by itself is considered an expression, and so is a variable.
• 17
• x
• In a script, an expression all by itself is a legal, but it doesn't do anything.
The following script results in nothing.
17
3.2
'Hello, World!'
1 + 1
23. Comments, Statements, Operators, Expressions,
Variables, Assignment
• Let’s put it all together.
• Remember a variable is also an expression.
• # Statement - it has an assignment using the operator
of an expression (“Spooky”)
to a variable (pet_name)
• This next line is a statement because of the print command.
Note the expressions and variables
pet_name = “Spooky”
print “%s is %i in earth years , %i in dog years.” % (pet_name, age_earth_years, age_dog_years)
pet_name
7age_earth_years
6dog_aging_rate
*
pet_name
age_dog_years age_earth_years dog_aging_rate
=
=
=
= *
=
24. In CodeSkulptor
Note : line 8 uses the “line continuation” character ‘’
http://www.codeskulptor.org/#user41_qHZ1pvOqLztPmGM.py
http://tinyurl.com/PythonExampleBLTI
25. The Modulus Operator %
• Gives the remainder of a division as an int
• print 12 % 5
2
%
27. Rock Paper Lizard Scissors Spock
Assign numbers to the 5
positions in the ring starting
with zero.
28. Rock Paper Lizard Scissors Spock
Rearrange in outcome order:
Make Rock zero.
Work out all outcomes from Rock’s perspective.
Put all of the opponents that rock’s will lose against on the
clockwise side.
29. Rock Paper Lizard Scissors Spock
Put all opponents that rock can
beat on the anti-clockwise
side.