The Big Python Guide

Similar documents
Text Input and Conditionals

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Programming with Python

If Statements, For Loops, Functions

Part III Appendices 165

Algorithm Design and Recursion. Search and Sort Algorithms

Data Structures. Lists, Tuples, Sets, Dictionaries

Admin. How's the project coming? After these slides, read chapter 13 in your book. Quizzes will return

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

Creating the Data Layer

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

An Introduction to Python

THE IF STATEMENT. The if statement is used to check a condition: if the condition is true, we run a block

Intro. Scheme Basics. scm> 5 5. scm>

cs1114 REVIEW of details test closed laptop period

Honors Computer Science Python Mr. Clausen Programs 4A, 4B, 4C, 4D, 4E, 4F

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

ENGR 102 Engineering Lab I - Computation

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

Python Intro GIS Week 1. Jake K. Carr

Python: common syntax

Slicing. Open pizza_slicer.py

Introduction to Python (All the Basic Stuff)

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

Lab 4: Strings/Loops Due Apr 22 at midnight

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

Exercise: Inventing Language

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

Stratford School Academy Schemes of Work

Program Planning, Data Comparisons, Strings

Selection statements. CSE 1310 Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington

Coding Workshop. Learning to Program with an Arduino. Lecture Notes. Programming Introduction Values Assignment Arithmetic.

CSCE 110 Programming I

Notes on Chapter 1 Variables and String

3.4. FOR-LOOPS 65. for <v a r i a b l e > in < sequence >:

Python Unit

1 Lecture 5: Advanced Data Structures

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

LOOPS. Repetition using the while statement

A453 Task 1: Analysis: Problem: Solution:

Outline: Search and Recursion (Ch13)

EXCEL BASICS: MICROSOFT OFFICE 2010

Introduction to String Manipulation

(Python) Chapter 3: Repetition

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

Flow Control: Branches and loops

Variables and Data Representation

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

2SKILL. Variables Lesson 6. Remembering numbers (and other stuff)...

Types, lists & functions

To become familiar with array manipulation, searching, and sorting.

CMSC201 Computer Science I for Majors

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

Decisions, Decisions. Testing, testing C H A P T E R 7

Fun facts about recursion

CS Summer 2013

CS 115 Lecture 8. Selection: the if statement. Neil Moore

Basics of Programming with Python

4. Use a loop to print the first 25 Fibonacci numbers. Do you need to store these values in a data structure such as an array or list?

Control Structures 1 / 17

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

EXCEL BASICS: MICROSOFT OFFICE 2007

Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi.

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

Variables and numeric types

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

CMSC 201 Spring 2017 Homework 4 Lists (and Loops and Strings)

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

Variables, expressions and statements

Play with Python: An intro to Data Science

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

Introduction to Python Code Quality

Python 1: Intro! Max Dougherty Andrew Schmitt

Chapter 1. Data types. Data types. In this chapter you will: learn about data types. learn about tuples, lists and dictionaries

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

printf( Please enter another number: ); scanf( %d, &num2);

Python for Non-programmers

CMPT 120 Control Structures in Python. Summer 2012 Instructor: Hassan Khosravi

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Collections. Lists, Tuples, Sets, Dictionaries

Introduction to Programming

Introduction to Programming with JES

Search Lesson Outline

Introduction to Computation for the Humanities and Social Sciences. CS 3 Chris Tanner

Zipf's Law. This preliminary discussion gives us our first ideas about what the program we're writing needs to do.

[ the academy_of_code] Senior Beginners

MITOCW watch?v=0jljzrnhwoi

Beyond Blocks: Python Session #1

MITOCW watch?v=se4p7ivcune

Here n is a variable name. The value of that variable is 176.

Iteration. # a and b are now equal # a and b are no longer equal Multiple assignment

Downloaded from Chapter 2. Functions

CMPT 120 Basics of Python. Summer 2012 Instructor: Hassan Khosravi

Transcription:

The Big Python Guide Big Python Guide - Page 1

