The Big Python Guide

Size: px
Start display at page:

Download "The Big Python Guide"

Transcription

1 The Big Python Guide Big Python Guide - Page 1

2 Contents Input, Output and Variables Selection (if...then) Iteration (for loops) Iteration (while loops) String Manipulation Lists Text File Handling CSV File Handling Random Numbers Validation Exceptions Procedures and Functions Big Python Guide - Page 2

3 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

4 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

5 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

6 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

7 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

8 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

9 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

10 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

11 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

12 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

13 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

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

15 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 (recurring) Big Python Guide - Page 15

16 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

17 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

18 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

19 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

20 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

21 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

Text Input and Conditionals

Text Input and Conditionals Text Input and Conditionals Text Input Many programs allow the user to enter information, like a username and password. Python makes taking input from the user seamless with a single line of code: input()

More information

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

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

Programming with Python

Programming with Python Programming with Python Dr Ben Dudson Department of Physics, University of York 21st January 2011 http://www-users.york.ac.uk/ bd512/teaching.shtml Dr Ben Dudson Introduction to Programming - Lecture 2

More information

If Statements, For Loops, Functions

If Statements, For Loops, Functions Fundamentals of Programming If Statements, For Loops, Functions Table of Contents Hello World Types of Variables Integers and Floats String Boolean Relational Operators Lists Conditionals If and Else Statements

More information

Part III Appendices 165

Part III Appendices 165 Part III Appendices 165 Appendix A Technical Instructions Learning Outcomes This material will help you learn how to use the software you need to do your work in this course. You won t be tested on it.

More information

Algorithm Design and Recursion. Search and Sort Algorithms

Algorithm Design and Recursion. Search and Sort Algorithms Algorithm Design and Recursion Search and Sort Algorithms Objectives To understand the basic techniques for analyzing the efficiency of algorithms. To know what searching is and understand the algorithms

More information

Data Structures. Lists, Tuples, Sets, Dictionaries

