Guide to Programming with Python Chapter Two Basic data types, Variables, and Simple I/O: The Useless Trivia Program.

Slides:



Advertisements
Similar presentations
Lecture 2 Introduction to C Programming
Advertisements

Introduction to C Programming
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Introduction to C Programming
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Python November 14, Unit 7. Python Hello world, in class.
 2002 Prentice Hall. All rights reserved. 1 Intro: Java/Python Differences JavaPython Compiled: javac MyClass.java java MyClass Interpreted: python MyProgram.py.
Data types and variables
Introduction to Python
CS 1 with Robots Variables, Data Types & Math Institute for Personal Robots in Education (IPRE)‏
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
 2002 Prentice Hall. All rights reserved. 1 Chapter 2 – Introduction to Python Programming Outline 2.1 Introduction 2.2 First Program in Python: Printing.
Introduction to C Programming
Basic Input/Output and Variables Ethan Cerami New York
Basic Elements of C++ Chapter 2.
Guide to Programming with Python
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Chapter 2 Data Types, Declarations, and Displays.
Objectives You should be able to describe: Data Types
Introduction to Python
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Agenda  Commenting  Inputting Data from Keyboard (scanf)  Arithmetic Operators  ( ) * / + - %  Order of Operations  Mixing Different Numeric Data.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 2 Input,
Input, Output, and Processing
Computer Science 101 Introduction to Programming.
Chapter 2: Using Data.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
Week 1 Algorithmization and Programming Languages.
Beginning C++ Through Game Programming, Second Edition
Knowledge Base C++ #include using std namespace; int main(){} return 0 ; cout
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
COMP 171: Data Types John Barr. Review - What is Computer Science? Problem Solving  Recognizing Patterns  If you can find a pattern in the way you solve.
Variables, Expressions and Statements
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
CS 1 with Robots Variables, Data Types & Math Institute for Personal Robots in Education (IPRE)‏ Sec 9-7 Web Design.
Chapter 2 Variables.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
Programming Fundamentals. Overview of Previous Lecture Phases of C++ Environment Program statement Vs Preprocessor directive Whitespaces Comments.
Data Tonga Institute of Higher Education. Variables Programs need to remember values.  Example: A program that keeps track of sales needs to remember.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
Python Let’s get started!.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
C++ for Engineers and Scientists Second Edition
Data Manipulation Variables, Data Types & Math. Aug Variables A variable is a name (identifier) that points to a value. They are useful to store.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
More about comments Review Single Line Comments The # sign is for comments. A comment is a line of text that Python won’t try to run as code. Its just.
Topics Designing a Program Input, Processing, and Output
Chapter 2 Basic Computation
Python Let’s get started!.
Variables, Expressions, and IO
Useful String Methods Cont…
Introduction to C++ Programming
Escape sequences: Practice using the escape sequences on the code below to see what happens. Try this next code to help you understand the last two sequences.
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Variables, Data Types & Math
Variables, Data Types & Math
Core Objects, Variables, Input, and Output
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Variables, Data Types & Math
Unit 3: Variables in Java
Presentation transcript:

Guide to Programming with Python Chapter Two Basic data types, Variables, and Simple I/O: The Useless Trivia Program

Objectives  Variables: –Store data in the computer’s memory –Legal names & good names –Use variables to access and manipulate that data  Basic data types –String (single, double, and triple-quoted strings; escape sequences made up of two characters, a backslash followed by another character) –Numeric types (integers & floats); make programs do math –Type conversion: str -> int, int -> str, etc –Function (method)  Get input from users to create interactive programs Guide to Programming with Python2

Variables  Variable: Represents a value; provides way to get at information in computer memory  Variables allow you to store and manipulate information  You can create variables to organize and access this information  Assignment statement: Assigns a value to a variable; creates variable if necessary  name = "Larry" –Stores string "Larry" in computer memory –Creates variable name, which refers to "Larry" Guide to Programming with Python3

Naming Variables  Rules for legal variable names –Can contain only numbers, letters, and underscores –Can’t start with a number –Can’t be a keyword  Keyword: Built-in word with special meaning  Legal Names –velocity, player2, max_health  Illegal Names –?again, 2nd_player, print Guide to Programming with Python4

Naming Variables (continued)  Guidelines for good variable names –Choose descriptive names; score instead of s –Be consistent; high_score or highScore –Follow traditions; Names that begin with underscore have special meaning –Keep the length in check personal_checking_account_balance - too long? –Self-documenting code: Code written so that it’s easy to understand, independent of any comments Guide to Programming with Python5

