An Introduction to Python for KS4!

Size: px
Start display at page:

Download "An Introduction to Python for KS4!"

Transcription

1 An Introduction to Python for KS4 Python is a modern, typed language - quick to create programs and easily scalable from small, simple programs to those as complex as GoogleApps. IDLE is the editor that comes free with Python. There are other text editors that will work, including Textastic for the ipad. When you start Python on the Mac you get the following window: Notice the warning about TkInter. The above installation had the latest version of tcltk running. This can occur on some installs on Macs and can have issues with some graphical applications but, for applications up to GCSE level, it is not an issue. The next step to writing your python code is to launch the editor window. Click File>New File and a blank window will open. Print() and Input() Commands Type the following, using the print() command: print ( Hello Cornwall ) Now File>Save and call it Hello.py, saving to desktop. Next, click Run>Run Module and the following should happen. Note that the program runs in the shell window.

2 Now. Looking at the code we typed: print ( Hello Cornwall ) print Hello Cornwall In Python 2, this would have been written as: In both, you can see that outputted text must be enclosed within quotes. Note that smart quotes fail and so copying and pasting code from a word processor can cause errors. This is really common with students so one to watch out for. Taking the code to the next step, we want to ask the user for their name and then print out a welcome. Edit the code in the editor window to read: name = null name = input ( What is your name? ) print ( Hello,name,. Welcome to Cornwall ) Save the code as HelloName.py and run. You should see the following: Here we have introduced a text variable, name to store the input. Although it is not strictly necessary to declare it at the start, it is a good habit for the students to get into. \n - introduce a line break \t - insert a tab \\ - insert a backslash \ - insert a speech mark There are special characters that we can enter into text to improve flow and presentation.

3 It is possible to use single speech marks, and so avoid having to \ speech marks. This can be confusing for students, so I wouldn t recommend its introduction early on. print( Hello, he said. ) could be used to replace print( \ Hello\, he said. )

4 Maths Functions Python can be used like a calculator. This is a good opportunity to introduce integer and floating point variables at the same time. * Multiply If we add an extra line at the start of the program, we can also add more functions, such as trigonometry. import math This brings in a new module. Modules are extra Python commands that can be added and a lot are installed along with the standard Python files. Some useful ones are: math.e Inserts e These extra functions are extremely useful in the GCSE Controlled Assessments. Variables + Add % Modulus - Subtract ** Raise to the power / Divide // Divide (Integer Part) math.sin() Sine of an angle math.floor() Integer part of a decimal math.cos() Cosine of an angle math.sqrt() Square Root math.tan() Tangent of an angle math.pi Inserts Pi To use these functions, we need to be able to define variables. name = null Text String correct = set([ y, yes ]) Sets score = 1 Integer correct = ( y, yes ) Tuple (read-only list) g = Floating Point letters = [ a, b, c ] List Sets, Tuples and Lists have an Index, starting with 0, that can refer to elements in the values. For example: mylist = [ a, b, c ] print (mylist[1]) would print out b, as this is at the second position with index value of 1. A dice randomiser could be of the form: import random throws = ( 1, 2, 3, 4, 5, 6 ) choice = random.randint(1,6) print(throws[choice])

5 So a simple program involving other variable types might have a form: x = 0 y = 0 m = 0 c = 0 print( For a linear equation of y=mx+c, please enter m and c ) m = int(input( m: )) c = int(input( c: )) print( Now enter the value of x that you want to process ) x = int(input( x: )) y=(m*x)+c print( Y =,y) Note the introduction of the int() conversion. input() always returns a string. We want an integer here. Students often forget the second closing ) so one to watch out for. Try the above code for yourself. The nice thing is that this introduces variables, input, process and output. Now. The above is a little inefficient. It would be nice to calculate a range of y values for a series of x. We can modify the above code like this: x = 0 y = 0 m = 0 c = 0 print( For a linear equation of y=mx+c ) print( please enter m and c ) m = int(input( m: )) c = int(input( c: )) x = -5 while x < 6: y=(m*x)+c print( X:,x,,Y:,y) x+=1 print( Finished ) I have included the code from IDLE to show the handy way that it uses colour to show correct syntax. Note the tabbing for the while loop. This also introduces a condition x < 6 and a simple incremental addition to a variable x+=1. When we used BASIC, we might have written x=x+1 to add one to a counter. A final variable type is the Dictionary. These are another type of list but, this time, you supply the index value. For example: elements = {1: Hydrogen, 2: Helium, 3: Lithium, 4: Beryllium } The index value is called the Key and the item in quotes is called the Value.

