Fundamentals of Programming (Python) Getting Started with Python Sina Sajadmanesh Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science
Outline 1. Software Development Paradigm 2. Defining the Problem 3. Creating a Design 4. Coding with Python 5. Testing the Program 2
Software Development 1. Define the Problem Objectives? Inputs? Outputs? Process? 2. Create a Design With algorithm & flowcharts 3. Code the Program Using a programming language (Python) 4. Test the Program Write appropriate tests & see if you get the right answers Use the Debugging system 3
Defining the Problem Celsius-Fahrenheit Conversion Objective The temperature is given in Celsius, user wants it expressed in degrees Fahrenheit. Input Temperature in Celsius Output Temperature in Fahrenheit Process Fahrenheit = 9 Celsius + 32 5 4
Creating a Design Algorithm a well-defined recipe for solving a problem Has a finite number of steps Completes in a finite amount of &me Often referred to as pseudocode Celsius-Fahrenheit Algorithm 1. Begin 2. C input from user 3. F C x 9/5 + 32 4. Output F 5. End 5
Creating a Design Flowchart A graphical model to represent an algorithm Steps are shown with boxes of different shapes The flow is specified by arrows Begin Input C F C x 9/5 + 32 Terminal Decision Process Input/ output Output F End 6
Coding with Python When you start Python, you will see something like: Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> The >>> is a Python prompt indicating that Python is ready for us to give it a command. These commands are called statements. 7
Coding with Python The first Program: Printing a line of text The print function sends a stream of text to the standard output >>> print("hello world") Hello world 8
Coding with Python The second program: Ask user s name The input function receives a stream of text from standard input >>> user = input( What s your name? ") What s your name? Sina >>> print("hello", user) Hello Sina 9
Variables in Python >>> user = input( What s your name? ") user is an example of a variable A variable is used to assign a name to a value so that we can refer to it later. Variables have names, called identifiers 10
Variables in Python A variable name (identifier) can be any one word that: Consists of letters, numbers, or _ Does not start with a number Is not a Python reserved word (keyword) and del from not while as elif global or with assert else if pass yield break except import print class exec in raise continue finally is return def for lambda try Python is case-sensitive: User is not the same as user 11
Data Types Python provides some basic or primitive data types Numeric int 25, -32, 0, 1024 float 1.5, 0.0025, -80.635 complex Boolean True False String 1+3j, -2.5+j, 12j this is a string, 25, False 12
Arithmetic Operations Symbol Meaning Precedence + Addition Low - Subtraction Low * Multiplication Medium / Division Medium // Floor Division Medium % Reminder (mod) Medium ** Exponentiation (Power) High 13
A Complete Program Celsius-Fahrenheit Python Program >>> c = input("enter temperature in Celsius: ") >>> f = c * 9/5 + 32 >>> print("temperature in Fahrenheit:", f) 14
A Complete Program Celsius-Fahrenheit Python Program >>> c = input("enter temperature in Celsius: ") >>> f = c * 9/5 + 32 >>> print("temperature in Fahrenheit:", f) Any Problems? The input function returns a string Needs to be converted into float >>> c = float(c) 15
Type Conversion Data type converter functions To Integer >>> x = int("25") >>> x = int(34.287) >>> x = int(true) To Float >>> x = float("34.287") >>> x = float(12) >>> x = float(false) To String >>> x = str(34.287) >>> x = str(12) >>> x = str(true) To Boolean >>> x = bool("text") >>> x = bool(0) >>> x = bool(34.287) 16
Put All Together Celsius-Fahrenheit Python Program >>> c = input("enter temperature in Celsius: ") >>> f = float(c) * 9/5 + 32 >>> print("temperature in Fahrenheit:", f) Want to save your program? Let s switch to script mode! 17
Python Running Modes Interactive Mode Write code directly in interpreter command line shell Gives immediate feedback for each statement Best for playing around with your code Script Mode Write code into a file and save it with.py extension Give the file as input to the interpreter Best for running the program multiple times 18
Test the Program Programming often leads to Error! Programming errors are called bugs Tracking the bugs and correcting them is called debugging Different error types Syntax error Runtime error Semantic error 19
Programming Errors Syntax Error Caused by the violation of rules and structure of Python language Found when the code is being interpreted to machine language. Pretty easy to catch Example: choosing a keyword as a name for a variable >>> lambda = 1.5 File "<stdin>", line 1 lambda = 1.5 ^ SyntaxError: invalid syntax 20
Programming Errors Runtime Error (Exception) Caused due to many reasons, such as hardware failure, access violation, memory errors, Found while the code is running Moderate to catch (need coding) Example: using operators with incorrect operand types >>> x = "text" >>> x / 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for /: 'str' and 'int' 21
Programming Errors Semantic Error Caused due to incorrect coding or design No error messages are generated at all! Tricky to catch (need code inspection) Example: incorrect use of operator >>> c = input("enter temperature in Celsius: ") >>> f = float(c) * 9//5 + 32 >>> print("temperature in Fahrenheit:", f) 22
Experimental Debugging An important skill Frustrating but challenging Sounds like detective work Follow the clues to find the source of error Get help from a debugger IDEs usually come with a debugger Helps to find bugs using debugging tools such as breakpoints, profilers, etc. 23