Introduction to Ruby, part I

Size: px
Start display at page:

Download "Introduction to Ruby, part I"

Transcription

1 Introduction to Ruby, part I April 20, 205 Output # evaluate expression and prints result. >> => 9 >> 7 * 3 => 2 >> Hello, world! => "Hello, world!" # print text on standard output >> puts Hello, world! Hello, world! 2 Dynamically typed variables >> v = nil # Creates a new variable v on the stack holding # a reference to an instance of NilClass. >> v = 42 # Updates the v variable with a reference to an => 42 # a Fixnum object, with value 42. >> s = Hello # Creates a new variable s on the stack holding a => "Hello" # reference to a String object with value Hello. >> v + s # Invokes the +-method on the Hello String # object referenced by the s variable. This will # raise a TypeError as the String object does not # know how to add a Fixnum to a String. >> v + s # + is invoked on the Fixnum, resulting in a # TypeError as String cannot automaticly be

2 # converted to Fixnum. >> v.to_s # The to_s-method returns a printable string => "42" # representation of the object. In this case # "42". >> s + v.to_s # Returns the concatenated string "Hello42" => "Hello42" >> s.methods # Returns an array of the methods defined for the => ["upcase!",...] # object referenced by s. >> s, v = v, s # Multiple assignment: Swaps the values of v and s. => [42, "Hello"] 3 Lists >> l = [v, s] # Creates a list(array) containing Hello and 42. => ["Hello", 42] >> l << 3.0 # All kinds of types may be mixed in a list. => ["Hello", 42, 3.0] >> l.pop # Removes and returns the last element in list. => 3.0 # Can pop multiple values, i.e. l.pop(2) returns # a list of the last two elements. >> r =..4 # Creates a new instance of the Range class =>..4 # Useful when looping. x..y is inclusive the # last element, x...y is exclusive. >> l = r.to_a # Creates a new array from the range => [, 2, 3, 4] >> l = l + [5, 6] # Concatenation of lists => [, 2, 3, 4, 5, 6] # Loop over each element in the list l and summarise in sum. >> l.each do element?> the_sum += element # Above loop will crash as the_sum is unassigned, and therefore # considered nil. NameError is raised as nil has no + method. >> the_sum = 0 >> l.each do element 2

3 ?> the_sum += element => [,2,3,4,5,6] # iteration returns the iterated object >> puts the_sum 2 # Alternate loop syntax >> l.each { element the_sum += element } 4 List access and slicing >> lst = [ a, b, c ] # Creates a new list from literal => ["a", "b", "c"] # representation >> lst = Array.new() # Creates a new list by calling => [] # constructor of the Array class # The index method [] takes one or two arguments. # The first is which index to retrieve, negative index means # count backwards from the end of the list. Second argument # is how many consecutive elements to returns as a new list. >> lst[] # Returns b as is the second position in list. => "b" >> lst[-] # Returns the last element of the list. => "c" >> lst[7] # Indexing outside of the list returns nil. # To make sure indexing outside the array results in errors, # one may use fetch instead. >> lst.fetch(7) IndexError: index 7 outside of array bounds: from (irb):59:in fetch from (irb):59 from /usr/local/bin/irb:2:in <main> >> lst[,] # Returns a new list containing "b", [start, length]. => ["b"] >> lst[0,3] # Returns 3 elements from index 0, [start, length]. => ["a","b","c"] >> lst.dup # Returns a copy of the list. => ["a", "b", "c"] 3

4 >> lst.reverse # Returns a copy of the list reversed. ["c", "b", "a"] 5 Associative arrays (Hashes/Dictionaries/Maps?) # Create a new Hash, with unordered mappings. >> h = { one =>, two =>2, three =>3, four =>4 } => {"three"=>3, "two"=>2, "one"=>, "four"=>4} >> h["one"] # Update hash, key "three" refers the same value as # key "four". >> h["three"] = h["four"] => 4 # Print string representation of the contents of the Hash. >> puts h.inspect {"three"=>4, "two"=>2, "one"=>, "four"=>4} >> h.keys => ["three", "two", "one", "four"] >> h.has_key? "four" >> h.has_value? 4 # Is this one of the values? # Iterate over the key/value-pairs and print each. >> h.each { key, value puts "#{key} => #{value}" } three => 4 two => 2 one => four => 4 => {"three"=>4, "two"=>2, "one"=>, "four"=>4} Control Structures, iteration, ranges again # The Ruby if-statement begins with "if" and a conditional (no do) # and ends with "end" >> if nil >> print "nil is true" 4

