MIT AITI Python Software Development

Similar documents
6.S189 Homework 1. What to turn in. Exercise 1.1 Installing Python. Exercise 1.2 Hello, world!

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

Expressions and Variables

Fundamentals: Expressions and Assignment

CS 115 Lecture 4. More Python; testing software. Neil Moore

CSCE 120: Learning To Code

Learning the Language - V

Introduction to programming with Python

ENGR 101 Engineering Design Workshop

CSI Lab 02. Tuesday, January 21st

Name & Recitation Section:

CS 112: Intro to Comp Prog

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore

Hello, World and Variables

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

Ex: If you use a program to record sales, you will want to remember data:

My First Python Program

6.149 Checkoff 2. What to complete. Recall: Creating a file and running a program in IDLE.

Python for Non-programmers

CIS 110: Introduction to Computer Programming

Variables, expressions and statements

Lecture 3. Input, Output and Data Types

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

Algorithms and Programming I. Lecture#12 Spring 2015

Python Programming Exercises 1

Text Input and Conditionals

NESTED IF STATEMENTS AND STRING/INTEGER CONVERSION

Turn in a printout of your code exercises stapled to your answers to the written exercises at 2:10 PM on Thursday, January 13th.

Downloaded from Chapter 2. Functions

C++ Programming: From Problem Analysis to Program Design, Third Edition

Introduction to Python and programming. Ruth Anderson UW CSE 160 Winter 2017

CS109A ML Notes for the Week of 1/16/96. Using ML. ML can be used as an interactive language. We. shall use a version running under UNIX, called

Visual Basic for Applications

Problem Solving for Intro to Computer Science

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Logical Thinking through Computer Programming

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

2. INTRODUCTORY EXCEL

4. Java Project Design, Input Methods

CSE 115. Introduction to Computer Science I

Basic Data Types and Operators CS 8: Introduction to Computer Science, Winter 2019 Lecture #2

CMSC 201 Computer Science I for Majors

Information Science 1

SAMS Programming A/B. Lecture #1 Introductions July 3, Mark Stehlik

Implementing an Algorithm for Boomerang Fraction Sequences in Python

Computer Architecture and System Software Lecture 02: Overview of Computer Systems & Start of Chapter 2

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

CS1 Lecture 3 Jan. 18, 2019

Topic 4 Expressions and variables

CSC-140 Assignment 6

Topic 2: Introduction to Programming

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.

Chapter Two PROGRAMMING WITH NUMBERS AND STRINGS

Python Input, output and variables. Lecture 23 COMPSCI111/111G SS 2018

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

AQA Decision 1 Algorithms. Section 1: Communicating an algorithm

Variables, Data Types, and Arithmetic Expressions Learning Objectives:

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

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

Lecture 1. Types, Expressions, & Variables

6.S189 Homework 2. What to turn in. Exercise 3.1 Defining A Function. Exercise 3.2 Math Module.

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

Modular Arithmetic. Marizza Bailey. December 14, 2015

Python for Analytics. Python Fundamentals RSI Chapters 1 and 2

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

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

Full file at

Information Science 1

Variable and Data Type I

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

1. What type of error produces incorrect results but does not prevent the program from running? a. syntax b. logic c. grammatical d.

This lab will introduce you to MySQL. Begin by logging into the class web server via SSH Secure Shell Client

CIS133J. Working with Numbers in Java

1/11/2010 Topic 2: Introduction to Programming 1 1

The PHP language. Teaching you everything about PHP? Not exactly Goal: teach you how to interact with a database via web

CMSC201 Computer Science I for Majors

Variable and Data Type I

Variables, Expressions, and Statements

Recall that strings and tuples are immutable datatypes, while lists are mutable datatypes. What does this mean?

CSc 372. Comparative Programming Languages. 4 : Haskell Basics. Department of Computer Science University of Arizona

If Statements, For Loops, Functions

MODULE 02: BASIC COMPUTATION IN JAVA

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

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

FRAC: Language Reference Manual

CMSC 201 Fall 2018 Lab 04 While Loops

CMSC201 Computer Science I for Majors

Unit 3. Constants and Expressions

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

INFORMATION TECHNOLOGY SPREADSHEETS. Part 1

cs1114 REVIEW of details test closed laptop period

COMP 110 Introduction to Programming. What did we discuss?

Welcome to CS61A! Last modified: Thu Jan 23 03:58: CS61A: Lecture #1 1

Introduction to Programming in Turing. Input, Output, and Variables

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

CS1 Lecture 3 Jan. 22, 2018

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

Python Input, output and variables

Introduction to TURING

Transcription:

