Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
Advertisements

What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
CS0007: Introduction to Computer Programming Console Output, Variables, Literals, and Introduction to Type.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Lecture 2 Introduction to C Programming
Introduction to C Programming
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Python November 14, Unit 7. Python Hello world, in class.
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
CS31: Introduction to Computer Science I Discussion 1A 4/2/2010 Sungwon Yang
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
Introduction to Python
Python Crash Course by Monica Sweat. Python Perspective is strongly typed, interpreted language is used to define scripts (Don't even need to define a.
 2002 Prentice Hall. All rights reserved. 1 Chapter 2 – Introduction to Python Programming Outline 2.1 Introduction 2.2 First Program in Python: Printing.
String Escape Sequences
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
CSC 9010: Natural Language Processing
Python.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
Line Continuation, Output Formatting, and Decision Structures CS303E: Elements of Computers and Programming.
Introduction to Python
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Sales person receive RM200/week plus 9% of their gross sales for that week. Write an algorithms to calculate the sales person’s earning from the input.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Input, Output, and Processing
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 5 – Dental Payment Application: Introducing.
Computer Science 101 Introduction to Programming.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.
With Python.  One of the most useful abilities of programming is the ability to manipulate files.  Python’s operations for file management are relatively.
CSC141 Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture - 6.
Chapter 2 Variables.
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
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.
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use the.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
Python Let’s get started!.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP Basics.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Midterm Exam Topics (Prof. Chang's section) CMSC 201.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
Python Basics  Values, Types, Variables, Expressions  Assignments  I/O  Control Structures.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.
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.
String and Lists Dr. José M. Reyes Álamo.
Basic concepts of C++ Presented by Prof. Satyajit De
Chapter 1.2 Introduction to C++ Programming
Chapter 2 Variables.
Introduction to Python
Line Continuation, Output Formatting, and Decision Structures
The Selection Structure
Variables, Expressions, and IO
Introduction to Scripting
Line Continuation, Output Formatting, and Decision Structures
Introduction to C++ Programming
T. Jumana Abu Shmais – AOU - Riyadh
String and Lists Dr. José M. Reyes Álamo.
CISC101 Reminders All assignments are now posted.
Unit 3: Variables in Java
Chapter 2 Variables.
Introduction to C Programming
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

Introduction to Python Lecture 1

CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language There are no declarations of variables Variables take a retain the type of the data assigned to it Whitespace is used as delimiters no main method

CS 484 – Artificial Intelligence3 First Statement Hello World >>> print 'Hello World!' Usually double and single quotes can be used interchangeably A string in double quotes cannot contain a " A string in single quotes cannot contain a ' Put strings in """ if you need both or newlines Try: outputting Hello World on two lines

CS 484 – Artificial Intelligence4 Python Calculator You can print the results of expressions (variables and functions) >>> print >>> print ((8 % 3) ** (7 / 3)) * ( 5 – 1) Integer vs. Floating point division >>> print 15 / 4 >>> print 15 / 4.0

CS 484 – Artificial Intelligence5 Using Formatted Strings Combining strings and numbers >>> print 'The total is ', Combining strings with many numbers >>> print "The sum of %d and %d is %d" % (7, 18, (7 + 18)) Just like printf in C, other example codes %s – String %x – Hexadecimal %0.2f – A real number with two figures following the decimal point %4d – Leading spaces to pad the number to at least 4 digits %04d – Leading 0's to pad the number to at least 4 digits

CS 484 – Artificial Intelligence6 Other important features Comments begin with a # >>> print # This should print 12 Making use of libraries or other functions and methods you have written >>> import sys >>> sys.exit() >>> from random import * >>> from pyrobot.brain import Brain

CS 484 – Artificial Intelligence7 Python Error Messages >>> print 'fred' + 7 Traceback (innermost last): File " ", line 1, in ? TypeError: cannot concatenate 'str' and 'int' objects Errors only reported when line is encountered Python's error messages are often wrong Inspect the line of the error and a few above

CS 484 – Artificial Intelligence8 Variables Variables are not declared Can change types with new assignments >>> q = 7 # q is currently a number >>> print q >>> q = 'Seven' # q is reassign to a string >>> print q

CS 484 – Artificial Intelligence9 String Operators + operator: String Concatenation >>> print 'Again' + ' and again' * operator: String repetition >>> print 'repeat ' * 3 Combining operators >>> print 'Again' + (' and again' * 3) String methods are documented here

CS 484 – Artificial Intelligence10 Boolean Operators C/Java Operator Python Operator A && BA and B A || BA or B A == B A != B A <> B !Anot A Relational operators are all the same 5 <= 6 Boolean values True (case sensitive) False Try print ((5 <= 6) == true)

CS 484 – Artificial Intelligence11 Lists A sequence of items Has the ability to grow (unlike array) Use indexes to access elements (array notation) examples aList = [] another = [1,2,3] You can print an entire list or an element print another print another[0] index -1 accesses the end of a list

CS 484 – Artificial Intelligence12 List operation append method to add elements (don't have to be the same type) aList.append(42) aList.append(another) del removes elements del aList[0] # removes 42 Concatenate lists with + Add multiple elements with * zerolist = [0] * 5 Multiple assignments point = [1,2] x, y = point More operations can be found at

CS 484 – Artificial Intelligence13 Control Statements Conditionals if : elif : else: Example: name = "Jane" if "a" in name: print "There is an 'a'" else: print "There is not an 'a'" There is no switch statement

CS 484 – Artificial Intelligence14 Control Statements Loops while : for in range(i,j): # up to but # not including j Example: name = "Jane" for c in name: print c no do while loops

CS 484 – Artificial Intelligence15 Interacting with user Obtaining data from a user Use function raw_input for strings or input for numbers Example name = raw_input("What's your name?") Command Line arguments Example: import sys for item in sys.argv: print item Remember sys.argv[0] is the program name

CS 484 – Artificial Intelligence16 Defining New Functions Syntax def ( ): Remember there is not type checking Function may or may not return something Example def times(n): for i in range(1,13): print "%2d x %2d = %3d" % (i, n, i*n)

CS 484 – Artificial Intelligence17 Classes Begin with header line class : Constructor and methods tabbed over once first argument is "self" Constructor def __init__(self, ): Methods def (self, ): Class variables self.

CS 484 – Artificial Intelligence18 Example Class class Message: def __init__(self, aString): self.text = aString def printIt(self): print self.text def getMessage(self): return self.text Use: from Message import * msg = Message("hi") msg.printIt() Use: from Message import * msg = Message("hi") msg.printIt()

CS 484 – Artificial Intelligence19 Using Files Function open opens a file in the mode specified by the argument = open(, ) file name is a string with path and name of the file Possible modes "r" to read "w" to write "rb" to read a binary file "wb" to write a binary file Example input = open("myFile.txt", "r") output = open("copy.txt", "w") for line in input.readlines(): output.write(line) input.close() output.close()

CS 484 – Artificial Intelligence20 Sample Program # file: createDict.py # by: Dawn Lawrie # date: September 8, 2005 # Reads the standard dictionary and creates a simpler # dictionary that only includes words in all lowercase letters # without aprostrophes # Opens the input and output files input = open("/usr/share/dict/american-english", "r") output = open("simpleDict", "w") # Reads each lines of the dictionary for line in input.readlines(): # Assumes that the word should not be in the simpler # dictionary good = False

CS 484 – Artificial Intelligence21 Sample Program # Accepts the word if it contains at least one lowercase # letter lowercase = "abcdefghijklmnopqrstuvwxyz" for c in lowercase: if not good and c in line: good = True # Rejects the word if there is an apostrophe if "'" in line: good = False # Rejects the word if it contains a uppercase letter if good: caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for c in caps: if good and c in line: good = False

CS 484 – Artificial Intelligence22 Sample Program con't # Outputs the word if it is acceptable if good: output.write(line)

CS 484 – Artificial Intelligence23 Using String Methods # file: createDict2.py # by: Dawn Lawrie # date: September 8, 2005 … code the opens files has been removed # Reads each lines of the dictionary for line in input.readlines(): # Removes all leading and trailing whitespace word = line.strip() # Outputs the word if all the characters are alphabetic # and they are all lowercase if word.isalpha() and word.islower(): output.write(word + "\n")

CS 484 – Artificial Intelligence24 Pitfalls My common mistakes Forgetting ":" in a condition or loop especially after else Emacs helps because it won't tab over Forgetting "self" before class variables Without it python creates a new variable Forgetting the return statement This turned up as a type mismatch when I tried to use the results of the function which I had stored in another variable (Very Confusing)

CS 484 – Artificial Intelligence25 Lab Exercise Write a program in python that plays hangman