5 >> if false >> print "false is true" # "nil" and "false" evaluates to false in Ruby, everything else # (including 0) eveluates to true >> if 0 >> print "0 is true" 0 is true # Only nil and false are false # Logical operators ("and" and "or") can be used to combine # conditionals >> if 0 and [] and {} and >> puts "0 and [] and {} and are true" (irb):5: warning: string literal in condition 0 and [] and {} and are true # If-statements can be combined using "elsif". The "else" clause # will be run if none of the conditionals above evaluated to # true. >> name = "Yukihiro" => "Yukihiro" >> if name == "Yukihiro" >> puts "Ruby" >> elsif name == "Guido" >> puts "Python" >> else?> puts "None of the above" Ruby # "or" and "and" will be evaluated as boolean true/false but # will also always return one of the objects in the expression >> names = { "Yukihiro" => "Ruby",?> "Guido" => "Python",?> } => {"Yukihiro"=>"Ruby", "Guido"=>"Python"} >> puts names[name] or "None of the above" Ruby 5

6 => "None of the above" >> puts (names[name] or "None of the above") Ruby >> result = (false or Beatrice or false) => "Beatrice" >> if result >> puts result Beatrice >> result = ( Beatrice and [] and Isak ) => "Isak" >> if result >> puts result Isak # Negation of boolean values is done using "not". >> not false >> (not true) == false # The true and false values are represented by objects, and there # is only one true object and one false object >> (not true) === false >> (not true).object_id == false.object_id # The Ruby while-loop starts with "while" and a conditional and # ends with end >> i = 0 => 0 >> while i < 0 >> puts i >> i += 0. 6

7 . 8 9 # Several other ways of looping exists, e.g. the "each" iterator # in the Range class. >> lst =..0 =>..0 >> lst.each { i puts i} =>..0 # Or a for loop on the range class. >> for i in..4 >> puts i =>..4 # Below we see an example of operations that we could do with # lists. Using the "zip" method from the Array class we create a # new list containing lists of the elements from the original # lists that were found on the same index. >> cs = [ a, b, c ] => ["a", "b", "c"] >> ns = [,2,3] => [, 2, 3] >> zip = cs.zip(ns) => [["a", ], ["b", 2], ["c", 3]] # The list of lists is looped over using the "each" operator and # the elements of the lists inside the list are printed out. >> zip.each do ch, no?> puts "#{ch} #{no}" 7

8 a b 2 c 3 => [["a", ], ["b", 2], ["c", 3]] # The "collect" iterator will loop over the list collecting all # elements from the original list for which the conditional in the # code block evaluates to true. In this case, the code block # contains no conditional and all elements will be collected. >> chars = zip.collect { c, n c} => ["A", "b", "c"] >> nums = zip.collect { c, n n} => [, 2, 3] A first simple program # Let s say we have a file named "words.txt" with the following # words stored in it: # alpha # bravo # charlie # delta # echo # foxtrot # golf # hotel # india # juliet # kilo # lima # mike # november # oscar # papa # quebec # romeo # sierra # tango # uniform # victor # whiskey # xray # yankee # zulu 8

9 # The following code returns a list of words starting with a # (lowercase) vowel. >> matches = [] => [] >> vowels = "aoueiy".chars.to_a => ["a", "o", "u", "e", "i", "y"] >> f = open( words.txt ) => #<File:words.txt> >> f.each do line?> matches << line.strip if vowels.include? line.strip.chars.first => #<File:words.txt> >> matches => ["alpha", "echo", "india", "oscar", "uniform", "yankee"] 9

WSR Commands. WSR Commands: Mouse Grid: What can I say?: Will show a list of applicable commands

WSR Commands. WSR Commands: Mouse Grid: What can I say?: Will show a list of applicable commands WSR Commands Updated September 10, 2010 WSR Commands: What can I say?: Will show a list of applicable commands Refresh speech commands: Updates the list of speech commands that are currently available

More information

PHONETIC ALPHABET The use of standard phonetics for the pronunciation of letters in call signs and text aids accuracy and efficiency.