MIT AITI Python Software Development PYTHON L02: In this lab we practice all that we have learned on variables (lack of types), naming conventions, numeric types and coercion, strings, booleans, operator grouping, and relational operators. Exercise 2.1) Variables Recall that variables are containers for storing information. For example Program text: a = Hello, world! print a Output: Hello, world! 1. In python, variables are not classified into types. Remember that variable names must start with an letter and not a number. Before you write your code determine which of the following variable names are good. Feel free to check if you are right by using them in your python shell. What are your reasons for why some are not good? a] list bad, too vague b] 56thnumber bad, should use a list if storing many ordered variables c] length good, but could be more specific d]!tayo! bad, not alphanumeric e] NUMBER bad, too general and doesn t follow lowercase convention f] hklgiup bad, nonsensical g] Nokia_phone1 good h] 1170hjhh bad, nonsensical i] answer_to_ex 1.1 bad, can't have decimals j] the answer bad, can't have spaces When making variable names in python be sure to make variable names that are relevant to your code. Avoid having variable names like a or khlkh which are ambiguous and do not give the reader any understanding or insight on what is being stored in your variable. For example if you re making a variable that stores a phone number you can use variable names like phone_number or phone_num etc. Exercise 2.2) Types 1. It is important that we know the type of the values stored in a variable so that we can use the correct operators. Python automatically infers the type from the value you assign

to the variable. Write down the type of the values stored in each of the variables below. Pay special attention to punctuation: values are not always the type they seem! 1. a = False boolean 2. b = 3.7 float 3. c = 'Alex' string 4. d = 7 int 5. e = 'True' string 6. f = 17 int 7. g = '17 null (error raised) 8. h = True boolean 9. i = '3.14159' string 10. j = ---add--- string To verify your answers, you can use the interactive Python shell, but first try to do the exercise without help. >>> a = False False >>> type(a) <type 'bool'> Exercise 2.3) Strings and String Operators 1. Given the following variables: school = 'Strathmore' now = 'NOW' 1. school[:4] stra 2. school[-1] e 3. school*2 StrathmoreStrathmore 4. school[:-1] + now + school[-1] StrathmorNOWe 5. now[1] O 6. now[4] error 7. school*2 + school*[:-1] + now + school*[-1] error You can use the python shell to clarify your answers. 2. In this part of the exercise you will explore string operators a discussed in class. Now write a series of print statements to print out a greeting box and a goodbye message that can be sent as a text. name = 'John Adetunji' greeting = 'Happy Birthday' goodbye = 'Goodbye, all!' space = ' ' star = *

Use only the first name in the greeting box and only the last name in the goodbye message e.g. they should read Happy Birthday John and Goodbye Adetunji respectively. You can use other like -, # to make the greeting card prettier but be sure to store them in variable to make your work easy. Save the file as greetings.py. print star*20 print greeting+space+name[:name.find(' ')] print goodbye[:goodbye.find(',')]+name[name.find(' '):] print star*20 Exercise 2.4) Boolean: 1. Boolean operators can seem tricky at first, and it takes practice to evaluate them correctly. Write the value (True or False) produced by each expression below, using the assigned values of the variables a, b, and c. a = False b = True c = False 1. b and c False 2. b or c True 3. not a and b True 4. (a and b) or not c True 5. not b and not (a or c) False 6. not ((not b or not a) and c ) or a True Remember, to work from the inside out, starting with the inner-most expressions, like in arithmetic. Evercise 2.5) Operations: Order of Operation Python has the ability to be used as a cheap, 5-dollar calculator. In particular, it supports basic mathematical operators +, -, *, / as well as the power operator (**) and the modulus operator (%). Program Text: x = 5 + 7 print x y = x + 10 print y Output:

12 22 Note that we can use variables in the definition of other variables! Mathematical operators only work on numbers-ints or floats. Statements such as Hi + 5 or 5 + 7 will not work. 1. Input the following sets of equations, and note the difference between int arithmetic and float arithmetic. You can do this just in your interpreter (you don t need to turn anything in for this part), but pay attention to the output! a] 5/2, 5/2.0 and 5.0/2- Note that as long as one argument is a float, all of your math will be floating point! b] 7*(1/2) and 7* (1/2.0) c] 5 2, 5.0 2, and 5 2.0 d] 1/3.0- Note the final digit is rounded. Python does this for non-terminating decimal numbers, as computers cannot store infinite numbers! Take 6.004 to find out more about this... 2. Transcribe the following equations into Python (without simplifying!), preserving order of operation with parenthesis as needed. Save each as the value of a variable, and then print the variable. a] 3 5/2+3 (3*5)/(2+3), could differ b] 7 + 9 2 same c] (-19)**.25+100 d] 6 mod 4 - If you aren t familiar with modular arithmetic, it is pretty straightforward- the modulus operator in the expression x mod y, gives the remainder when x is divided by y. Try a couple modular expressions until you get the hang of it. It is written as 6%4 3. The order of evaluation for an arithmetic or logical expression is determined by operator precedence rules. For each of the following expressions, add parentheses so that the precedence is explicit, and then write down the value of the expression. Then add parentheses that change the value of the expression, and write the new value (you only need to find one example of this). For example: Example: 3 * 4 + 60 / 2 Answer: (3 * 4) + (60 / 2) = 42 3 * (4 + 60) / 2 = 96 a] 4 + 3 * 4 + 4 4+(3*4)+4 b] 4.0 / 3.0 + 1 (4.0/3.0)+1 c] not False and (3 > 4) (not False) and (3>4)