Contents Input, Output and Variables........ 3 Selection (if...then)......... 4 Iteration (for loops)......... 5 Iteration (while loops)........ 6 String Manipulation......... 7 Lists........... 10 Text File Handling......... 12 CSV File Handling......... 13 Random Numbers......... 15 Validation.......... 16 Exceptions.......... 18 Procedures and Functions........ 20 Big Python Guide - Page 2

Topic 1 - Input, Output and Variables To display something on the screen in Python you use the print keyword. For example: will display Hello world on the screen when run. To collect information from the user, you can use the input keyword - there are two ways to do this: Or you could a similar thing by doing: In both examples, what the user types in is stored in a variable called yourname. Variables are temporary storage spaces in RAM that allow you to keep information that you will use later in your program. Variables have different types which refer to the types of information that you are storing and what can be done with them. The main types are: String (text) - known in python as str Integer (whole number) - known in python as int Float (numbers with decimal points) - known in python as float Boolean (special variable that can only be True or False) - known in python as boolean If you use input, whatever is typed in is treated as text. This might mean that if you are writing a program to add two numbers (for example) you will need to tell Python to store it as a number instead of text. An example is shown below: You can also use variables at the start, in the middle, or at the end of a print statement. Adapting the program above: Big Python Guide - Page 3

Topic 2 - Selection (if...then) Often in programming you want your computer to make a decision. This is where you can use if...then to decide what to do. An example is shown below: The first choice always begins with if, other options are elif (short for else if) and finally if none of the above match else will deal with that. if and elif both use conditionals to make decisions. The main ones are: Conditional Name Symbol Equals == Greater Than > Less Than < Greater Than or Equals To >= Less Than or Equals To <= Not Equals!= You can also use combine conditionals using and, or, not. For example, in the example above if we wanted to accept both upper and lower case A to choose Open File we could use: The line(s) following an if, elif or else are always indented to indicate that the lines are part of that decision. Big Python Guide - Page 4

Topic 3 - Iteration (for loops) Iteration is also known informally as loops. This is where you want to repeat a set of instructions a certain number of times. There are two ways to do this, a for loop and a while loop. We use a for loop when you know in advance how many times a loop needs to loop. The above example will display the six times table from 0x6 to 12x6 (for some reason in Python, when using range always go one higher). counter is an integer variable which is created by the for loop to keep track of how many times the loop has counted round. You can break out of a for loop at any time using the break keyword. Big Python Guide - Page 5

Topic 4 - Iteration (while loops) Iteration is also known informally as loops. This is where you want to repeat a set of instructions a certain number of times. There are two ways to do this, a for loop and a while loop. We use a while loop when we don t know in advance how often to loop a set of instructions. The above example will keep looping while the guess does not match the password. When the password is guessed correctly then the loop stops and the message Password accepted is displayed on screen. You can also use a while loop as an infinite loop. This is where a loop continues until a break keyword is issued - useful for menu systems. The easiest way to do this is to say while True - as True is always True! For example: In the example above, the loop continues until Q is entered, triggering the break command. Big Python Guide - Page 6

Topic 5 - String Manipulation Python calls text a string - the word string comes from a string of characters. Python has quite advanced string manipulation techniques. This allows us to slice strings (extracting parts of what is stored), to find out how many characters are in a string and to change the text stored in a string in a certain kind of way. To get part of a string, we can use string slicing: This will display the letter J as it is the first letter in the string myfullname - remember that in Python lists start at zero (and Python treats a string as a fancy list!). To get a few letters from a string, we can change it slightly to slice more out: This will display the word John as it starts at character 0 and has a length of 4 characters. To find out how many letters are in a string is easy - we use the len keyword: This will display the answer 10 as there are 10 characters (including the space) in the string myfullname. We can count how many times a certain character is in a string: This will display the answer 2 as the character h appears twice in the string - note it is also case sensitive. We can find out the location in the string that a word begins at: This will display the answer 5 as the word Smith begins at location number 5 in the myfullname string (which is a list..!) Big Python Guide - Page 7