PHONETIC ALPHABET The use of standard phonetics for the pronunciation of letters in call signs and text aids accuracy and efficiency. This document contains the International Phonetic Alphabet, Pronunciation of Figures and ARES approved Prowords to be used for all ARES operations. PHONETIC ALPHABET The use of standard phonetics for the

More information

Installation Manual and User Guide

Installation Manual and User Guide SMARTEARS VOICE-BASED FILE BROWSER Installation Manual and User Guide Developed By Team 2 (Nehru Hall Of Residence) Anshul Gupta, Ashish Yadav, Arpit Agarwal, Arun Mallya & Aakash Goenka April 4, 2012

More information

Clock Commands. Cisco IOS XR System Management Command Reference for the Cisco CRS Router, Release 4.2.x 1

Clock Commands. Cisco IOS XR System Management Command Reference for the Cisco CRS Router, Release 4.2.x 1 This module describes the commands used to set and display the internal clock settings in Cisco IOS XR software. For more information about manually setting the router clock, see Cisco IOS XR Getting Started

More information

Digital Messages Using Windows and Android Devices

Digital Messages Using Windows and Android Devices Digital Messages Using Windows and Android Devices February 3, 2016 Dick Illman AH6EZ Types of Amateur Radio Disaster Communications Neighborhood Liason Relaying FRS user traffic Consolidating regional

More information

DATA 301 Introduction to Data Analytics Data Representation. Dr. Ramon Lawrence University of British Columbia Okanagan

DATA 301 Introduction to Data Analytics Data Representation. Dr. Ramon Lawrence University of British Columbia Okanagan DATA 301 Introduction to Data Analytics Data Representation Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca DATA 301: Data Analytics (2) Computer Terminology There is a

More information

Clock Commands on the Cisco IOS XR Software

Clock Commands on the Cisco IOS XR Software This module describes the commands used to set and display the internal clock settings in Cisco IOS XR software. For more information about manually setting the router clock, see Cisco IOS XR Getting Started

More information

Clock Commands on the Cisco IOS XR Software

Clock Commands on the Cisco IOS XR Software Clock Commands on the Cisco IOS XR Software This module describes the commands used to set and display the internal clock settings in Cisco IOS XR software. For more information about manually setting

More information

Clock Commands. Cisco IOS XR System Management Command Reference for the Cisco XR Series Router, Release 4.3.x OL

Clock Commands. Cisco IOS XR System Management Command Reference for the Cisco XR Series Router, Release 4.3.x OL This module describes the commands used to set and display the internal clock settings in Cisco IOS XR software. For more information about manually setting the router clock, see Cisco IOS XR Getting Started

More information

COMMUNICATION SYSTEMS RCT STUDY GUIDE Explain the importance of good communication.

COMMUNICATION SYSTEMS RCT STUDY GUIDE Explain the importance of good communication. LEARNING OBJECTIVES: 2.02.01 Explain the importance of good communication. 2.02.02 Identify the two methods of communication and be able to determine different types of each. 2.02.03 Describe different

More information

Survey Reading the Notes. COSC 122 Computer Fluency. Information Representation. Survey Class Still Easy? Key Points

Survey Reading the Notes. COSC 122 Computer Fluency. Information Representation. Survey Class Still Easy? Key Points COSC 122 Computer Fluency Information Representation Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Survey Reading the Notes Question: HONESTLY, how often do you read

More information

COSC 122 Computer Fluency. Information Representation. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 122 Computer Fluency. Information Representation. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 122 Computer Fluency Information Representation Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Survey Reading the Notes COSC 122 - Dr. Ramon Lawrence Question: HONESTLY,

More information

FOR EFFICIENT DICTATION

FOR EFFICIENT DICTATION TIPS FOR EFFICIENT DICTATION Page 1 / 6 1. Why dictate with Philips digital dictation systems? You can talk 7 times faster than you can write so you can record digitally far more speedily than on paper

More information

Advanced Python. Executive Summary, Session 1

Advanced Python. Executive Summary, Session 1 Advanced Python Executive Summary, Session 1 OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or use with operators). Everything in Python is an object.

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 4 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

15.1 Origins and Uses of Ruby

15.1 Origins and Uses of Ruby 15.1 Origins and Uses of Ruby - Designed by Yukihiro Matsumoto; released in 1996 - Use spread rapidly in Japan - Use is now growing in part because of its use in Rails - A pure object-oriented purely interpreted