4. Some new operators are +=, -=, *=, /=. They change the value of the stored variable in quickest way. we add 6 to a variable in two different ways; note that we get the same result! Try using all of these operators in your interpreter window before moving on. >>> x = 5 >>> x = x + 6 >>> print x 11 >>> y = 5 >>> y += 6 >>> print y 11 Exercise 2.6) User input: 1. In this exercise, we will ask the user for her first and last name and date of birth and print them out formatted. Create a new file and call it userinput.py. Here is an example of what the program would do: Enter your first name: Anne Enter your last name: Willims Enter your date of birth: Month? July Day? 31 Year? 1987 Anne Williams was born on July 31, 1987 The text in italics is the what the user inputs. To print a string and a number in one line, you just need to separate the arguments with a comma. The print statement adds a space between the two arguments. print 'October', 20 Or you can convert the number to a string and then use the string operator: print 'October ' + str(20) OPTIONAL: Now, for something completely different... a discussion on how to print strings, most prettily... mo = October day = 20 year = 1987 print mo, day, year will have the output October 20 1987

Note that none of the commas are in this output! To do that you want something like this: print mo, day+,, year. The + sign concatenates/add two strings together, but can only be used on two strings. Using it on a number and a string will cause an error (because it is ambiguous as to what you want the program to do!). That s why it s a great idea to use raw input for this problem; if you use input you d have to convert the int to a string. We ll cover this more in-depth on Thursday, when we get to strings, but you may want to play with string concatenation operations now to get everything to look its prettiest. first = raw_input("enter your first name: ") last = raw_input("enter your last name: ") print "Enter your date of birth: " m = raw_input("month? ") d = raw_input("day? ") y = raw_input("year? ") print first+" "+last+" was born on "+m+" "+str(d)+", "+str(y) Exercise 2.7) Zeller s Algorithm- Optional but helpful Some problem sets will have optional exercises at the end. Feel free to work on these problems if you have time at the end of the assignment, but you certainly don t have to do them. However, you will get excellent practice in Python, and we will give you feedback on any optional work you turn in. Zeller s algorithm computes the day of the week on which a given date will fall (or fell). In this exercise, you will write a program to run Zeller s algorithm on a specific date. You will need to create a new file for this program, zellers.py. The program should use the algorithm outlined below to compute the day of the week on which the user s birthday fell in the year you were born and print the result to the screen. Start with the program in Exercise 2.6, but ask for the month as a number between 1-12 where March is 1 and February is 12. If born in Jan or Feb, enter previous year (see the notes below). In the end, print out the name of the user and the day of the week they were born. Zeller s algorithm is defined as follows:

Let A, B, C, D denote integer variables that have the following values: A = the month of the year, with March having the value 1, April the value 2, December the value 10, and January and February being counted as months 11 and 12 of the preceding year (in which case, subtract 1 from C) B = the day of the month (1, 2, 3,, 30, 31) C = the year of the century (e.g. C = 89 for the year 1989) D = the century (e.g. D = 19 for the year 1989) Note: if the month is January or February, then the preceding year is used for computation. This is because there was a period in history when March 1st, not January 1st, was the beginning of the year. Let W, X, Y, Z, R also denote integer variables. Compute their values in the following order using integer arithmetic: W = (13*A - 1) / 5 X = C / 4 Y = D / 4 Z = W + X + Y + B + C - 2*D R = the remainder when Z is divided by 7 The value of R is the day of the week, where 0 represents Sunday, 1 is Monday,..., 6 is Saturday. If the computed value of R is a negative number, add 7 to get a non negative number between 0 and 6. Print out R. You can check to be sure your code is working by looking at http://www.timeanddate.com/calendar/. Run some test cases- try today s date, your birth date, any other dates you like. Feel free to submit your zellers.py code if you wish, we ll take a look at it if you do. # ask the user of their first and last names first_name = raw_input('enter your first name: ') last_name = raw_input('enter your last name: ') # ask the user for their date of birth print 'Enter your date of birth: ' day = input('day? ') month = input('month? (Mar: 1,..., Jan: 11, Feb: 12) ') year = input('year? (If born in Jan or Feb, enter previous year)') # find the century and year century = year/100 year = year % 100

# apply zeller's algorithm W = (13 * month - 1) / 5 X = year / 4 Y = century / 4 Z = W + X + Y + day + year - 2 * century R = Z % 7 # print out the result print first_name, last_name, 'was born on day', R, 'of the week' print "(0 means Sunday, 1 means Monday,..., 6 means Saturday)"