PROGRAMMING BASICS Programming for non-programmers. You will need Python 2.7.10 Go to https://www.python.org/downloads/https://www.python.org/downloads/

Slides:



Advertisements
Similar presentations
CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
Advertisements

Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
16-May-15 Sudden Python Drinking from the Fire Hose.
Jay Summet CS 1 with Robots IPRE Python Review 1.
Python (yay!) November 16, Unit 7. Recap We can store values in variables using an assignment statement >>>x = We can get input from the user using.
Python November 14, Unit 7. Python Hello world, in class.
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
Introduction to Python
Files in Python The Basics. Why use Files? Very small amounts of data – just hardcode them into the program A few pieces of data – ask the user to input.
Introduction to C Programming
While Loops and Do Loops. Suppose you wanted to repeat the same code over and over again? System.out.println(“text”); System.out.println(“text”); System.out.println(“text”);
Guide to Programming with Python Chapter Two Basic data types, Variables, and Simple I/O: The Useless Trivia Program.
What is RobotC?!?! Team 2425 Hydra. Overview What is RobotC What is RobotC used for What you need to program a robot How a robot program works Framework.
Working with Numbers in Alice - Converting to integers and to strings - Rounding numbers. - Truncating Numbers Samantha Huerta under the direction of Professor.
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
An Introduction to Textual Programming
Introduction to Python
Instructor: Chris Trenkov Hands-on Course Python for Absolute Beginners (Spring 2015) Class #001 (January 9, 2015)
Instructor: Chris Trenkov Hands-on Course Python for Absolute Beginners (Spring 2015) Class #002 (January 17, 2015)
CATHERINE AND ANNIE Python: Part 4. Strings  Strings are interesting creatures. Although words are strings, anything contained within a set of quotes.
Programing Concept Ken Youssefi/Ping HsuIntroduction to Engineering – E10 1 ENGR 10 Introduction to Engineering (Part A)
PYTHON: PART 2 Catherine and Annie. VARIABLES  That last program was a little simple. You probably want something a little more challenging.  Let’s.
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
Input, Output, and Processing
Instructor: Chris Trenkov Hands-on Course Python for Absolute Beginners (Spring 2015) Class #005 (April somthin, 2015)
5 BASIC CONCEPTS OF ANY PROGRAMMING LANGUAGE Let’s get started …
Conditions. Objectives  Understanding what altering the flow of control does on programs and being able to apply thee to design code  Look at why indentation.
Python Programming Using Variables and input. Objectives We’re learning to build functions and to use inputs and outputs. Outcomes Build a function Use.
Lesson 4 Using Variables in Python – Creating a Simple ChatBot Program.
C++ Basics C++ is a high-level, general purpose, object-oriented programming language.
Decisions in Python Bools and simple if statements.
1 Computer Science of Graphics and Games MONT 105S, Spring 2009 Session 1 Simple Python Programs Using Print, Variables, Input.
Variables, Expressions and Statements
Introduction to Python Lesson 1 First Program. Learning Outcomes In this lesson the student will: 1.Learn some important facts about PC’s 2.Learn how.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
COIT29222 Structured Programming 1 COIT29222-Structured Programming Lecture Week 02  Reading: Textbook(4 th Ed.), Chapter 2 Textbook (6 th Ed.), Chapters.
CRE Programming Club - Class 2 Robert Eckstein and Robert Heard.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
Python Let’s get started!.
Programming Seminar 2009 Night 0. Why we’re holding this seminar You’re probably not a computer science major – Or even anything remotely close (e.g.
Data Types and Conversions, Input from the Keyboard CS303E: Elements of Computers and Programming.
PROGRAMMING IN PYTHON LETS LEARN SOME CODE TOGETHER!
Introduction to Computer Programming - Project 2 Intro to Digital Technology.
Python Lesson 1 1. Starter Create the following Excel spreadsheet and complete the calculations using formulae: 2 Add A1 and B1 A2 minus B2 A3 times B3.
GCSE Computing: Programming GCSE Programming Remembering Python.
Python Basics  Values, Types, Variables, Expressions  Assignments  I/O  Control Structures.
Python Arithmetic Operators OperatorOperationDescription +AdditionAdd values on either side of the operator -SubtractionSubtract right hand operand from.
Instructor: Chris Trenkov Hands-on Course Python for Absolute Beginners (Spring 2015) Class #003 (February 14, 2015)
Part 1 Learning Objectives To understand that variables are a temporary named location to store data and that programmers work with different data types.
Python Review 1.
Whatcha doin'? Aims: To start using Python. To understand loops.
Input and Output Upsorn Praphamontripong CS 1110
Introduction to Python
CMSC201 Computer Science I for Majors Lecture 22 – Binary (and More)
Formatting Output.
ECS10 10/10
IF statements.
Variables, Expressions, and IO
Programming 101 Programming for non-programmers.
Formatting Output.
Engineering Innovation Center
Introduction to TouchDevelop
Introduction In today’s lesson we will look at: why Python?
Programming with Python, for beginners
Data Types Every variable has a given data type. The most common data types are: String - Text made up of numbers, letters and characters. Integer - Whole.
Data Types and Maths Programming Guides.
Hardware is… Software is…
Presentation transcript:

PROGRAMMING BASICS Programming for non-programmers. You will need Python Go to Click, download it and install it.

Objectives You will be able to: Write code! (And read it) Output and Input: Push and pull data to and from the user Data Types: Store information in the computer’s memory Loops: Repeat common operations Understand how programs are put together

4 Things To Bear In Mind Programming is more of a skill than a subject. Even if you memorise all the books, your first driving lesson isn’t going to be perfect. Reading code is easier if you read right to left. Think ‘6 = 3 + 3’ rather than ‘3 + 3 = 6’. Mistakes are useful. The more you make, the more you learn. I’m going to show you more than you need to know. It may not seem important, but it will help you find problems later.

Participation Feedback is useful Stop me if you get confused. This is not a classroom If you need to leave, that’s obviously OK.

Natural Language and Formal Language Question: How is spoken language different to a programming language? Check out the next slide...

Natural Language and Formal Language A uvetrsniiy fnuod taht wodrs wtih mxeid up leettrs cuold slitl be raed relleivaty esilay. Hndas up fi yuo cna raed tihs.

Natural Language and Formal Language A university found that words with mixed up letters could still be read relatively easily. Hands up if you can read this.

Natural Language and Formal Language Question: How is spoken language different to a programming language? Natural language can be structured or unstructured: “I’m going to the park later; are you coming?” “Park. Later. Coming?” Formal languages, like mathematics and Python have rules = 6 is syntactically correct = 6 is not. name = ‘Drew’ is syntactically correct. Put Drew in name is not. The words and symbols have to be in the right order.

What can computers do? Question: What are the basic building blocks of a computer program? What can you actually ask computers to do?

What can computers do? Compare and manipulate values This is done using operators. (+, -, *, /,, >, ≥, …) Store values in memory Variables hold values and have different types. Alter the flow of execution Loop through something a certain number of times. for loops, while loops Split the program into paths and control what happens when. if…else if…else statements, try…catch…finally statements Define and run functions Almost always followed by (brackets).

First Steps Open IDLE (Python GUI) IDLE stands for Integrated DeveLopment Environment

print(“Hello, World!”) Traditionally, the first program written in a new language outputs “Hello, World!” to the screen. So let’s do that. print(“Hello, World!”) Questions: What did that do? What can we learn from it? What else can we print() ?

print(“Hello, World!”) Questions: What did that do? Reading right to left: Set up a string parameter of “Hello, World!” Passed it to a function called ‘ print ’ Output the string to the screen

print(“Hello, World!”) Questions: What can we learn from it? 1) Python doesn’t need additional setup. The equivalent “Hello, World!” in C# is  2) The output function is print() 3) Functions can be spotted by their (brackets) 4) We can give functions extra information (parameters) in their brackets 5) Written text needs quotation marks around it