More information

MathTalk. using. Dragon NaturallySpeaking. Pre-algebra, Algebra, Trig, Calculus Statistics, Graphing, etc. 1116

MathTalk. using. Dragon NaturallySpeaking. Pre-algebra, Algebra, Trig, Calculus Statistics, Graphing, etc. 1116 MathTalk for Scientific Notebook using Dragon NaturallySpeaking VOICE MATHEMATICS Pre-algebra, Algebra, Trig, Calculus Statistics, Graphing, etc. 1116 Metroplex Voice Computing, Inc. www.mathtalk.com mathtalk@mathtalk.com

More information

CS 5142 Scripting Languages

CS 5142 Scripting Languages CS 5142 Scripting Languages 10/25/2012 Ruby 1 Outline Ruby Martin Hirzel 2 About Ruby Invented 1995 by Yokihiro Matz Matsumoto Influenced by SmallTalk Everything is an object (even e.g., integers) Blocks

More information

Cumberland County ARES/RACES A SHORT GUIDE TO EMERGENCY RADIO COMMUNICATIONS INTRODUCTION

Cumberland County ARES/RACES A SHORT GUIDE TO EMERGENCY RADIO COMMUNICATIONS INTRODUCTION Cumberland County ARES/RACES A SHORT GUIDE TO EMERGENCY RADIO COMMUNICATIONS INTRODUCTION The following document is not intended to be detailed and comprehensive. It is intended to be a SHORT synopsis

More information

CMSC330 Spring 2015 Midterm #1 9:30am/11:00am/12:30pm

CMSC330 Spring 2015 Midterm #1 9:30am/11:00am/12:30pm CMSC330 Spring 2015 Midterm #1 9:30am/11:00am/12:30pm Name: Discussion Time (circle one): 10am 11am 12pm 1pm 2pm 3pm Discussion TA (circle one): Amelia Casey Chris Mike Elizabeth Eric Tommy Instructions

More information

What is Ruby? CSc 372. Comparative Programming Languages. 27 : Ruby Introduction. Department of Computer Science University of Arizona

What is Ruby? CSc 372. Comparative Programming Languages. 27 : Ruby Introduction. Department of Computer Science University of Arizona What is Ruby? CSc 372 Comparative Programming Languages 27 : Ruby Introduction Department of Computer Science University of Arizona Everything is an object. Everything can be changed: method can be added

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 3 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

FM 11-32: Team Speak

FM 11-32: Team Speak TABLE OF CONTENTS How To Connect to Team Speak...3 Steps To Connect...4 Team Speak Settings...5 Using Team Speak...5 Sound Options...5 Size, Icons and Acronyms...7 Team Speak Courtesy...8 Joining a Channel...8

More information

Lists, loops and decisions

Lists, loops and decisions Caltech/LEAD Summer 2012 Computer Science Lecture 4: July 11, 2012 Lists, loops and decisions Lists Today Looping with the for statement Making decisions with the if statement Lists A list is a sequence

More information

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017 SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Python I. Some material adapted from Upenn cmpe391 slides and other sources Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

CMSC330 Spring 2015 Midterm #1 9:30am/11:00am/12:30pm

CMSC330 Spring 2015 Midterm #1 9:30am/11:00am/12:30pm CMSC330 Spring 2015 Midterm #1 9:30am/11:00am/12:30pm Name: Discussion Time (circle one): 10am 11am 12pm 1pm 2pm 3pm Discussion TA (circle one): Amelia Casey Chris Mike Elizabeth Eric Tommy Instructions

More information

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015 SCHEME 7 COMPUTER SCIENCE 61A October 29, 2015 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Python. Executive Summary

Python. Executive Summary Python Executive Summary DEFINITIONS OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or response to operators). Everything in Python is an object. "atomic"

More information

Programming in Python

Programming in Python 3. Sequences: Strings, Tuples, Lists 15.10.2009 Comments and hello.py hello.py # Our code examples are starting to get larger. # I will display "real" programs like this, not as a # dialog with the Python

More information

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives CS 61A Scheme Spring 2018 Discussion 7: March 21, 2018 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme

More information

Ruby Topic Maps. Introduction to Ruby. Benjamin Bock.

