MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON
Table of contents 2 1. Learning Outcomes 2. Introduction 3. The first program: hello world! 4. The second program: hello (your name)! 5. More data types 6. Important things to know 7. If Statement 8. The third program: boy or girl? 9. For Statement 10. The fourth and fifth programs: your name + hello students! 11. While Statement 12. The sixth program: security word 13. Functions 14. Seventh program: my functions 15. Interesting links 16. Exercises
3 1. Learning Outcomes
Learning Outcomes 4 State the basis of Python programming Discover the data types Learn the different types of statements Do some simple programs
5 2. Introduction
Why Python? 6 Easy to learn Powerful programming language Efficient high-level data structures Simple but effective approach to object-oriented programming Elegant syntax and dynamic typing
How to use Python? 7 From the shell or from the saved programs. The shell executes each instruction as you type it Useful for experiments Each line starts with three chevron: >>> The saved programs are executed all at once. If something isn t correct, an error line will appear in red explaining which kind of mistake it is and where it is
How to get Python? 8 From a PC, downloadable for free in the official website: https://www.python.org/downloads/
How to get Python? 9 From Raspberry Pi, it is already downloaded and ready to use in the desktop (IDLE or IDLE 3)
Comments 10 They start with a hash character (#) They finish at the end of the line
Numbers 11 int: signed integer numbers long: long integers (can also be represented in octal or hex) float: real numbers, fractional part, floating point complex: complex numbers (j for the imaginary part)
Numbers 12 0x indicates hexadecimal L, l indicates long integer It is better to write an uppercase L to avoid confusion with the number 1
13 3. The first program: hello world!
First steps 14 Open the IDLE File / New File Write your code on the new window! Save it Save before running the program (ctrl + s) If not, it will ask you to save it. Always say yes! To run: Run / Run Module or F5 Be careful!!! Python is case sensitive To interrupt the program: ctrl+c
Hello world! 15
Hello world! 16
17 4. The second program: hello (your name)!
Hello (your name)! 18 Now, try it yourself! Create a questionnaire and swap places with your classmates to see who has the best one
19 5. More data types
Strings 20 Contiguous set of characters in between quotation marks, which can be simple ( ) or double ( ) Accessing a single positing of a string: String[n] Where n is the desired position Accessing more than one position in a string: String[0:2] Take the positions 0 and 1 of the string The first number is included The second isn t!! Remember: the first position is included, the last isn t
Strings 21 Accessing more than one position in a string: String[:2] Take the first two positions If there is no number 0, from the beginning String[2:] Take from the second position to the end If there is no number the end + concatenation * repetition
Strings 22 Now, try it yourself! Create a string and play with it
Lists 23 Enclosed within square brackets ([ ]) Separated by commas (,) It is possible to have different types of data within the same string They can be accessed as the strings
Lists 24 Now, try it yourself! Create a list (or two) and play with them
Tuples 25 Similar to lists, but tuples CAN T BE MODIFIED Only-read list Enclosed within parentheses ( ( ) ) Separated by commas
Tuples 26
Modifying Lists 27 Now, try it yourself! Take the lists that you ve just created and modify some elements
Dictionary 28 Enclosed within curly brackets ({ }) Separated by commas (,) It is possible to have different types of data within the same dictionary Function (variable) in (dictionary) It tells us whether the variable is in the dictionary (True) or not (False)
Dictionary level 1 29 Now, try it yourself! Create your own shopping list
Dictionary level 2 30 Now, try it yourself! Create your own personalised messages for checking the items on your shopping list
Dictionary level 3 31 Now, try it yourself! Swap places with your classmates and see who gets the highest score
Converting types 32 int(x [,base]) long(x [,base] ) float(x) complex(real [,imag]) str(x) tuple(s) list(s) hex(x) oct(x) Converts x to an integer. base specifies the base if x is a string. Converts x to a long integer. base specifies the base if x is a string. Converts x to a floating-point number. Creates a complex number. Converts object x to a string representation. Converts s to a tuple. Converts s to a list. Converts an integer to a hexadecimal string. Converts an integer to an octal string.
Calculator 33 + - * will return the same type of number if one is float, then the result will be float / will always return a float (decimals) // forces a floor division (no decimals) div % calculates the remainder mod
Calculator 34 Integer Float Now, try it yourself! Do some Maths directly on the Shell
35 6. Important things to know
Important things to know 36 Declaration: = Used to define the value of a variable or a constant Comparison: == Used to compare one variable or constant with a value It appears in statements such as if and while print ( ) len(string) help(topic) parentheses needed! it gives you the length of a string it opens the help menu about the topic No need for semicolon at the end of the sentences! Key words in lowercase!
Important things to know 37 Identifiers: Must start with a letter or an underscore Punctuation characters, @, $,, %, etc. are not allowed \n It creates a line break You can write as many as you want together to create more than one blank line. eg. \n\n\n would create 3 blank lines True and False (Boolean) must have the first letter upper-case! If so, they should be red (automatic)
Important things to know 38 If we don t want to end the program until the user has pressed the enter key: input( Press the enter key to exit ) (Yes, it has to be the enter key) If you are printing strings and numbers in the same line (the same print statement), you should convert the numbers to string using the function str() print( Your favourite number is +str(favnumber))
Important things to know 39 If we need that a string occupies more than one line, start it with triple quotes ( ) or ( ) If a string has to contain an apostrophe ( ), it should be written with a backslash before it to avoid Python interpreting it as the end of the string eg. print( They aren\ t studying hard enough.)
Coding Styles 40 Use 4-space indentation, and no tabs. Wrap lines so that they don t exceed 79 characters. Use blank lines to separate functions and classes, and larger blocks of code inside functions. When possible, put comments on a line of their own. Use spaces around operators and after commas, but not directly inside bracketing constructs: a = f(1, 2) + g(3, 4)
Common Mistakes 41 Double check that: The indentation of all loops is correct The blank spaces ( ) are where they should be Extra spaces may lead into errors All brackets are closed When editing the code, whichever is enclosed in the brackets will be momentary highlighted in grey You have colons (:) after statement words The spelling of the variables, functions and constants is the same throughout all the code Remember that Python is very sensitive!
42 7. If Statement
if 43 if (condition 1): Action 1 if (condition 1): else: Action 1 Action 2 if (condition 1): Action 1 elif (condition 2): Action 2 elif (condition 3): Action 3
44 8. The third program: boy or girl?
Boy or girl? version 1 45 We need to convert the input to an integer! Now, try it yourself! Create your own personalised messages and options
Boy or girl? version 1 46
Boy or girl? version 2 47 Now, try it yourself! Create your own personalised messages
Boy or girl? version 2.2 48 Now, try it yourself! Create your own personalised messages with different options and different questions
49 9. For and Range Statements
For 50 In other programming languages, for is used to iterate a sequence over certain conditions defined by the user but not in Python! In Python, it iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. for (i) in (string):
For 51 Now, try it yourself! Create your own list and iterate on it to print all of its elements on separate lines Why not trying adding something after each word?
Range 52 Is like the for function in other programming languages for (i) in range(n): Remember that Python works with 0 as the first element! Now, try it yourself!
53 10. Fourth and fifth programs: your name + hello students
Your name in different lines 54 Now, try it yourself! Create your own question and iterate it
Hello students 55 Now, try it yourself! Create your own list and iterate on it to print all of its elements on separate lines with a message
56 11. While Statement
While 57 The loop is executed as long as the condition is true Operands for the condition: < > == <= >=!= less than greater than equal to less than or equal to greater than or equal to different to while (True): Infinite loop!
While 58 Now, try it yourself! Create your own loop with some operations on it
59 12. Sixth program: security word
Security word level 1 60
Security word level 2 61 If the user has typed the security word wrong 5 times, then wait for 30 seconds before allowing the user to type it again. To do so: import time (at the very beginning of the program) when you want the delay: time.sleep(s) being s the number of seconds you want the program to stop
Security word level 3 62 If the user writes down the security word wrong 5 times, wait for 30 seconds. The second time that the user writes 5 wrong security words, wait for 60 seconds. The third time, wait for 90 seconds. The fourth, 120 seconds. And so on
Security word level 3 63
Security word PRO 64 Now, we are going to emulate a login system from any website/computer First, you need to ask the user for a login name
65 13. Functions
Functions 66 Useful for shortening the code and automatising sets of actions that will be repeatedly used together and in the same order def function_name(internal_name_input1, internal_name_input2): print(output1, output2) To call it: function_name(value_1st_input, value_2nd_input)
Functions 67 Now, try it yourself! Create your own function and call it as man times as you want with different input values
68 14. Seventh program: my functions
My functions 69 Create a function sum() and a function multiply() that sums and multiplies (respectively) all the numbers in a list of numbers. Make sure that it works with any list of numbers, regardless of its length. For that, create a couple of lists which have different lengths and try to call the function with each.
My functions solutions 70 Now, try it yourself! Create your own list and use it in a function
My functions solutions 71 Now, try it yourself! Create your own list and use it in a function
72 15. Interesting links
Interesting links 73 https://docs.python.org/3/ https://docs.python.org/2/reference/index.html http://www.pythoncourse.eu/sequential_data_types.php http://www.tutorialspoint.com/python/
74 16. Exercises Remember to do the flowchart and the pseudo code BEFORE programming!!!
0: A, B, C, D or E? 75 Take the pseudo code of the exercise where the user is asked the result of an exam (0-100) and the program returns the equivalent mark in terms of A, B, C, D or E.
0: A, B, C, D or E? solution 76
1: Histogram 77 Create a program which, given 7 inputs, writes down a histogram. (Note that some of the inputs can be 0) eg. 2, 5, 6, 8, 10, 7, 11 ** ***** ****** ******** ********** ******* ***********
1: Histogram solution 78
1: Histogram solution 79
1: Histogram solution with for and list 80
2: 99 bottles of beer 81 Level 1: Traditional song in the USA and Canada 99 bottles of beer on the wall, 99 bottles of beer. Take one down, pass it around, 98 bottles of beer on the wall. 98 bottles of beer on the wall, 98 bottles of beer. Take one down, pass it around, 97 bottles of beer on the wall. etc. Create a Python program which generates all the verses of this song.
2: 99 bottles of beer 82 Level 2: Modify the last verse like this (underlined): 1 bottle of beer on the wall, 1 bottle of beer. Take one down and pass it around, no more bottles of beer on the wall. No more bottles of beer on the wall, no more bottles of beer. Go to the store and buy some more, 99 bottles of beer on the wall.
2: 99 bottles of beer 83 Level 3: If you have developed your code using range, now use while If you have developed your code using while, now use range Level 4: Learn the song and sing it!
2: 99 bottles of beer solution 84 Using range
2: 99 bottles of beer solution 85 Using while
2: 99 bottles of beer solution 86
3: age guess 87 Level 1: start with the basic functionality Ask the year when the user was born Display the age Level 2: Polish the program asking the user if he or she has already celebrated the birthday this year. This will mean a ± 1 year. Level 3: Greet the user and make a sentence with his or her name plus his or her age eg. (name), you re (age) years old!
3: age guess 88 Level 4: If the user has born this year, display a special message eg. You are still a baby! Level 5: Avoid negative ages by displaying a message if the user enters a year superior to that we are in (2014) eg. Oops! You aren t born yet! Level 6: In the same situation as before, ask the user to come back in X years time, when he or she will be born eg. Come back in (X) years time!
3: age guess 89 Level 7: Instead of pressing 1 or 2 to know if the birthday has been celebrated yet, ask the user to write yes or no (lowercase) Level 8: Create age blocks with personalised messages for each 1~12: 13~19: 20~30: 31~65: >65: You are a child! You are a teenager! You are a youngster! You are an adult! You are a senior!
3: age guess solution 90 Levels 1 to 6
3: age guess solution 91 Levels 7 and 8
The random function with a list 92 1. Import the random module at the very first line of the program. import random 2. Create a list of things to be randomly picked. This means that if you want a random animal, you will have to create a list of animals. 3. Assign to a variable a random value of the list. my_fav_animal = random.choice(animals) 4. Now you can use my_fav_animal as usual!
The random function with a list 93 Now, try it yourself! Create your own list and randomly pick one of its items
The random function with numbers 94 1. Import the random module at the very first line of the program. import random 2. Assign to a variable a random value of the defined range. random_num = random.randint(1,100) 3. Now you can use your random_num as usual!
The random function with numbers 95 Now, try it yourself! Randomly pick one number from a defined range
4: Story time 96 You are going to create a story which will be different every time you run the program For that, we will create different lists and use the random function
4: Story time 97 Ask the user his or her name and gender and store them in appropriate variables Create a variable called pronoun which will obviously be he, she or it. Assign it depending on the gender Create four lists: Roles, names, actions and places eg. roles = [ knight, princess, prince, wizard ] They can have as many items as you want and not all the list have to have the same number of words
4: Story time 98 Now write the story, all in the same line! Suggestion: write the story in a variable and then do a print of this variable If you aren t feeling imaginative, you can borrow this story: Once upon a time, there was a (role) called (user s name). (pronoun) and some friends found themselves in the magic land of (place). This land was ruled by (name) the (role2). All of a sudden a mysterious voice spoke to them from high in the sky and said: you must (action) (name) the (role2) to lift the curse of not being able to use technology
4: Story time solution 99
5: Guess the number 100 Level 1: The program will randomly generate a number between 1 and 100 and the user will have to guess it. To help the user, the program will say whether the number to be guessed is higher or lower than that the user entered. Level 2: Interact with the user and display personalised messages with his or her name.
5: Guess the number 101 Level 3: Count how long does it take to the user to guess the number and display different messages depending if the user has guessed it in the first round or not. Level 4: If the number guessed by the user is really close to the actual number (let s say it s 5 or less units lower or higher), display a special message
5: Guess the number a bit of help 102 Level 4: if users_num < random_num: if users_num random_num <= 5 print ( You\ re almost there! Just a little bit higher! ) if users_num > random_num: if users_num random_num >= 5 print ( You\ re almost there! Just a little bit lower! )
6: Hangman 103 I guess you all know how to play hangman! The user can only fail 5 times Level 1: Fixed word The remaining guesses are just a number on the screen (not the actual hangman) Level 2: List of words, random choice of them
6: Hangman 104 Level 3: Display a hangman. You can do one like this: O \_ _/ / \ d b Level 4: Give the option that another user writes down the secret word! (If there is only one player, the program will choose the secret word. If there are two players, the first user will write the word down and the second will have to guess it). Hint: after the 1 st player has written down the word, introduce a lot of spaces so the 2 nd player can t see the word!
6: Hangman solution 105 Levels 1 to 3
6: Hangman solution 106 Level 4