Hidden or visible? Some lines of code show you something. These are expressions. Could be a value or the result of a calculation. The value that comes out is called a ‘return value’. print() outputs text, which is different. Other pieces of code just run without showing you anything. These are statements. They usually do something useful, but do not need to be shown to the user.

Hidden or visible? Expressions return a value. Enter these: “Drew” / < 35 min(51, 79, 23, 18, 37) Try your own! Statements do not. Enter these: name = “Drew” seconds = 120 minutes = seconds / 60 Try your own!

Data Types 30 years ago computers had to be told exact data types, including: BooleanTrue or false DateYear, month, day, hour, minutes, seconds, milliseconds (+ zone) FloatFloating point (decimal) numbers DoubleDouble-precision floating-point numbers IntegerWhole numbers (no decimal places) LongVery big whole numbers CharSingle characters (either from a keyboard or special characters) StringOne or more characters put together

Data Types Python works out the types for you.

Putting It All Together Just as numbers can be added together to form bigger numbers, strings can be added to each other to form bigger strings. (This is called concatenation.) print(“Hello ” + “CodeUp” + “ people”) name = “Drew” print(“Hello ” + name) Remember the spaces – the computer won’t do it for you!

Putting It All Together Be aware of types when concatenating. Non-strings must be converted first… legs = 4 stringLegs = str(legs) print(“Most dogs have ” + stringLegs + “ legs.”) …though the conversion can be done ‘in-line’. print(“Most dogs have ” + str(legs) + “ legs.”)