Ruby Topic Maps. Introduction to Ruby. Benjamin Bock. Ruby Topic Maps http://rtm.rubyforge.org Introduction to Ruby Benjamin Bock 1 Calculator irb(main):001:0> 1+2 Type irb in your Terminal / Command / Shell window to start the interactive Ruby interpreter

More information

Your First Ruby Script

Your First Ruby Script Learn Ruby in 50 pages Your First Ruby Script Step-By-Step Martin Miliauskas @mmiliauskas 1 Your First Ruby Script, Step-By-Step By Martin Miliauskas Published in 2013 by Martin Miliauskas On the web:

More information

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives CS 6A Scheme Fall 207 Discussion 7: October 25, 207 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

More information

CSE 413 Programming Languages & Implementation. Hal Perkins Winter 2019 Ruby Containers, Blocks, and Procs

CSE 413 Programming Languages & Implementation. Hal Perkins Winter 2019 Ruby Containers, Blocks, and Procs CSE 413 Programming Languages & Implementation Hal Perkins Winter 2019 Ruby Containers, Blocks, and Procs CSE413 Winter 2019 1 The Plan Ruby container data structures Blocks and control structures (iterators,

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 4 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

Introduction to Ruby. SWEN-250 Personal Software Engineering

Introduction to Ruby. SWEN-250 Personal Software Engineering Introduction to Ruby SWEN-250 Personal Software Engineering A Bit of History Yukihiro "Matz'' Matsumoto Created a language he liked to work in. Been around since mid-90s. Caught on in early to mid 00s.

More information

Incident Command System Voice. Traffic Handling. User Guide WX4PBC Palm Beach County Skywarn Creative Commons

Incident Command System Voice. Traffic Handling. User Guide WX4PBC Palm Beach County Skywarn  Creative Commons Incident Command System Voice Traffic Handling User Guide WX4PBC Palm Beach County Skywarn www.pbcskywarn.org Creative Commons Licensees may copy, distribute, display and perform the work and make derivative

More information

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Language Syntax version beta Proposed Syntax

Language Syntax version beta Proposed Syntax Superpowered game development. Language Syntax version.0. beta Proposed Syntax Live/current version at skookumscript.com/docs/v.0/lang/syntax/ November, 0 Better coding through mad science. Copyright 00-0

More information

ABC DNSSEC Key Ceremony Scripts

ABC DNSSEC Key Ceremony Scripts Abbreviations ABC DNSSEC Key Ceremony Scripts KMF= Key Management Facility TEB = Tamper Evident Bag (large DIEBOLD item #00051991000C small #00051991000A) HSM = Hardware Security Module FD = Flash Drive

More information

Programming Ruby The Pragmatic Programmers Guide

Programming Ruby The Pragmatic Programmers Guide Extracted from: Programming Ruby The Pragmatic Programmers Guide Second Edition This PDF file contains pages extracted from Programming Ruby, published by The Pragmatic Bookshelf. For more information,

More information

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists Module 04: Lists Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10 1 Consider the string method split >>> name = "Harry James Potter" >>> name.split() ['Harry',

More information

UC Getting Started. Overview. Getting Started page 1

UC Getting Started. Overview. Getting Started page 1 UC Getting Started Contents Overview Tip: to navigate to a section say UC Getting Started 1-4 (Point 1-5), for example, Getting Started 4 1. Whirlwind tour 2. The First Commands cheat sheet 3. The elements

More information

CS111 Jeopardy: The Home Version

CS111 Jeopardy: The Home Version CS111 Jeopardy: The Home Version The game that turns CS111 into CSfun11! Fall 2018 This is intended to be a fun way to review some of the topics that will be on the CS111 final exam. These questions are

More information

"Hello" " This " + "is String " + "concatenation"

Hello  This  + is String  + concatenation Strings About Strings Strings are objects, but there is a special syntax for writing String literals: "Hello" Strings, unlike most other objects, have a defined operation (as opposed to a method): " This

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

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python Python Sequence Types Sequence types str and bytes are sequence types Sequence types have several operations defined for them Indexing Python Sequence Types Each element in a sequence can be extracted

More information

Ruby: Useful Classes and Methods

Ruby: Useful Classes and Methods Ruby: Useful Classes and Methods Computer Science and Engineering College of Engineering The Ohio State University Lecture 6 Ranges Instance of class (Range) indices = Range.new(0, 5) But literal syntax

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

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives CS 6A Scheme Fall 208 Discussion 8: October 24, 208 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

More information

Lecture 1. Basic Ruby 1 / 61

Lecture 1. Basic Ruby 1 / 61 Lecture 1 Basic Ruby 1 / 61 What does this do? 3.times do print 'Hello, world!' end 2 / 61 Why Ruby? Optimized for programmer happiness Used for Ruby on Rails Very popular web framework 3 / 61 Course Policies

More information

Strengthen Your Python Foundations

Strengthen Your Python Foundations Strengthen Your Python Foundations The code examples that are provided along with the chapters don't require you to master Python. However, they will assume that you previously obtained a working knowledge

More information

CS 11 python track: lecture 3. n Today: Useful coding idioms

CS 11 python track: lecture 3. n Today: Useful coding idioms CS 11 python track: lecture 3 Today: Useful coding idioms Useful coding idioms "Idiom" Standard ways of accomplishing a common task Using standard idioms won't make your code more correct, but more concise

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 3 Thomas Wies New York University Review Last week Names and Bindings Lifetimes and Allocation Garbage Collection Scope Outline Control Flow Sequencing

More information

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals Midterm 1 Review Important control structures Functions Loops Conditionals Important things to review Binary numbers Boolean operators (and, or, not) String operations: len, ord, +, *, slice, index List

More information

CS 303E Fall 2011 Exam 2 Solutions and Criteria November 2, Good Luck!

CS 303E Fall 2011 Exam 2 Solutions and Criteria November 2, Good Luck! CS 303E Fall 2011 Exam 2 Solutions and Criteria November 2, 2011 Name: EID: Section Number: Friday discussion time (circle one): 9-10 10-11 11-12 12-1 2-3 Friday discussion TA(circle one): Wei Ashley Answer

More information

Positional, keyword and default arguments

Positional, keyword and default arguments O More on Python n O Functions n Positional, keyword and default arguments in repl: >>> def func(fst, snd, default="best!"):... print(fst, snd, default)... >>> func(snd='is', fst='python') ('Python', 'is',

More information

Documentation for LISP in BASIC

Documentation for LISP in BASIC Documentation for LISP in BASIC The software and the documentation are both Copyright 2008 Arthur Nunes-Harwitt LISP in BASIC is a LISP interpreter for a Scheme-like dialect of LISP, which happens to have

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Iterators, Generators, Exceptions & IO Raymond Yin University of Pennsylvania September 28, 2016 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 2016 1 / 26 Outline

More information

Computer Sciences 368 Scripting for CHTC Day 3: Collections Suggested reading: Learning Python

Computer Sciences 368 Scripting for CHTC Day 3: Collections Suggested reading: Learning Python Day 3: Collections Suggested reading: Learning Python (3rd Ed.) Chapter 8: Lists and Dictionaries Chapter 9: Tuples, Files, and Everything Else Chapter 13: while and for Loops 1 Turn In Homework 2 Homework

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Object Oriented Programming Harry Smith University of Pennsylvania February 15, 2016 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 1 / 26 Outline

More information

Ruby. Mooly Sagiv. Most slides taken from Dan Grossman

Ruby. Mooly Sagiv. Most slides taken from Dan Grossman Ruby Mooly Sagiv Most slides taken from Dan Grossman Ruby dynamic, reflective, object-oriented, general-purpose programming language Designed and developed in the mid-1990s by Yukihiro "Matz" Matsumoto

More information

Sequences and iteration in Python

Sequences and iteration in Python GC3: Grid Computing Competence Center Sequences and iteration in Python GC3: Grid Computing Competence Center, University of Zurich Sep. 11 12, 2013 Sequences Python provides a few built-in sequence classes:

More information

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A DEBUGGING TIPS COMPUTER SCIENCE 61A 1 Introduction Every time a function is called, Python creates what is called a stack frame for that specific function to hold local variables and other information.

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Array, Hashes, Code Blocks, Equality 1 Arrays and Hashes Ruby data structures are typically constructed from Arrays and Hashes Built-in syntax for both Each

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1(c): Java Basics (II) Lecture Contents Java basics (part II) Conditions Loops Methods Conditions & Branching Conditional Statements A

More information

Introduction CMSC 330: Organization of Programming Languages. Books on Ruby. Applications of Scripting Languages

Introduction CMSC 330: Organization of Programming Languages. Books on Ruby. Applications of Scripting Languages Introduction CMSC 330: Organization of Programming Languages Ruby is an object-oriented, imperative scripting language I wanted a scripting language that was more powerful than Perl, and more object-oriented

More information

Typed Racket: Racket with Static Types

Typed Racket: Racket with Static Types Typed Racket: Racket with Static Types Version 5.0.2 Sam Tobin-Hochstadt November 6, 2010 Typed Racket is a family of languages, each of which enforce that programs written in the language obey a type

More information

5. VHDL - Introduction - 5. VHDL - Design flow - 5. VHDL - Entities and Architectures (1) - 5. VHDL - Entities and Architectures (2) -

5. VHDL - Introduction - 5. VHDL - Design flow - 5. VHDL - Entities and Architectures (1) - 5. VHDL - Entities and Architectures (2) - Sistemas Digitais I LESI - 2º ano Lesson 5 - VHDL Prof. João Miguel Fernandes (miguel@di.uminho.pt) Dept. Informática - Introduction - VHDL was developed, in the mid-1980s, by DoD and IEEE. VHDL stands

More information

MEIN 50010: Python Data Structures

MEIN 50010: Python Data Structures : Python Data Structures Fabian Sievers Higgins Lab, Conway Institute University College Dublin Wednesday, 2017-10-18 Data Structures Stacks, Queues & Deques Structures Data structures are a way of storing

More information

SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012

SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012 SCHEME COMPUTER SCIENCE 6A October 29th, 202 In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs, we will eventually

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Iterators, Generators, IO, and Exceptions Harry Smith University of Pennsylvania February 15, 2018 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2018

More information

CS115 - Module 9 - filter, map, and friends

CS115 - Module 9 - filter, map, and friends Fall 2017 Reminder: if you have not already, ensure you: Read How to Design Programs, Intermezzo 3 (Section 18); Sections 19-23. Abstraction abstraction, n. 3a.... The process of isolating properties or

More information

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1 EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1 COMPUTER SCIENCE 61A June 24, 2014 0.1 Warmup What Would Python Do? >>> x = 6 >>> def square(x):... return x * x >>> square(x) >>> max(pow(2, 3), square(-5)) -

More information

Message Passing USE AND DISTRIBTION NOTICE. Housekeeping. Agenda. Message Passing Tabletop 1/31/2018

Message Passing USE AND DISTRIBTION NOTICE. Housekeeping. Agenda. Message Passing Tabletop 1/31/2018 USE AND DISTRIBTION NOTICE Message Passing Santa Clara County RACES authorization is granted to use and duplicate this material as is as long as this page and the copyright notices on each page are included,

More information

A Tour of Ruby.... for Java programmers

A Tour of Ruby.... for Java programmers A Tour of Ruby... for Java programmers Everything has a value Everything has a value, which I'll show in a comment (following Matsumoto): 1234 # => 1234 2 + 2 # => 4 'Hello' + 'World' # => 'HelloWorld'

More information

4. Write the output that would be printed from each of the following code fragments. (8pts) x = 9 y = x / 2 print('y ==', y) +1 4.

4. Write the output that would be printed from each of the following code fragments. (8pts) x = 9 y = x / 2 print('y ==', y) +1 4. 1. Write an X To the left of each valid Python name (identifier). (4pts) a) X pyhonindetfriar c) X a_b_c_d b) 9to5 d) x*y all or none 2. Write an X To the left of each Python reserved word (keyword). (4pts)