We can replace words: This will replace the word John with the word Jane, displaying Jane Smith as the answer. We can change the case of letters in the string: This will display: You can reverse the contents of a string: Which will display htims nhoj - the string in reverse order. The Python is a bit weird here, don t worry too much about it! You can put two strings together quite easily: This takes the contents of the first string John, adds a space, then adds Smith displaying John Smith. This is also known as concatenation. Big Python Guide - Page 8

You can also test a string to see if it has certain characters or not. You can do this using an if...then with the string. For example: The tests that can be done with strings are:.isalnum() checks to see if the string is alphanumeric.isalpha() checks to see if the string is only made up of letters.isdigit() checks to see if the string is only made up of numeric digits.isupper() checks to see if the string is only UPPER CASE.islower() checks to see if the string is only lower case.startswith( J ) checks to see if the string starts with the character J.endswith( h ) checks to see if the string ends with the character h Big Python Guide - Page 9

Topic 6 - Lists Lists are collections of data of the same type of information. For example if I was collecting a list of names, I would use a list. Creating a list in Python is easy: Each item in the list has an index number starting a zero. So listofnames[0] is Andrew, listofnames[1] is John, listofnames[2] is Adam and so on. We can display individual list items easily: This will display Adam as that name is in position 2 in the list (remember we start counting at zero). To display each of the items in a list we can use a for...next loop to do so: This will display each name in the list on a separate line on the screen. We can also display only some names, again using a for...next loop to do so: This starts at list item [2] - which is Adam and goes two times to the number 4 - in this case it will display Adam and then Carol. When using a for...next loop with a list always go one above where you think you should stop. (Continues on next page) Big Python Guide - Page 10

You can also add and remove things to and from a list: The above code creates an empty list to start with, then appends three items to the list, displays them, removes Bananas from the list and redisplays the list. You can also sort lists into numeric or alphabetical order. For example: This will display Adam Andrew Carol John as that would be the correct alphabetical order. You can also find out if an item is in a list. For example: Big Python Guide - Page 11

Topic 7 - Text File Handling In Python you may wish to transfer information from RAM to secondary storage (e.g. hard drive or network drive) so that is can be kept and used again. This is where file handling is useful. You can read or write information to and from a text file. For example, the following code writes a list of items to a text file: To open the file, you create a file object - it needs a filename and a mode. The filename is the name of the file - the file will be created in the same folder as your Python program. The mode is w for writing and r for reading. Each item is written to a file in a similar way to printing something on screen. After using a file it must be closed, otherwise the information will not be correctly written to the text file and you may lose data. To read information back into a list, it is essentially the reverse of the program above: The program above creates an empty list, opens the text file in read mode, copies the contents of the text file into the listofnames list, closes the file then displays the contents of the listofnames as normal. Big Python Guide - Page 12

Topic 8 - CSV File Handling In Topic 7 you looked at how you can use a plain text file to store information. Up until now we have written and read data to/from a simple text file. This is OK, but it s not great for lists of items. Instead, we can use Comma Separated Values (or CSV) for lists. This is where a list can be written out to a file with each element separated by a comma. For example if I had an address book CSV file it would look like: Adam,45 Kilbourne Road,Belper,Derbyshire,DE56 0DJ Andrew,12 High Street,Belper,Derbyshire,DE56 0AB Carol,22 Market Place,Belper,Derbyshire,DE56 1LK John,53 Middle Street,Belper,Derbyshire,DE56 2KD Each row in the file is a different record, each piece of data is separated by a comma. To use a CSV file effectively we must know what each piece of data is for this file it is: Name,Address,Town,County,Postcode Python has a CSV file handling function that we can use in conjunction with lists and for loops. If I wanted to display the name of each person in my address book the code would look like: The program first imports the CSV file handling module built into Python. It then tries to open a file called addressbook.txt (note it must be in the same folder as your Python program). It then copies the structure of the file into a variable called reader. It then creates a list called addresslist using the information stored in the reader variable. To display the details it is easy, simply use a for loop for each person's details we can choose to display what we want. In our example: details[0] is the name details[1] is the address details[2] is the town details[3] is the county details[4] is the postcode Big Python Guide - Page 13

