Download presentation
Presentation is loading. Please wait.
Published byHester Walker Modified over 9 years ago
1
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/ Click, download it and install it.
2
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
3
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.
4
Participation Feedback is useful Stop me if you get confused. This is not a classroom If you need to leave, that’s obviously OK.
5
Natural Language and Formal Language Question: How is spoken language different to a programming language? Check out the next slide...
6
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.
7
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.
8
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. 3 + 3 = 6 is syntactically correct. 3 3 += 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.
9
What can computers do? Question: What are the basic building blocks of a computer program? What can you actually ask computers to do?
10
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).
11
First Steps Open IDLE (Python GUI) IDLE stands for Integrated DeveLopment Environment
12
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() ?
13
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
14
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
15
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.
16
Hidden or visible? Expressions return a value. Enter these: “Drew” 120 120 / 60 15 < 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!
17
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
18
Data Types Python works out the types for you.
19
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!
20
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.”)
21
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!)
22
Questions?
23
Input So, if print() can get things out of our program… …how do we get stuff in?
24
Input So, if print() can get things out of our program… …how do we get stuff in? Keyboard Mouse Files Internet
25
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.
26
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?
27
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.
28
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.
29
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?
30
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.
31
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)
32
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
33
Different types do different things Computers are fast, not clever.
34
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.
35
Nested functions Because functions return values, you can use them as parameters.
36
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
37
Questions?
38
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()
39
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) + “.”)
40
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)
41
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 ( : )
42
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.
43
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
44
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
45
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
46
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
47
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?
48
ASCII American Standard Code for Information Interchange
49
Application of Loops: Complex Series 1, 1, 2, 3, 5, 8, 13, 21, 34... The next number is always the sum of the previous two.
50
Fibonacci 1, 1, 2, 3, 5, 8, 13, 21, 34...
51
Fibonacci
52
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.
53
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.
54
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.
55
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.
56
Fibonacci This code creates the values in the Fibonacci series: f = [1, 1] for i in range(10): f = f + [ f[ -2 ] + f[ -1 ] ]
57
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)
58
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
59
Questions?
60
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.
61
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!”)
62
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!”)
63
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
64
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.
65
Questions?
66
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.
67
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.
68
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)
69
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 http://www.greenteapress.com/thinkpython/thinkpython.pdfhttp://www.greenteapress.com/thinkpython/thinkpython.pdf You can learn for free on Code Academy They do lots of courses, including one on Python
70
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
71
KWD KnowWant to knowDon’t know
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.