More information

Iterators and blocks. Using iterators and blocks Iterate with each or use a for loop? Creating iterators

Iterators and blocks. Using iterators and blocks Iterate with each or use a for loop? Creating iterators Iterators and blocks Using iterators and blocks Iterate with each or use a for loop? Creating iterators CSc 372, Fall 2006 Ruby, Slide 77 Iterators and blocks Some methods are iterators. An iterator that

More information

Introduction to Python

Introduction to Python Introduction to Python Reading assignment: Perkovic text, Ch. 1 and 2.1-2.5 Python Python is an interactive language. Java or C++: compile, run Also, a main function or method Python: type expressions

More information

Artificial Intelligence A Primer for the Labs

Artificial Intelligence A Primer for the Labs Artificial Intelligence A Primer for the Labs Mathias Broxvall, Lia Susana d.c. Silva Lopez, November 2011 Chapter 1 General python instructions This document contains a quick primer for using Python

More information

EZ- ASCII: Language Reference Manual

EZ- ASCII: Language Reference Manual EZ- ASCII: Language Reference Manual Dmitriy Gromov (dg2720), Feifei Zhong (fz2185), Yilei Wang (yw2493), Xin Ye (xy2190), Joe Lee (jyl2157) Table of Contents 1 Program Definition... 3 2 Lexical Conventions...