Strings: Using Quotes  Using quotes inside strings –Define with either single ( ' ) or double quotes ( " ) 'Game Over' or "Game Over" –Define with one type, use other type in string "Program 'Game Over' 2.0"  Triple-quoted strings can span multiple lines """ I am a triple-quoted string """  Line-continuation character \ Guide to Programming with Python6

Strings: Using Escape Sequences  Escape sequence: Set of characters that allow you to insert special characters into a string –Backslash followed by another character –e.g. \n –Simple to use  Escape sequence give you greater control and flexibility over the text you display (e.g., fancy_credits.py) Guide to Programming with Python7

Escape Sequences (\?)  System bell –print "\a”  Newline –print "\nSpecial thanks goes out to:” Guide to Programming with Python8

Concatenating/Repeating Strings  String concatenation: Joining together of two strings to form a new string (string concatenation operator +) –"concat" + "enate” Compare the following: -print "contat", "enate” -print "contat” + "enate” (Print multiple values print "\nGrand Total: ", total)  String operator * creates a new string by concatenating a string a specified number of times –"Pie" * 10 = "PiePiePiePiePiePiePiePiePiePie” 9

ASCII Arts Guide to Programming with Python10 anzer_unt_Sattelzug.png HW: my_art.py ASCII: American Standard Code for Information Interchange

String Methods  Method: A function that an object has  Use dot notation to call (or invoke) a method –Use variable name for object, followed by dot, followed by method name and parentheses –an_object.a_method() –string.upper() #e.g., string.upper("abc") –"abc".upper() –Built-in method, like raw_input() can be called on its own.  Strings have methods that can make & return new strings Guide to Programming with Python11

String Methods (continued)  quote = "I think there is a world market for maybe five computers." –print quote.upper() I THINK THERE IS A WORLD MARKET FOR MAYBE FIVE COMPUTERS. –print quote.lower() i think there is a world market for maybe five computers. –print quote.title() I Think There Is A World Market For Maybe Five Computers. –print quote.replace("five", "millions of") I think there is a world market for millions of computers.  Original string unchanged –print quote I think there is a world market for maybe five computers. Guide to Programming with Python12

String Methods (continued) Table 2.4: Useful string methods Guide to Programming with Python13 optional parameter

Working with Numbers  Can work with numbers as easily as with strings  Need to represent numbers in programs –Score in space shooter game –Account balance in personal finance program  Numeric types –Integers: Numbers without a fractional part 1, 0, 27, -100 –Floating-Point Numbers (or Floats): Numbers with a fractional part 2.376, -99.1, 1.0  Guide to Programming with Python14

Mathematical Operators  Addition and Subtraction –print displays 1950  Integer Division –print 24 / 6 displays 4 –But print 19 / 4 displays 4 as well –Result of integer division always integer (rounding down)  Floating-Point Division –print 19.0 / 4 displays 4.75 –When at least one number is a float, result is a float  Modulus (remainder of integer division) –print 107 % 4 displays 3 Guide to Programming with Python15

Mathematical Operators (continued) Guide to Programming with Python16 The result of integer division is always a integer The result of float division is always a float Python 2.x vs Python 3.x

Augmented Assignment Operators  Common to assign a value to a variable based on its original value  Augmented assignment operators provide condensed syntax –Original: score = score + 1 –Augmented: score += 1 Guide to Programming with Python17

Using the Right Types  Python does not need to specify the type of a variable in advance (by contrast, C does) Python: cost = 10 C: int cost = 10;  Important to know which data types are available  Equally important to know how to work with them  If not, might end up with program that produces unintended results  Converting values: e.g., int(“3”) = 3 Guide to Programming with Python18

Getting User Input by raw_input  raw_input() function –Prompts the user for text input –Returns what the user entered as a string  name = raw_input("Hi. What's your name? ") –argument "Hi. What's your name?” –Returns what user entered as a string –In assignment statement, name gets returned string  Function: A named collection of programming code that can receive values, do work, and return values  Argument: Value passed to a function  Return value: Value returned from a function upon completion Guide to Programming with Python19

Using User Inputs Properly  int() function converts a value to an integer car = raw_input("Lamborghini Tune-Ups: ") car = int(car)  Can nest multiple function calls (nesting function calls means putting one inside the other) rent = int(raw_input("Manhattan Apartment: ")) Guide to Programming with Python20

In This Example: total = ? car = raw_input("Lamborghini Tune-Ups: ") rent = raw_input("Manhattan Apartment: ") jet = raw_input("Private Jet Rental: ") gifts = raw_input("Gifts: ") food = raw_input("Dining Out: ") staff = raw_input("Staff (butlers, chef, driver, assistant): ") guru = raw_input("Personal Guru and Coach: ") games = raw_input("Computer Games: ") total = car + rent + jet + gifts + food + staff + guru + games  car, rent, jet, gifts, food, staff, guru, games are strings  total is concatenation of all strings Guide to Programming with Python21

Logic Errors  Logic Error: An error that doesn’t cause a program to crash, but instead produces unintended results (compare to Syntax error)  Program output that looks like very large number:  Remember, raw_input() returns a string, so program is not adding numbers, but concatenating strings  Debugging a program is difficult –Myth #1: “My program gives nicer results before I fix the bug” Guide to Programming with Python22

Summary  A variable represents a value and provides way to get at information in computer memory –An assignment statement assigns a value to a variable and creates variable if necessary –Augmented assignment operators e.g., x += 10  Basic data types: –Strings (escape sequences) –Numeric types (int, float) –Mathematical operators (+, *)  A function is a named collection of programming code that can receive values (arguments), do some work, and return values, e.g., raw_input(), string methods Guide to Programming with Python23