6 Operators > Greater Than < Less Than >= Greater Than or Equal <= Less Than or Equal = Not Equal == Exactly Equal Note how we use a single equal sign to assign a value but a double equal sign to check equivalence. For example: a=1 b=1 while a == b: print ( Equal )

7 Comments If we use a # tag at the start of a line, the line is not compiled and so is a comment. We use these to annotate a program #define variables a=1 # Start a Loop while a = 0: print(a)

8 Modules As said earlier, modules bring extra commands. import math This module gives us extended mathematical functions import random math.sin() Sine of an angle math.floor() Integer part of a decimal math.cos() Cosine of an angle math.sqrt() Square Root math.tan() Tangent of an angle math.pi Inserts Pi math.e This module gives us a range of random items to use in other calculations random.randint(a,b) Inserts e Random integer between a and b random.choice(list) random.randrange(start, stop, step) Random string from a list Random number within a range random.random() Random decimal number between 0.0 and 1.0

9 Selection When we ask a user for an input, it is often useful to define the action, based on their response. For this we use IF statements in programming. In Python we have IF, ELIF and ELSE. For example answer1 = null answer1 = input ( What is your choice? y/n ) if answer1 == y : print( Yes ) else: print( No ) or goodchoices = set([ y, yes ]) answer1 = input ( What is your choice? y/n ) if answer1 in goodchoices: print( Good Choice ) else: print( Bad Choice ) words = ['cat', 'dog', mouse'] for w in words: print ( Word: w,,length:,len(w)) We can also use lists with another selection tool - FOR. Look at this example: This loop would cycle through the list, printing the length of the words in the list, using the len() command. The result would be: Word: cat, Length: 3 Word: dog, Length: 3 Word: mouse, Length: 5

10 Functions We can make programs more efficient by collecting parts of a program together and turning it into a function. Lets look at this program again: x = 0 y = 0 m = 0 c = 0 print( For a linear equation of y=mx+c ) print( please enter m and c ) m = int(input( m: )) c = int(input( c: )) x = -5 while x < 6: y=(m*x)+c print( X:,x,,Y:,y) x+=1 print( Finished ) x =0 y = [] m = 0 c = 0 counter = 0 #The Function def linear(m,c): counter = 0 x = -5 while counter < 11: y=(m*x)+c print( X:,x,,Y:,y) x+=1 counter+=1 #End of the function print( For a linear equation of y=mx+c ) print( please enter m and c ) m = int(input( m: )) c = int(input( c: )) linear(m,c) print( Finished ) Lets look at this program again. The def command defines the function here. The function is passed the two values of m and c using the function name - note that you cannot use the name of any built in command as a function name.

11 Menus A simple menu for a choice could use the techniques that we have seen up until now: level = input( Please enter your choice - a, b or c: ) while level = a and level = b and level = c : level = input( Sorry, your choice must be - a, b or c: ) This gives us some sort of validation checking on a menu option. Next we will see some further code examples, all of which have examples useful for GCSE coursework tasks.

12 Extra lists - adding and removing list elements mylist = ['Bob','Sue','Rita'] index = 0 myextra = 'Null' size = len(mylist) for index in range(0,size): print (index+1,':',mylist[index]) print ("Add names to the list") print ("Type Stop to stop") while myextra = 'Stop': myextra = input("add a name> ") mylist.append(myextra) mylist.remove('stop') index = 0 print ("Your new list of names is") size = len(mylist) for index in range(0,size): print (index+1,':',mylist[index]) import random Making random names. Useful for game characters. FirstNames = ['Bob','Sue','Rita','Sam','George','Degory','Thomasina'] LastNames = ['Smith','Jones','Roberts','Willa','Curnow','Mitchell'] WholeName = "" rounds = int(input("how many names would you like? ")) while rounds > 0: WholeName = random.choice (FirstNames) + " " + random.choice (LastNames) print (WholeName) rounds -= 1 print ( End") Countdown loop with Play Again choice launchagain = True counter = 10 validchoice = set(['y','y','yes','yes']) while launchagain == True: counter = 10 print ("Countdown>",counter) while counter >1: counter -= 1 print ("Countdown>",counter) print ("Launch") launchchoice = input("would you like to launch another rocket? (y/n)") launchagain = launchchoice in validchoice print ("Thanks for launching rockets. )

13 Random Captain Generator for Sports This code combines all of the elements that we have seen and is a useful demonstration for GCSE Coursework tasks. It also shows effective use of commenting. # Import any functions we need import random # Initialise our variables # Set the captain player number to 0 captain = 0 # Set the number of players to 0 players = 0 # Set the While loop value to True playagain = True # Define any functions we need # The function is called 'captainizer'. This is fed the number of players (players) when called def captainizer (players): # Create a random integer between 1 and the number of players. captain = random.randint(1,players) # Return the number of the captain using the variable name 'captain' return captain # Print a welcome message to the users print (""" Welcome Which sport would you like? 1 Football 2 Rugby 3 Double's Tennis """) # Begin the body of the programme. The While statement continues until False while playagain: # We are going to give users a choice of sports. This is in case people do not know how many should be on a team # This can be expanded easily with more sports. # Ask the user which sport they would like sportchoice = input ("Choose your sport, 1,2 or 3") # Sport Choice Sections # Check for sport and initialise variable with number of players, call the captainizer function and output the value to the screen # Whilst this code could be simplified, this method makes adding new sports very quick. # Choice 1 if sportchoice == "1": players = 11 captain = captainizer (players) print ("Out of ",players,", your Captain is player number ",captain) #Choice 2 elif sportchoice == "2": players = 15

14 captain = captainizer (players) print ("Out of ",players,", your Captain is player number ",captain) #Choice 3 elif sportchoice == "3": players = 2 captain = captainizer (players) print ("Out of ",players,", your Captain is player number ",captain) #Trap if no valid choice is made. else: print ("You didn't choose a valid sport") # Output the results to a file try: #Open a file with name "captain.txt" and place in append mode captainfile = open("captain.txt", "a") try: # Text String captainfile.write("your Captain is player number ") # Note that you cannot output numbers without turning them into a text string captainfile.write(str(captain)) #T ext String captainfile.write(" out of ") # Note that you cannot output numbers without turning them into a text string captainfile.write(str(players)) # Text String captainfile.write(" players") # Text String captainfile.write("\n") finally: # Close the file captainfile.close() except IOError: pass # Now we test for whether the user wants another go # Set the while look value to True, just to be sure. playagain = True # Ask the user if they want to play again playagain = input("do you want to choose another captain? (y/n)") # never assume they will do as they are told. Strip out all capitals and allow y and yes to be valid answers to play again playagain = playagain.strip().lower() in ('y','yes') # Now we say goodbye print ("Thank you for playing") quit

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

Expressions and Variables

Expressions and Variables Expressions and Variables Expressions print(expression) An expression is evaluated to give a value. For example: 2 + 9-6 Evaluates to: 5 Data Types Integers 1, 2, 3, 42, 100, -5 Floating points 2.5, 7.0,

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

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

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

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

CS 102 Lab 3 Fall 2012

CS 102 Lab 3 Fall 2012 Name: The symbol marks programming exercises. Upon completion, always capture a screenshot and include it in your lab report. Email lab report to instructor at the end of the lab. Review of built-in functions

More information

Table of Contents EVALUATION COPY

Table of Contents EVALUATION COPY Table of Contents Introduction... 1-2 A Brief History of Python... 1-3 Python Versions... 1-4 Installing Python... 1-5 Environment Variables... 1-6 Executing Python from the Command Line... 1-7 IDLE...

More information

Try typing the following in the Python shell and press return after each calculation. Write the answer the program displays next to the sums below.

Try typing the following in the Python shell and press return after each calculation. Write the answer the program displays next to the sums below. Name: Date: Instructions: PYTHON - INTRODUCTORY TASKS Open Idle (the program we will be using to write our Python codes). We can use the following code in Python to work out numeracy calculations. Try

More information

VBScript: Math Functions

VBScript: Math Functions C h a p t e r 3 VBScript: Math Functions In this chapter, you will learn how to use the following VBScript functions to World Class standards: 1. Writing Math Equations in VBScripts 2. Beginning a New

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

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

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Python review. 1 Python basics. References. CS 234 Naomi Nishimura Python review CS 234 Naomi Nishimura The sections below indicate Python material, the degree to which it will be used in the course, and various resources you can use to review the material. You are not

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

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

What did we talk about last time? Examples switch statements

What did we talk about last time? Examples switch statements Week 4 - Friday What did we talk about last time? Examples switch statements History of computers Hardware Software development Basic Java syntax Output with System.out.print() Mechanical Calculation

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

CS 1110, LAB 2: FUNCTIONS AND ASSIGNMENTS

CS 1110, LAB 2: FUNCTIONS AND ASSIGNMENTS CS 1110, LAB 2: FUNCTIONS AND ASSIGNMENTS http://www.cs.cornell.edu/courses/cs1110/2017fa/labs/lab2/ First Name: Last Name: NetID: The purpose of this lab is to get you comfortable with using assignment

More information

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON 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.

More information

roboturtle Documentation

roboturtle Documentation roboturtle Documentation Release 0.1 Nicholas A. Del Grosso November 28, 2016 Contents 1 Micro-Workshop 1: Introduction to Python with Turtle Graphics 3 1.1 Workshop Description..........................................

More information

Java for Python Programmers. Comparison of Python and Java Constructs Reading: L&C, App B

Java for Python Programmers. Comparison of Python and Java Constructs Reading: L&C, App B Java for Python Programmers Comparison of Python and Java Constructs Reading: L&C, App B 1 General Formatting Shebang #!/usr/bin/env python Comments # comments for human readers - not code statement #

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

Python Programming Exercises 1

Python Programming Exercises 1 Python Programming Exercises 1 Notes: throughout these exercises >>> preceeds code that should be typed directly into the Python interpreter. To get the most out of these exercises, don t just follow them

More information

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python CONDITION CONTROLLED LOOPS Introduction to Programming - Python Generating Random Numbers Generating a random integer Sometimes you need your program to generate information that isn t available when you

More information

Chapter 3 : Computer Science. Class XI ( As per CBSE Board) Data Handling. Visit : python.mykvs.in for regular updates

Chapter 3 : Computer Science. Class XI ( As per CBSE Board) Data Handling. Visit : python.mykvs.in for regular updates Chapter 3 : Computer Science Class XI ( As per CBSE Board) Data Handling Introduction Most of the computer programming language support data type, variables,operator and expression like fundamentals.python

More information

Variable Manipulator Driver. Installation and Usage Guide. Revision: 1.0 Date: Monday, July 10, 2017 Authors: Alan Chow

Variable Manipulator Driver. Installation and Usage Guide. Revision: 1.0 Date: Monday, July 10, 2017 Authors: Alan Chow Variable Manipulator Driver Installation and Usage Guide Revision: 1.0 Date: Monday, July 10, 2017 Authors: Alan Chow Contents Overview... 3 Usage Scenarios... 3 Features... 3 Change Log... 4 Driver Installation...

More information

Jython. secondary. memory

Jython. secondary. memory 2 Jython secondary memory Jython processor Jython (main) memory 3 Jython secondary memory Jython processor foo: if Jython a

More information

Introduction to Python

Introduction to Python Introduction to Python Efstratios RAPPOS efstratios.rappos@heig-vd.ch Slide 1 2016 HEIG-VD SNU Summer School Background Easy and popular programming language Interpreted: must have python installed to

More information

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information

CSC Software I: Utilities and Internals. Programming in Python

CSC Software I: Utilities and Internals. Programming in Python CSC 271 - Software I: Utilities and Internals Lecture #8 An Introduction to Python Programming in Python Python is a general purpose interpreted language. There are two main versions of Python; Python

More information

egrapher Language Reference Manual

egrapher Language Reference Manual egrapher Language Reference Manual Long Long: ll3078@columbia.edu Xinli Jia: xj2191@columbia.edu Jiefu Ying: jy2799@columbia.edu Linnan Wang: lw2645@columbia.edu Darren Chen: dsc2155@columbia.edu 1. Introduction

More information

Variables, Functions and String Formatting

Variables, Functions and String Formatting Variables, Functions and String Formatting Code Examples HW 2-1, 2-2 Logical Expressions Comparison Operators a == b Comparison operators compare the right-hand side and the lefthand side and return True

More information

Python Games. Session 1 By Declan Fox

Python Games. Session 1 By Declan Fox Python Games Session 1 By Declan Fox Rules General Information Wi-Fi Name: CoderDojo Password: coderdojowireless Website: http://cdathenry.wordpress.com/ Plans for this year Command line interface at first

More information

Programming Training. Main Points: - Python Statements - Problems with selections.

Programming Training. Main Points: - Python Statements - Problems with selections. Programming Training Main Points: - Python Statements - Problems with selections. print() print(value1, value2, ) print( var =, var1) # prints the text var= followed by the value of var print( Here is

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

Python Input, output and variables

Python Input, output and variables Today s lecture Python Input, output and variables Lecture 22 COMPSCI111/111G SS 2016! What is Python?! Displaying text on screen using print()! Variables! Numbers and basic arithmetic! Getting input from

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

Let's Look Back. We talked about how to create a form in HTML. Forms are one way to interact with users

Let's Look Back. We talked about how to create a form in HTML. Forms are one way to interact with users Introduction to PHP Let's Look Back We talked about how to create a form in HTML Forms are one way to interact with users Users can enter information into forms which can be used by you (programmer) We

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

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators 1 Professor: Sana Odeh odeh@courant.nyu.edu Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators Review What s wrong with this line of code? print( He said Hello ) What s wrong with

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

Lesson 3: Basic Programming Concepts

Lesson 3: Basic Programming Concepts 3 ICT Gaming Essentials Lesson 3: Basic Programming Concepts LESSON SKILLS After completing this lesson, you will be able to: Explain the types and uses of variables and operators in game programming.

More information

Python Input, output and variables. Lecture 22 COMPSCI111/111G SS 2016

Python Input, output and variables. Lecture 22 COMPSCI111/111G SS 2016 Python Input, output and variables Lecture 22 COMPSCI111/111G SS 2016 Today s lecture u What is Python? u Displaying text on screen using print() u Variables u Numbers and basic arithmetic u Getting input

More information

How To Think Like A Computer Scientist, chapter 3; chapter 6, sections

How To Think Like A Computer Scientist, chapter 3; chapter 6, sections 6.189 Day 3 Today there are no written exercises. Turn in your code tomorrow, stapled together, with your name and the file name in comments at the top as detailed in the Day 1 exercises. Readings How

More information

Math Day 2 Programming: How to make computers do math for you

Math Day 2 Programming: How to make computers do math for you Math Day 2 Programming: How to make computers do math for you Matt Coles February 10, 2015 1 Intro to Python (15min) Python is an example of a programming language. There are many programming languages.

More information

ASCII Art. Introduction: Python

ASCII Art. Introduction: Python Python 1 ASCII Art All Code Clubs must be registered. Registered clubs appear on the map at codeclub.org.uk - if your club is not on the map then visit jumpto.cc/18cplpy to find out what to do. Introduction:

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

ENGR 102 Engineering Lab I - Computation

ENGR 102 Engineering Lab I - Computation ENGR 102 Engineering Lab I - Computation Learning Objectives by Week 1 ENGR 102 Engineering Lab I Computation 2 Credits 2. Introduction to the design and development of computer applications for engineers;

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

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types Introduction to Computer Programming in Python Dr William C Bulko Data Types 2017 What is a data type? A data type is the kind of value represented by a constant or stored by a variable So far, you have

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

C Functions. 5.2 Program Modules in C

C Functions. 5.2 Program Modules in C 1 5 C Functions 5.2 Program Modules in C 2 Functions Modules in C Programs combine user-defined functions with library functions - C standard library has a wide variety of functions Function calls Invoking

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

ECS Baruch Lab 5 Spring 2019 Name NetID (login, like , not your SUID)

ECS Baruch Lab 5 Spring 2019 Name NetID (login, like  , not your SUID) ECS 102 - Baruch Lab 5 Spring 2019 Name NetID (login, like email, not your SUID) Today you will be doing some more experiments in the shell. Create a file Lab5.txt. In this file you will be asked to save

More information

And Parallelism. Parallelism in Prolog. OR Parallelism

And Parallelism. Parallelism in Prolog. OR Parallelism Parallelism in Prolog And Parallelism One reason that Prolog is of interest to computer scientists is that its search mechanism lends itself to parallel evaluation. In fact, it supports two different kinds

More information

Programming to Python

Programming to Python Programming to Python Sept., 5 th Slides by M. Stepp, M. Goldstein, M. DiRamio, and S. Shah Compiling and interpreting Many languages require you to compile (translate) your program into a form that the

More information

Using Classes. GEEN163 Introduction to Computer Programming

Using Classes. GEEN163 Introduction to Computer Programming Using Classes GEEN163 Introduction to Computer Programming Unless in communicating with it one says exactly what one means, trouble is bound to result. Alan Turing talking about computers Homework The

More information

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs. Lesson 2 VARIABLES Aim Understanding how computer programs store values, and how they are accessed and used in computer programs. WHAT ARE VARIABLES? When you input data (i.e. information) into a computer

More information

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15 1 LECTURE 1: INTRO Introduction to Scientific Python, CME 193 Jan. 9, 2014 web.stanford.edu/~ermartin/teaching/cme193-winter15 Eileen Martin Some slides are from Sven Schmit s Fall 14 slides 2 Course Details

More information

Princess Nourah bint Abdulrahman University. Computer Sciences Department

Princess Nourah bint Abdulrahman University. Computer Sciences Department Princess Nourah bint Abdulrahman University 1 And use http://www.w3schools.com/ JavaScript Objectives Introduction to JavaScript Objects Data Variables Operators Types Functions Events 4 Why Study JavaScript?

More information

Chapter 2 Input, Processing and Output. Hong Sun COSC 1436 Spring 2017 Jan 30, 2017

Chapter 2 Input, Processing and Output. Hong Sun COSC 1436 Spring 2017 Jan 30, 2017 Chapter 2 Input, Processing and Output Hong Sun COSC 1436 Spring 2017 Jan 30, 2017 Designing a Program Designing a Program o Programs must be carefully designed before they are written. Before beginning

More information

CHAPTER 3: CORE PROGRAMMING ELEMENTS

CHAPTER 3: CORE PROGRAMMING ELEMENTS Variables CHAPTER 3: CORE PROGRAMMING ELEMENTS Introduction to Computer Science Using Ruby A variable is a single datum or an accumulation of data attached to a name The datum is (or data are) stored in

More information

Introduction to Python

Introduction to Python Introduction to Python خانه ریاضیات اصفهان فرزانه کاظمی زمستان 93 1 Why Python? Python is free. Python easy to lean and use. Reduce time and length of coding. Huge standard library Simple (Python code

More information

Introduction to C Language

Introduction to C Language Introduction to C Language Instructor: Professor I. Charles Ume ME 6405 Introduction to Mechatronics Fall 2006 Instructor: Professor Charles Ume Introduction to C Language History of C Language In 1972,

More information

Detailed guide for learning to program in Python 3

Detailed guide for learning to program in Python 3 Detailed guide for learning to program in Python 3 This is a general guide to assist in learning Python 3. Not all the components here are necessary for teaching or learning programming for Edexcel GCSE

More information

BB4W. KS3 Programming Workbook INTRODUCTION TO. BBC BASIC for Windows. Name: Class:

BB4W. KS3 Programming Workbook INTRODUCTION TO. BBC BASIC for Windows. Name: Class: KS3 Programming Workbook INTRODUCTION TO BB4W BBC BASIC for Windows Name: Class: Resource created by Lin White www.coinlea.co.uk This resource may be photocopied for educational purposes Introducing BBC

More information

Introduction to Python, Cplex and Gurobi

Introduction to Python, Cplex and Gurobi Introduction to Python, Cplex and Gurobi Introduction Python is a widely used, high level programming language designed by Guido van Rossum and released on 1991. Two stable releases: Python 2.7 Python

More information

Revision of Basics of Python

Revision of Basics of Python Chapter 1 : Computer Science Class XII ( As per CBSE Board) Revision of Basics of Python Introduction It is widely used general purpose,high level programming language.developed by Guido van Rossum in

More information

! Widely available. ! Widely used. ! Variety of automatic checks for mistakes in programs. ! Embraces full set of modern abstractions. Caveat.

! Widely available. ! Widely used. ! Variety of automatic checks for mistakes in programs. ! Embraces full set of modern abstractions. Caveat. Why Java? Lecture 2: Intro to Java Java features.! Widely available.! Widely used.! Variety of automatic checks for mistakes in programs.! Embraces full set of modern abstractions. Caveat.! No perfect

More information

Ch.2: Loops and lists

Ch.2: Loops and lists Ch.2: Loops and lists Joakim Sundnes 1,2 Hans Petter Langtangen 1,2 Simula Research Laboratory 1 University of Oslo, Dept. of Informatics 2 Aug 29, 2018 Plan for 28 August Short quiz on topics from last

More information

BASIC ELEMENTS OF A COMPUTER PROGRAM

BASIC ELEMENTS OF A COMPUTER PROGRAM BASIC ELEMENTS OF A COMPUTER PROGRAM CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING LOGO Contents 1 Identifier 2 3 Rules for naming and declaring data variables Basic data types 4 Arithmetic operators

More information

Intro to Python & Programming. C-START Python PD Workshop

Intro to Python & Programming. C-START Python PD Workshop Don t just buy a new video game, make one. Don t just download the latest app, help design it. Don t just play on your phone, program it. No one is born a computer scientist, but with a little hard work

More information

CSC Web Programming. Introduction to JavaScript

CSC Web Programming. Introduction to JavaScript CSC 242 - Web Programming Introduction to JavaScript JavaScript JavaScript is a client-side scripting language the code is executed by the web browser JavaScript is an embedded language it relies on its

More information

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial CSI31 Lecture 5 Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial 1 3.1 Numberic Data Types When computers were first developed, they were seen primarily as

More information

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS 1439-1440 1 Outline 1. Introduction 2. Why Python? 3. Compiler and Interpreter 4. The first program 5. Comments and Docstrings 6. Python Indentations

More information

Built-in Types of Data

Built-in Types of Data Built-in Types of Data Types A data type is set of values and a set of operations defined on those values Python supports several built-in data types: int (for integers), float (for floating-point numbers),

More information

Preview from Notesale.co.uk Page 3 of 79

Preview from Notesale.co.uk Page 3 of 79 ABOUT THE TUTORIAL Computer Prgramming Tutorial Computer programming is the act of writing computer programs, which are a sequence of instructions written using a Computer Programming Language to perform

More information

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University Lesson #3 Variables, Operators, and Expressions Variables We already know the three main types of variables in C: int, char, and double. There is also the float type which is similar to double with only

More information

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems CSSE 120 Introduction to Software Development Exam 1 Format, Concepts, What you should be able to do, and Sample Problems Page 1 of 6 Format: The exam will have two sections: Part 1: Paper-and-Pencil o

More information

The Very Basics of the R Interpreter

The Very Basics of the R Interpreter Chapter 2 The Very Basics of the R Interpreter OK, the computer is fired up. We have R installed. It is time to get started. 1. Start R by double-clicking on the R desktop icon. 2. Alternatively, open

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

The float type and more on variables FEB 6 TH 2012

The float type and more on variables FEB 6 TH 2012 The float type and more on variables FEB 6 TH 2012 The float type Numbers with decimal points are easily represented in binary: 0.56 (in decimal) = 5/10 + 6/100 0.1011 (in binary) = ½+0/4 + 1/8 +1/16 The

More information

Expressions. Eric McCreath

Expressions. Eric McCreath Expressions Eric McCreath 2 Expressions on integers There is the standard set of interger operators in c. We have: y = 4 + 7; // add y = 7-3; // subtract y = 3 * x; // multiply y = x / 3; // integer divide

More information

PIC 10A. Lecture 3: More About Variables, Arithmetic, Casting, Assignment

PIC 10A. Lecture 3: More About Variables, Arithmetic, Casting, Assignment PIC 10A Lecture 3: More About Variables, Arithmetic, Casting, Assignment Assigning values to variables Our variables last time did not seem very variable. They always had the same value! Variables stores

More information

Long (or LONGMATH ) floating-point (or integer) variables (length up to 1 million, limited by machine memory, range: approx. ±10 1,000,000.

Long (or LONGMATH ) floating-point (or integer) variables (length up to 1 million, limited by machine memory, range: approx. ±10 1,000,000. QuickCalc User Guide. Number Representation, Assignment, and Conversion Variables Constants Usage Double (or DOUBLE ) floating-point variables (approx. 16 significant digits, range: approx. ±10 308 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

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I BASIC COMPUTATION x public static void main(string [] args) Fundamentals of Computer Science I Outline Using Eclipse Data Types Variables Primitive and Class Data Types Expressions Declaration Assignment

More information

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi Shell / Python Tutorial CS279 Autumn 2017 Rishi Bedi Shell (== console, == terminal, == command prompt) You might also hear it called bash, which is the most widely used shell program macos Windows 10+

More information

A variable is a name for a location in memory A variable must be declared

A variable is a name for a location in memory A variable must be declared Variables A variable is a name for a location in memory A variable must be declared, specifying the variable's name and the type of information that will be held in it data type variable name int total;

More information

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu) I. INTERACTIVE MODE VERSUS SCRIPT MODE There are two ways to use the python interpreter: interactive mode and script mode. 1. Interactive Mode (a) open a terminal shell (terminal emulator in Applications

More information

Course Outline. Introduction to java

Course Outline. Introduction to java Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.

More information

KS5-HE Transition Guide Checkpoint Task Instructions and answers for teachers

KS5-HE Transition Guide Checkpoint Task Instructions and answers for teachers KS5-HE Transition Guide Checkpoint Task Instructions and answers for teachers These instructions should accompany the OCR resource Types of programming language KS5-HE Transition guide which supports OCR

More information

Programming Basics. Part 1, episode 1, chapter 1, passage 1

Programming Basics. Part 1, episode 1, chapter 1, passage 1 Programming Basics Part 1, episode 1, chapter 1, passage 1 Agenda 1. What is it like to program? 2. Our first code 3. Integers 4. Floats 5. Conditionals 6. Booleans 7. Strings 8. Built-in functions What

More information

Python 2. KS3 Programming Workbook. Name. ICT Teacher Form. Taking you Parseltongue further. Created by D.Aldred P a g e 1

Python 2. KS3 Programming Workbook. Name. ICT Teacher Form. Taking you Parseltongue further. Created by D.Aldred P a g e 1 Python 2 KS3 Programming Workbook Taking you Parseltongue further Name ICT Teacher Form Created by D.Aldred P a g e 1 To Execute the program code press F5 Welcome to Python The python software has two

More information

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG 1 Notice Assignments Reading Assignment: Chapter 3: Introduction to Parameters and Objects The Class 10 Exercise

More information

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing SECTION 1: INTRODUCTION ENGR 112 Introduction to Engineering Computing 2 Course Overview What is Programming? 3 Programming The implementation of algorithms in a particular computer programming language

More information

The Big Python Guide

The Big Python Guide 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

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

Computer Programming : C++

Computer Programming : C++ The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming : C++ Experiment #1 Basics Contents Structure of a program

More information

Lecture 4. Defining Functions

Lecture 4. Defining Functions Lecture 4 Defining Functions Academic Integrity Quiz Reading quiz about the course AI policy Go to http://www.cs.cornell.edu/courses/cs11110/ Click Academic Integrity in side bar Read and take quiz in

More information