So if we wanted to display name and postcode you could change the code to: Big Python Guide - Page 14

Topic 9 - Random Numbers In Python it is common to want to generate random numbers for use in a program. To do this we can use the random number library that is bundled with Python. Here is a program that uses random numbers: You must put import random at the top of any program that you want to use random numbers in. It should only appear at the top and not appear anywhere else in your program. random.randint(1,5) chooses a random number between 1 and 5. Note that unlike lists and for...next loops, random.randint includes the lowest and highest numbers you enter. If you want a random floating point number then you would use random.uniform(1,10) to choose a floating point random number between 1.0 and 9.9999 (recurring) Big Python Guide - Page 15

Topic 10 - Validation In programming you will often want to check what a user has entered is valid - in other words it is what you expect the user to type in. There are a few forms of validation that you might want to use. In the examples below we are going to use the following situation where you are asking for the user s mobile phone number and first name. The best way to check what a user has typed in is to use a while loop in conjuction with a Boolean flag. This means that if the user types in an answer, it is checked and it is wrong (or False in Boolean speak), then we will ask the question again. If when it is checked it is right (or True in Boolean speak) we can continue. For example: A mobile phone number (without any spaces or punctuation) is 11 digits long. This is the example we showed above - if the len gth of the mobile phone number is 11 then it is valid so we can continue. Otherwise (else) say it is wrong and continue. So for length checks use the keyword len. A mobile phone number should only be made up of digits. A good way to check for this is to use the.isdigit() method with a string. For example: Big Python Guide - Page 16

A person s name should always start with a capital letter. We can use the.isupper() method of a string, and a bit of string slicing to find out if the name has been entered correctly: There are certain types of user input or validation checks that can raise exceptions - so you may also wish to have a look at Topic 11 - Exceptions for more information. Big Python Guide - Page 17

Topic 11 - Exceptions Look at the program below: This program works fine if you type in numbers. But what if the user is stupid and types in the following? Clearly it is impossible for Python to turn the string elephant into an integer. So Python will throw what is called an exception: You will have seen these before when you as a programmer have done something stupid. In this case though it is the user being stupid and it should not be possible to cause a well written program to crash through user stupidity! You will notice that the exception has a type - in this case it is a ValueError. It is a ValueError as the program can t change it into an integer (it even says that in computer scientist speak on the error line!). This is where exceptions are useful. We can catch an exception and tell the user off - this is often carried out in conjunction with validation. Let s fix our code to catch user errors: (continued on the next page) Big Python Guide - Page 18

The code above will try and get the user input. If an exception is thrown an error message is shown and because we set valid to False, it will keep asking until the user enters a valid number. By combining validation and exceptions, you can make your code robust. To get the top mark bands in controlled assessment your code must be robust. Always assume that the user will enter incorrect output and think about what you can do to stop them. Big Python Guide - Page 19

Topic 12 - Procedures and Functions When developing longer programs, you may well wish to break it up into reusable chunks. This makes it easier to work with and in many cases also makes it more efficient. For example if you wanted to write a program that rolls a six sided dice three times you could use the following code: The above code works - but let s say you wanted to roll and display the three six sided dice several times in your program? That s a lot of copy and pasting and makes your code inefficient. We could therefore spin this out into a procedure: The example above will roll and display the results of nine dice rolls by calling the rollanddisplaydice() procedure three times. Nifty and more importantly efficient. To get top mark bands in the controlled assessment you must make efficient code. In the above examples you used a procedure - this is where Python will carry out the instructions and your program gets no feedback. Let s look at functions - this is where a result is returned to your code. Big Python Guide - Page 20

Imagine you are writing a program to work out the current in a circuit using Ohm s Law. You could write a function like this: In the example above, instead of using (), the function has two parameters that are passed to it - voltage and resistance. The function calculates the answer then returns that value to the caller. The caller then displays the result. As you can see, procedures and functions when used well can make programs more efficient, easier to write and easier to understand. Big Python Guide - Page 21