More information

OOP and Scripting in Python Advanced Features

OOP and Scripting in Python Advanced Features OOP and Scripting in Python Advanced Features Giuliano Armano Emanuele Tamponi Advanced Features Structure of a Python Script More on Defining Functions Default Argument Values Keyword Arguments Arbitrary

More information

Python A Technical Introduction. James Heliotis Rochester Institute of Technology December, 2009

Python A Technical Introduction. James Heliotis Rochester Institute of Technology December, 2009 Python A Technical Introduction James Heliotis Rochester Institute of Technology December, 2009 Background & Overview Beginnings Developed by Guido Van Rossum, BDFL, in 1990 (Guido is a Monty Python fan.)

More information

FORM 2 (Please put your name and form # on the scantron!!!!)

FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam 2: FORM 2 (Please put your name and form # on the scantron!!!!) True (A)/False(B) (2 pts each): 1. Recursive algorithms tend to be less efficient than iterative algorithms. 2. A recursive function

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

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

CS2304: Python for Java Programmers. CS2304: Sequences and Collections CS2304: Sequences and Collections Sequences In Python A sequence type in python supports: The in membership operator. The len() function. Slicing like we saw with strings, s[1:3]. And is iterable (for

More information

Structure and Flow. CS 3270 Chapter 5

Structure and Flow. CS 3270 Chapter 5 Structure and Flow CS 3270 Chapter 5 Python Programs Are made up of modules One module is the main (top-level) module The first one loaded (even if it s the interpreter) Its module object has main as its

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

Variables, Constants, and Data Types

Variables, Constants, and Data Types Variables, Constants, and Data Types Strings and Escape Characters Primitive Data Types Variables, Initialization, and Assignment Constants Reading for this lecture: Dawson, Chapter 2 http://introcs.cs.princeton.edu/python/12types

More information

CS100: CPADS. Decisions. David Babcock / Don Hake Department of Physical Sciences York College of Pennsylvania

CS100: CPADS. Decisions. David Babcock / Don Hake Department of Physical Sciences York College of Pennsylvania CS100: CPADS Decisions David Babcock / Don Hake Department of Physical Sciences York College of Pennsylvania James Moscola Decisions Just like a human, programs need to make decisions - Should turtle turn

More information

Tuples. CMSC 330: Organization of Programming Languages. Examples With Tuples. Another Example

Tuples. CMSC 330: Organization of Programming Languages. Examples With Tuples. Another Example CMSC 330: Organization of Programming Languages OCaml 2 Higher Order Functions Tuples Constructed using (e1,..., en) Deconstructed using pattern matching Patterns involve parens and commas, e.g., (p1,p2,

More information

Lists CS 1111 Introduction to Programming Fall 2018

Lists CS 1111 Introduction to Programming Fall 2018 Lists CS 1111 Introduction to Programming Fall 2018 [The Coder s Apprentice, 12] 1 Overview: Lists List = ordered sequence of values Mutable data type Because of the ordering, an element in a list can

More information

Basic types and definitions. Chapter 3 of Thompson

Basic types and definitions. Chapter 3 of Thompson Basic types and definitions Chapter 3 of Thompson Booleans [named after logician George Boole] Boolean values True and False are the result of tests are two numbers equal is one smaller than the other

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

Python Evaluation Rules

Python Evaluation Rules Python Evaluation Rules UW CSE 160 https://courses.cs.washington.edu/courses/cse160/15sp/ Michael Ernst and Isaac Reynolds mernst@cs.washington.edu April 1, 2015 Contents 1 Introduction 2 1.1 The Structure

More information

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming 2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float

More information

COMP284 Scripting Languages Lecture 3: Perl (Part 2) Handouts

COMP284 Scripting Languages Lecture 3: Perl (Part 2) Handouts COMP284 Scripting Languages Lecture 3: Perl (Part 2) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool

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

CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1

CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1 CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1 Goals of this tutorial You should be able to... understand

More information