Summary You have used Python You wrote your first program! Congratulations! How computers think Natural vs formal language Expressions vs statements Data types Functions Parameters, return values, (signatures!)

Questions?

Input So, if print() can get things out of our program… …how do we get stuff in?

Input So, if print() can get things out of our program… …how do we get stuff in? Keyboard Mouse Files Internet

Input Data coming into the program needs to be stored immediately, otherwise the computer loses track of it. For this we use variables. They hold data in memory so we can access it later. They have types (int, float, string, etc.) They have a name. Names can’t start with a number or a symbol.

Input There are two ways of getting data from the user. The first is as raw data. Raw data is pure, unprocessed text (i.e. string data) Try it: name = raw_input(“What is your name? ”) print(name) type(name) Questions: What did that do? What can we learn from it?

name = raw_input(“What is your name? ”) Questions: What did that do? Reading right to left: Set up a string parameter of “What is your name? ” Sent it to a function called ‘ raw_input ’ Waited for the user to enter data Assigned the new data a position in memory. Called that area of memory ‘name’ and typed it as a string variable.

name = raw_input(“What is your name? ”) Questions: What can we learn from it? Reading right to left: The string parameter we pass to raw_input() is used as a prompt. The function returns a value We can store the returned value ‘=’ (equals) is the assignment operator Variables do not have quotation marks around them.

Cooking the books raw_input() will always return the data entered as a string. If ‘raw’ is omitted, Python will ‘cook’ the input – work out its type. age = input(“How old are you? ”) print(age) type(age) Questions: What did that do? What can we learn from it?

age = input(“How old are you? ”) Questions: What did that do? Reading right to left: Set up a string parameter of “How old are you? ” Sent it to a function called ‘ input ’ Waited for input Assigned it a position in memory Worked out what type of value had been entered Called that area of memory ‘age’ and typed it as an int variable.

Cooking the books The type of data stored depends on whether we use raw_input() or input(). raw_input() always gives us a string type Even when we type in a number input() tries to run what we enter as code Think of it as ‘cooking’ the raw input b = input(“true or false? ”) type(b)

Different types do different things If there are 60 seconds in a minute, what fraction of a minute is 59 seconds? Try this: seconds = 59 type(seconds) seconds / 60 seconds = 59.0 type(seconds) seconds / 60

Different types do different things Computers are fast, not clever.

Different types do different things Another way to get around this is by converting the value. 59 will be treated as an integer unless you tell Python different. float(), int() and str() can all be used to change the type of a value.

Nested functions Because functions return values, you can use them as parameters.

Summary You have used functions print() sends data to the screen type() tells you the type of data raw_input() gets data from the user (as a string) input() gets data and treats it as code, working out the type automatically float(), int() and str() convert values There are many data types, used for different purposes bool (true or false); float (decimal); integer (whole number); string (text) The type of data affects how the computer processes it

Questions?

Quick Challenge 1 Write code to: Ask the user their name and store it to a string variable. Ask the user their age and store it to an int variable. Tell the person by name how old they will be in ten years. Operators: =, + Functions: raw_input(), input(), print()

Quick Challenge 1 name = raw_input(“What is your name? ”) age = input(“How old are you? ”) newAge = age + 10 print(“Hi ” + name + “.”) print(“In 10 years you will be ” + str(newAge) + “.”)

Loops Computers can process the same thing thousands of times. This is called looping and there are two types. for loops do things a certain number of times for i in range(10):for letter in “Hello”: print(i)print(letter) while loops do things while a condition is true i = 1 while i < 10: i = i + 1 print(i)

Loops Computers can process the same thing thousands of times. This is called looping and there are two types. for loops do things a certain number of times for i in range(10):for letter in “Hello”: print(i)print(letter) while loops do things while a condition is true i = 1 while i < 10: i = i + 1 print(i) Note the colons ( : )

Loops Computers can process the same thing thousands of times. This is called looping and there are two types. for loops do things a certain number of times for i in range(10):for letter in “Hello”: print(i)print(letter) while loops do things while a condition is true i = 1 while i < 10: i = i + 1 print(i) The gaps are also very important. This is how Python knows which lines are part of the loop and which lines are not.

Loop Control Loops can also be broken or continued. For example, if a point in a loop is reached where it’s pointless going any further, you can call the break statement. for i in range(10):while i < 10:print(i + 5) breaki += 1 break

Loop Control Loops can also be broken or continued. For example, if a point in a loop is reached where it’s pointless going any further, you can call the break statement. for i in range(10):while i < 10:print(i + 5) breaki += 1 break