Data Structures. Lists, Tuples, Sets, Dictionaries Data Structures Lists, Tuples, Sets, Dictionaries Collections Programs work with simple values: integers, floats, booleans, strings Often, however, we need to work with collections of values (customers,

More information

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

Admin. How's the project coming? After these slides, read chapter 13 in your book. Quizzes will return Recursion CS 1 Admin How's the project coming? After these slides, read chapter 13 in your book Yes that is out of order, but we can read it stand alone Quizzes will return Tuesday Nov 29 th see calendar

More information

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

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1 Review Midterm Exam 1 Review Midterm Exam 1 Exam on Monday, October 7 Data Types and Variables = Data Types and Variables Basic Data Types Integers Floating Point Numbers Strings Data Types and Variables

More information

Creating the Data Layer

Creating the Data Layer Creating the Data Layer When interacting with any system it is always useful if it remembers all the settings and changes between visits. For example, Facebook has the details of your login and any conversations

More information

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

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

An Introduction to Python

An Introduction to Python An Introduction to Python Day 2 Renaud Dessalles dessalles@ucla.edu Python s Data Structures - Lists * Lists can store lots of information. * The data doesn t have to all be the same type! (unlike many

More information

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

THE IF STATEMENT. The if statement is used to check a condition: if the condition is true, we run a block THE IF STATEMENT The if statement is used to check a condition: if the condition is true, we run a block of statements (called the if-block), elsewe process another block of statements (called the else-block).

More information

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

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

cs1114 REVIEW of details test closed laptop period

cs1114 REVIEW of details test closed laptop period python details DOES NOT COVER FUNCTIONS!!! This is a sample of some of the things that you are responsible for do not believe that if you know only the things on this test that they will get an A on any

More information

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

Honors Computer Science Python Mr. Clausen Programs 4A, 4B, 4C, 4D, 4E, 4F PROGRAM 4A Full Names (25 points) Honors Computer Science Python Mr. Clausen Programs 4A, 4B, 4C, 4D, 4E, 4F This program should ask the user for their full name: first name, a space, middle name, a space,

More information

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

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT Python The way of a program Srinidhi H Asst Professor Dept of CSE, MSRIT 1 Problem Solving Problem solving means the ability to formulate problems, think creatively about solutions, and express a solution

More information

ENGR 102 Engineering Lab I - Computation

ENGR 102 Engineering Lab I - Computation ENGR 102 Engineering Lab I - Computation Week 07: Arrays and Lists of Data Introduction to Arrays In last week s lecture, 1 we were introduced to the mathematical concept of an array through the equation

More information

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

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and

More information

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

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently. The Science of Computing I Lesson 4: Introduction to Data Structures Living with Cyber Pillar: Data Structures The need for data structures The algorithms we design to solve problems rarely do so without

More information

Python Intro GIS Week 1. Jake K. Carr

Python Intro GIS Week 1. Jake K. Carr GIS 5222 Week 1 Why Python It s simple and easy to learn It s free - open source! It s cross platform IT S expandable!! Why Python: Example Consider having to convert 1,000 shapefiles into feature classes

More information

Python: common syntax

Python: common syntax Lab 09 Python! Python Intro Main Differences from C++: True and False are capitals Python floors (always down) with int division (matters with negatives): -3 / 2 = -2 No variable data types or variable

More information

Slicing. Open pizza_slicer.py

Slicing. Open pizza_slicer.py Slicing and Tuples Slicing Open pizza_slicer.py Indexing a string is a great way of getting to a single value in a string However, what if you want to use a section of a string Like the middle name of

More information

Introduction to Python (All the Basic Stuff)

Introduction to Python (All the Basic Stuff) Introduction to Python (All the Basic Stuff) 1 Learning Objectives Python program development Command line, IDEs, file editing Language fundamentals Types & variables Expressions I/O Control flow Functions

More information

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

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n) Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Module 10A Lecture - 20 What is a function?

More information

Lab 4: Strings/Loops Due Apr 22 at midnight

Lab 4: Strings/Loops Due Apr 22 at midnight Lab 4: Strings/Loops Due Apr 22 at midnight For this lab, you must work with a partner. All functions should be commented appropriately. If there are random numbers, the function must still be commen ted

More information

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

CMSC 201 Fall 2016 Lab 09 Advanced Debugging CMSC 201 Fall 2016 Lab 09 Advanced Debugging Assignment: Lab 09 Advanced Debugging Due Date: During discussion Value: 10 points Part 1: Introduction to Errors Throughout this semester, we have been working

More information

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

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners Getting Started Excerpted from Hello World! Computer Programming for Kids and Other Beginners EARLY ACCESS EDITION Warren D. Sande and Carter Sande MEAP Release: May 2008 Softbound print: November 2008

More information

Exercise: Inventing Language

Exercise: Inventing Language Memory Computers get their powerful flexibility from the ability to store and retrieve data Data is stored in main memory, also known as Random Access Memory (RAM) Exercise: Inventing Language Get a separate

More information

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

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Spring 2011 Python Python was developed

More information

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

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s Intro to Python Python Getting increasingly more common Designed to have intuitive and lightweight syntax In this class, we will be using Python 3.x Python 2.x is still very popular, and the differences

More information

Stratford School Academy Schemes of Work

Stratford School Academy Schemes of Work Page 1 of 9 Number of weeks (between 6&8) Content of the unit Assumed prior learning (tested at the beginning of the unit) 6 This unit assumes that pupils already have some prior experience in Python or

More information

Program Planning, Data Comparisons, Strings

Program Planning, Data Comparisons, Strings Program Planning, Data Comparisons, Strings Program Planning Data Comparisons Strings Reading for this class: Dawson, Chapter 3 (p. 80 to end) and 4 Program Planning When you write your first programs,

More information

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

Selection statements. CSE 1310 Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington Selection s CSE 1310 Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1 Book reference Book: The practice of Computing Using Python 2-nd edition Second hand book

More information

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

Coding Workshop. Learning to Program with an Arduino. Lecture Notes. Programming Introduction Values Assignment Arithmetic. Coding Workshop Learning to Program with an Arduino Lecture Notes Table of Contents Programming ntroduction Values Assignment Arithmetic Control Tests f Blocks For Blocks Functions Arduino Main Functions

More information

CSCE 110 Programming I

CSCE 110 Programming I CSCE 110 Programming I Basics of Python (Part 1): Variables, Expressions, and Input/Output Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Spring 2013 Tiffani

More information

Notes on Chapter 1 Variables and String

Notes on Chapter 1 Variables and String Notes on Chapter 1 Variables and String Note 0: There are two things in Python; variables which can hold data and the data itself. The data itself consists of different kinds of data. These include numbers,

More information

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

3.4. FOR-LOOPS 65. for <v a r i a b l e > in < sequence >: 3.4. FOR-LOOPS 65 3.4 For-loops In the previous section we looked at while-loops, Python s basic looping structure. There is a second loop construct in Python called a for-loop. This is more specialized.

More information

Python Unit

Python Unit Python Unit 1 1.1 1.3 1.1: OPERATORS, EXPRESSIONS, AND VARIABLES 1.2: STRINGS, FUNCTIONS, CASE SENSITIVITY, ETC. 1.3: OUR FIRST TEXT- BASED GAME Python Section 1 Text Book for Python Module Invent Your

More information

1 Lecture 5: Advanced Data Structures

1 Lecture 5: Advanced Data Structures L5 June 14, 2017 1 Lecture 5: Advanced Data Structures CSCI 1360E: Foundations for Informatics and Analytics 1.1 Overview and Objectives We ve covered list, tuples, sets, and dictionaries. These are the

More information

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

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

LOOPS. Repetition using the while statement

LOOPS. Repetition using the while statement 1 LOOPS Loops are an extremely useful feature in any programming language. They allow you to direct the computer to execute certain statements more than once. In Python, there are two kinds of loops: while

More information

A453 Task 1: Analysis: Problem: Solution:

A453 Task 1: Analysis: Problem: Solution: : Analysis: Problem: The problem I need to solve is that I need to design, code, and test a program that simulates a dice throw of a 4, 6, or 12 sided die and outputs the result before repeating the process

More information

Outline: Search and Recursion (Ch13)

Outline: Search and Recursion (Ch13) Search and Recursion Michael Mandel Lecture 12 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture12final.ipynb

More information

EXCEL BASICS: MICROSOFT OFFICE 2010

EXCEL BASICS: MICROSOFT OFFICE 2010 EXCEL BASICS: MICROSOFT OFFICE 2010 GETTING STARTED PAGE 02 Prerequisites What You Will Learn USING MICROSOFT EXCEL PAGE 03 Opening Microsoft Excel Microsoft Excel Features Keyboard Review Pointer Shapes

More information

Introduction to String Manipulation

Introduction to String Manipulation Introduction to Computer Programming Introduction to String Manipulation CSCI-UA.0002 What is a String? A String is a data type in the Python programming language A String can be described as a "sequence

More information

(Python) Chapter 3: Repetition

(Python) Chapter 3: Repetition (Python) Chapter 3: Repetition 3.1 while loop Motivation Using our current set of tools, repeating a simple statement many times is tedious. The only item we can currently repeat easily is printing the

More information

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

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops PRG PROGRAMMING ESSENTIALS 1 Lecture 2 Program flow, Conditionals, Loops https://cw.fel.cvut.cz/wiki/courses/be5b33prg/start Michal Reinštein Czech Technical University in Prague, Faculty of Electrical

More information

Flow Control: Branches and loops

Flow Control: Branches and loops Flow Control: Branches and loops In this context flow control refers to controlling the flow of the execution of your program that is, which instructions will get carried out and in what order. In the

More information

Variables and Data Representation

Variables and Data Representation You will recall that a computer program is a set of instructions that tell a computer how to transform a given set of input into a specific output. Any program, procedural, event driven or object oriented

More information

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

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems. Plan for the rest of the semester: Programming We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems. We saw earlier that computers

More information

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

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail. OOP in Java 1 Outline 1. Getting started, primitive data types and control structures 2. Classes and objects 3. Extending classes 4. Using some standard packages 5. OOP revisited Parts 1 to 3 introduce

More information

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

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications Hello World! Computer Programming for Kids and Other Beginners by Warren Sande and Carter Sande Chapter 1 Copyright 2009 Manning Publications brief contents Preface xiii Acknowledgments xix About this

More information

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

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an  . Michigan State University CSE 231, Fall 2013 CSE 231, Rich Enbody Office Hours After class By appointment send an email 2 1 Project 1 Python arithmetic Do with pencil, paper and calculator first Idle Handin Help room 3 What is a Computer Program?

More information

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

2SKILL. Variables Lesson 6. Remembering numbers (and other stuff)... Remembering numbers (and other stuff)... Let s talk about one of the most important things in any programming language. It s called a variable. Don t let the name scare you. What it does is really simple.

More information

Types, lists & functions

Types, lists & functions Week 2 Types, lists & functions Data types If you want to write a program that allows the user to input something, you can use the command input: name = input (" What is your name? ") print (" Hello "+

More information

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

To become familiar with array manipulation, searching, and sorting. ELECTRICAL AND COMPUTER ENGINEERING 06-88-211: COMPUTER AIDED ANALYSIS LABORATORY EXPERIMENT #2: INTRODUCTION TO ARRAYS SID: OBJECTIVE: SECTIONS: Total Mark (out of 20): To become familiar with array manipulation,

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 12 Tuples All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted Modularity Meaning Benefits Program design Last Class We Covered Top

More information

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

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited

More information

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

Decisions, Decisions. Testing, testing C H A P T E R 7 C H A P T E R 7 In the first few chapters, we saw some of the basic building blocks of a program. We can now make a program with input, processing, and output. We can even make our input and output a little

More information

Fun facts about recursion

Fun facts about recursion Outline examples of recursion principles of recursion review: recursive linked list methods binary search more examples of recursion problem solving using recursion 1 Fun facts about recursion every loop

More information

CS Summer 2013

CS Summer 2013 CS 1110 - Summer 2013 intro to programming -- how to think like a robot :) we use the Python* language (www.python.org) programming environments (many choices): Eclipse (free from www.eclipse.org), or

More information

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

CS 115 Lecture 8. Selection: the if statement. Neil Moore CS 115 Lecture 8 Selection: the if statement Neil Moore Department of Computer Science University of Kentucky Lexington, Kentucky 40506 neil@cs.uky.edu 24 September 2015 Selection Sometime we want to execute

More information

Basics of Programming with Python

Basics of Programming with Python Basics of Programming with Python A gentle guide to writing simple programs Robert Montante 1 Topics Part 3 Obtaining Python Interactive use Variables Programs in files Data types Decision-making Functions

More information

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?

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? 1 Practice problems Here is a collection of some relatively straightforward problems that let you practice simple nuts and bolts of programming. Each problem is intended to be a separate program. 1. Write

More information

Control Structures 1 / 17

Control Structures 1 / 17 Control Structures 1 / 17 Structured Programming Any algorithm can be expressed by: Sequence - one statement after another Selection - conditional execution (not conditional jumping) Repetition - loops

More information

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

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples Abstract Data Types CS 234, Fall 2017 Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples Data Types Data is stored in a computer as a sequence of binary digits:

More information

EXCEL BASICS: MICROSOFT OFFICE 2007

EXCEL BASICS: MICROSOFT OFFICE 2007 EXCEL BASICS: MICROSOFT OFFICE 2007 GETTING STARTED PAGE 02 Prerequisites What You Will Learn USING MICROSOFT EXCEL PAGE 03 Opening Microsoft Excel Microsoft Excel Features Keyboard Review Pointer Shapes

More information

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

Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi. Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi Lecture 18 Tries Today we are going to be talking about another data

More information

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

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python CS95003 - Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / 2014 Subjects 1) Beginning with Python 2) Variables 3) Strings 4) Basic arithmetic operators 5) Flow control 6) Comparison