Loop Control Loops can also be broken or continued. If you’ve done all you can with a certain value and want to start with the next one, you can continue. for i in range(10):while i < 10:print(i + 5) continuei += 1 continue

Loop Control Loops can also be broken or continued. If you’ve done all you can with a certain value and want to start with the next one, you can continue. for i in range(10):while i < 10:print(i + 5) continuei += 1 continue

Quick Break Lots of languages are developing shortcuts for loops Run the following: n = range(48,127) print n k = [[c,chr(c)] for c in n] print k Question: What does it do?

ASCII American Standard Code for Information Interchange

Application of Loops: Complex Series 1, 1, 2, 3, 5, 8, 13, 21, The next number is always the sum of the previous two.

Fibonacci 1, 1, 2, 3, 5, 8, 13, 21, 34...

Fibonacci

This code creates the values in the Fibonacci series: f = [1, 1] f = f + [ f[ -2 ] + f[ -1 ] ] We’re always taking two values; the second-to-last and the last.

Fibonacci This code creates the values in the Fibonacci series: f = [1, 1] f = f + [ f[ -2 ] + f[ -1 ] ] The same operation is done over and over. We may as well loop.

Fibonacci This code creates the values in the Fibonacci series: f = [1, 1] f = f + [ f[ -2 ] + f[ -1 ] ] The same operation is done over and over. We may as well loop.

Fibonacci This code creates the values in the Fibonacci series: f = [1, 1] for i in range(10): f = f + [ f[ -2 ] + f[ -1 ] ] The same operation is done over and over. We may as well loop.

Fibonacci This code creates the values in the Fibonacci series: f = [1, 1] for i in range(10): f = f + [ f[ -2 ] + f[ -1 ] ]

Fibonacci This code creates the values in the Fibonacci series: f = [1, 1] for i in range(10): f = f + [ f[ -2 ] + f[ -1 ] ] This is a statement, so we have to print out the values ourselves. print(f) or for n in f: print(n)

Summary Loops Useful for repetitive tasks Complex series, games, artificial intelligence Can be broken or continued ‘For’ Loops Do the same thing a limited amount of times ‘While’ Loops Check a condition each time and loop again if it is true

Questions?

If…ElseIf…Else: Controlling the Execution Path Let’s say we’re writing code for a game where you can only turn right. The user enters a heading to follow. If the heading entered is greater than 180, it will take us left. If the angle is less than 0, the program will break. So we have to change what the code does in different situations: If the angle is less than 0, change it to 0. If the angle is more than 180, change it to 180.

If…ElseIf…Else: Controlling the Execution Path minAngle = 0 maxAngle = 180 angle = input(“Which way do you want to go? ”) if angle < 0: angle = minAngle print(“You can’t go that way.”) elif angle > 180: angle = maxAngle print(“You can’t go that way.”) else: print(“Go go go!”)

If…ElseIf…Else: Controlling the Execution Path minAngle = 0 maxAngle = 180 angle = input(“Which way do you want to go? ”) if angle < 0: angle = minAngle print(“You can’t go that way.”) elif angle > 180: angle = maxAngle print(“You can’t go that way.”) else: print(“Go go go!”)

If…ElseIf…Else: Conditions Each if/elif/else has associated conditions which must be met in order for that piece of code to be run. These can be as short, long or complicated as you want. Just like in maths, brackets can be used to control the order of importance user = raw_input(“What’s your name? ”) angle = input(“What’s your heading? ”) if user == “Drew” and angle < 0: print(“You should know better”) elif user != “Drew” and (angle 180): #Change angle

Summary If-ElseIf-Else Used to control which pieces of code are run in different circumstances. Can have any number of logical checks in any order Comes in if, if-else, and if-elseif-else flavours.

Questions?

Your Turn That’s all the learning done. As I said at the beginning, the best way to learn it is to do it. Make mistakes, ask for help.

Challenge 1. Ask the user how many numbers of the Fibonacci set they want. 2. Generate the lines using the code we saw before: f = [1, 1] for i in range(howManyNumbers): f = f + [ f[ -2 ] + f[ -1 ] ] 3. Print the numbers.

Challenge howManyNumbers = input(“How many numbers do you want? ”) f = [1, 1] for i in range(howManyNumbers): f = f + [ f[ -2 ] + f[ -1 ] ] for number in f: print(f)

Well Done! Thank you for coming. I hope you enjoyed yourself. If you want to try some more: These slides will be made available online There is a book: “Think Python – How to Think Like a Computer Scientist” Free from You can learn for free on Code Academy They do lots of courses, including one on Python

The Learning Wheel Know you don’t knowKnow you know Don’t know you don’t know Don’t know you know DK KDK K DKK

KWD KnowWant to knowDon’t know