More information

Variables and numeric types

Variables and numeric types s s and numeric types Comp Sci 1570 to C++ types Outline s types 1 2 s 3 4 types 5 6 Outline s types 1 2 s 3 4 types 5 6 s types Most programs need to manipulate data: input values, output values, store

More information

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

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop Announcements Lab Friday, 1-2:30 and 3-4:30 in 26-152 Boot your laptop and start Forte, if you brought your laptop Create an empty file called Lecture4 and create an empty main() method in a class: 1.00

More information

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

CMSC 201 Spring 2017 Homework 4 Lists (and Loops and Strings) CMSC 201 Spring 2017 Homework 4 Lists (and Loops and Strings) Assignment: Homework 4 Lists (and Loops and Strings) Due Date: Friday, March 3rd, 2017 by 8:59:59 PM Value: 40 points Collaboration: For Homework

More information

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

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts Simple Data Types There are a number of data types that are considered primitive in that they contain only a single value. These data

More information

Variables, expressions and statements

Variables, expressions and statements Variables, expressions and statements 2.1. Values and data types A value is one of the fundamental things like a letter or a number that a program manipulates. The values we have seen so far are 2 (the

More information

Play with Python: An intro to Data Science

Play with Python: An intro to Data Science Play with Python: An intro to Data Science Ignacio Larrú Instituto de Empresa Who am I? Passionate about Technology From Iphone apps to algorithmic programming I love innovative technology Former Entrepreneur:

More information

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

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite

More information

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

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration STATS 507 Data Analysis in Python Lecture 2: Functions, Conditionals, Recursion and Iteration Functions in Python We ve already seen examples of functions: e.g., type()and print() Function calls take the

More information

Introduction to Python Code Quality

Introduction to Python Code Quality Introduction to Python Code Quality Clarity and readability are important (easter egg: type import this at the Python prompt), as well as extensibility, meaning code that can be easily enhanced and extended.

More information

Python 1: Intro! Max Dougherty Andrew Schmitt

Python 1: Intro! Max Dougherty Andrew Schmitt Python 1: Intro! Max Dougherty Andrew Schmitt Computational Thinking Two factors of programming: The conceptual solution to a problem. Solution syntax in a programming language BJC tries to isolate and

More information

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

Chapter 1. Data types. Data types. In this chapter you will: learn about data types. learn about tuples, lists and dictionaries Chapter 1 Data types In this chapter you will: learn about data types learn about tuples, lists and dictionaries make a magic card trick app. Data types In Python Basics you were introduced to strings

More information

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

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control Chapter 2 Control, Quick Overview Control Selection Selection Selection is how programs make choices, and it is the process of making choices that provides a lot of the power of computing 1 Python if statement

More information

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

printf( Please enter another number: ); scanf( %d, &num2); CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful

More information

Python for Non-programmers

Python for Non-programmers Python for Non-programmers A Gentle Introduction 1 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013

More information

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

CMPT 120 Control Structures in Python. Summer 2012 Instructor: Hassan Khosravi CMPT 120 Control Structures in Python Summer 2012 Instructor: Hassan Khosravi The If statement The most common way to make decisions in Python is by using the if statement. The if statement allows you

More information

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

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Hello, in this lecture we will learn about some fundamentals concepts of java.

More information

Collections. Lists, Tuples, Sets, Dictionaries

Collections. Lists, Tuples, Sets, Dictionaries Collections Lists, Tuples, Sets, Dictionaries Homework notes Homework 1 grades on canvas People mostly lost points for not reading the document carefully Didn t play again Didn t use Y/N for playing again

More information

Introduction to Programming

Introduction to Programming Introduction to Programming Workshop 10 11 April 2017 Peter Smyth UK Data Service Accessing the course materials The code snippets used, the file needed for the final exercise, the additional exercises

More information

Introduction to Programming with JES

Introduction to Programming with JES Introduction to Programming with JES Titus Winters & Josef Spjut October 6, 2005 1 Introduction First off, welcome to UCR, and congratulations on becoming a Computer Engineering major. Excellent choice.

More information

Search Lesson Outline

Search Lesson Outline 1. Searching Lesson Outline 2. How to Find a Value in an Array? 3. Linear Search 4. Linear Search Code 5. Linear Search Example #1 6. Linear Search Example #2 7. Linear Search Example #3 8. Linear Search

More information

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

Introduction to Computation for the Humanities and Social Sciences. CS 3 Chris Tanner Introduction to Computation for the Humanities and Social Sciences CS 3 Chris Tanner Lecture 4 Python: Variables, Operators, and Casting Lecture 4 [People] need to learn code, man I m sick with the Python.

More information

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

Zipf's Law. This preliminary discussion gives us our first ideas about what the program we're writing needs to do. Zipf's Law In this unit, we'll be verifying the pattern of word frequencies known as Zipf's Law. Zipf's idea was pretty simple. Imagine taking a natural language corpus and making a list of all the words

More information

[ the academy_of_code] Senior Beginners

[ the academy_of_code] Senior Beginners [ the academy_of_code] Senior Beginners 1 Drawing Circles First step open Processing Open Processing by clicking on the Processing icon (that s the white P on the blue background your teacher will tell

More information

MITOCW watch?v=0jljzrnhwoi

MITOCW watch?v=0jljzrnhwoi MITOCW watch?v=0jljzrnhwoi The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free. To

More information

Beyond Blocks: Python Session #1

Beyond Blocks: Python Session #1 Beyond Blocks: Session #1 CS10 Spring 2013 Thursday, April 30, 2013 Michael Ball Beyond Blocks : : Session #1 by Michael Ball adapted from Glenn Sugden is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike

More information

MITOCW watch?v=se4p7ivcune

MITOCW watch?v=se4p7ivcune MITOCW watch?v=se4p7ivcune The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free. To

More information

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

Here n is a variable name. The value of that variable is 176. UNIT II DATA, EXPRESSIONS, STATEMENTS 9 Python interpreter and interactive mode; values and types: int, float, boolean, string, and list; variables, expressions, statements, tuple assignment, precedence

More information

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

Iteration. # a and b are now equal # a and b are no longer equal Multiple assignment Iteration 6.1. Multiple assignment As you may have discovered, it is legal to make more than one assignment to the same variable. A new assignment makes an existing variable refer to a new value (and stop

More information

Downloaded from Chapter 2. Functions

Downloaded from   Chapter 2. Functions Chapter 2 Functions After studying this lesson, students will be able to: Understand and apply the concept of module programming Write functions Identify and invoke appropriate predefined functions Create

More information

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

CMPT 120 Basics of Python. Summer 2012 Instructor: Hassan Khosravi CMPT 120 Basics of Python Summer 2012 Instructor: Hassan Khosravi Python A simple programming language to implement your ideas Design philosophy emphasizes code readability Implementation of Python was

More information