Lecture 1: Introduction to Python Programming PDF
Document Details
Uploaded by ComfortingNovaculite2539
University of Ghana
Tags
Summary
This document is a lecture on Introduction to Python Programming. It covers fundamental concepts of programming, algorithms and introduces Python as a language. The document also provides examples, including calculating simple operations.
Full Transcript
Lecture 1 Introduction to Python Programing Chapter Objectives By the end of this chapter, you should be able to: 1. Describe the basic features of an algorithm 2. Understand what a computer program is 3. Understand the role of Variables and perform variable assignment in Python...
Lecture 1 Introduction to Python Programing Chapter Objectives By the end of this chapter, you should be able to: 1. Describe the basic features of an algorithm 2. Understand what a computer program is 3. Understand the role of Variables and perform variable assignment in Python 4. Code and run simple Python programs Algorithms and Computer Programming Two fundamental ideas to note: Algorithms Computer Programming Algorithms An algorithm is simply a set of steps used to complete a specific task. They're the building blocks for programming They allow computers to make decisions. Algorithms Example Algorithm ▪ Steps for subtracting two numbers: ▪ Step 1: Write down the numbers, larger above smaller one, digits column-aligned from right ▪ Step 2: Start with the rightmost column of digits and work your way left through the various columns ▪ Step 3: Write down the difference between the digits in the current column of digits, borrowing a 1 from the top number’s next column to the left if necessary ▪ Step 4: If there is no next column to the left, stop ▪ Otherwise, move to the next column to the left; go to Step 3 ▪ The computing agent is a human being ▪ The sequence of steps that describes each of these computational processes is called an algorithm Algorithms ▪ Features of an algorithm: ▪ Consists of a finite number of instructions ▪ Each individual instruction is well defined ▪ Action described by the instruction can be performed effectively or be executed by a computing agent ▪ Describes a process that eventually halts after arriving at a solution to a problem ▪ Solves a general class of problems ▪ An algorithm is therefore like a blueprint (a guide for making something). Computer Programming ▪ In carrying out the instructions of an algorithm, a computing agent manipulates information ▪ Starts with input ▪ Transforms information according to well-defined rules ▪ Produces output ▪ The algorithms that describe information processing can also be represented as computer program. What is Computer Programming? ▪ Why perform routine tasks or thinking whiles a computer can do so for you faster and cheaper? ▪ If you own a store, and have to give someone a change, even though you know the process (algorithm) for determining the change, why struggle always to do this using your head when you could instruct a computer to perform the algorithm to tell you the change? ▪ The word instruct is very important since computers aren’t ‘bright’, and have to be instructed to perform the tasks we want. ▪ This is Programming! Computer Programming Language ▪ Humans need a way to communicate with Computers. ▪ The language that helps us to communicate with computers (i.e. allows us to write programs) is called a programming language. What is Python Programming Language? - Python is a high-level programming computer language that provides instructions to teach the computer how to perform a task. - Python syntax which reflects everyday language, which makes them easier to learn and use. - Python language also offer programmers development tools such as libraries and built-in functions. - Python offers efficient high-level data structures and an object-oriented programming style that is simple yet effective. What is Python Programming Language? - Python is a computer programming language designed to represent the needs of a problem and mimics natural language or mathematical notation. - Developed by Guido van Rossum. - Is a free and open-source language. - Thus, you can read, modify, and distribute the source code of Python scripts for free. - Works as an interpreter. - when you run a Python program, an interpreter will read it line by line, as opposed to compiled languages like C or C++, where the compiler first compiles the program before running it. Why Python? What is an IDE Jupyter Notebook PyCharm Spyder Canopy VIM ATOM Benefits of Using Python Programming - Easy to Read, Learn and Write. - Its syntax is similar to English and therefore enhances the code's readability and understanding. - Needs lesser lines of code to execute the same task compared to other languages. - Improved Productivity - Python's simplicity helps developers to focus on the task at hand. - Less time learning syntax or behavior of the programming language. - Python developers write less code and produce more. - Allocates data type to variables automatically. - The developer is not required to declare variables or their data types. Benefits of Using Python Programming - Has popular libraries such as: ▪ SciPy: for scientific and technical computing. ▪ Keras: for Artificial Neural Networks. ▪ Pandas: for manipulation and analysis of data. ▪ TensorFlow: for Machine Learning tasks. ▪ NumPy: for complex mathematical functions and computation. ▪ Scikit: for working with various Machine Learning Models. Applications of Python Programming Language 1. Web Development 2. Data Analysis and Visualization 3. Machine Learning and Artificial Intelligence (AI) 4. Game Development 5. Software Development 6. Web Scraping Applications 7. Embedded Applications 8. CAD Applications 9. Audio and Video Applications 10. Text Processing Already have Python Installed? ▪ Many PCs and Macs will have Python already installed. ▪ To check if you have python installed on a Windows PC, either: - Search in the start bar for Python - Or in the search bar, type cmd and click on “Command Prompt” - Next, type: “Python” to see the version you are running. ▪ If you find that you do not have Python installed on your computer, then you can download it for free from the following website: https://www.python.org/ Installing Python The setup process and installation of Python can be done in a number of methods: 1. Downloading official Python distributions from Python.org, 2. Installing through a package manager (Anaconda), 3. Installing specialized versions for numerical computation, IoT, and embedded systems. Installing Official Python Go to https://www.python.org/ Step 1: ▪ Select version of Python to download the Full Installer, and proceed to installation. ▪ Download either 32-bit (labeled x86) or 64-bit (labeled x86–64) version for your PC. ▪ The Latest Python 3 Release is Python 3.10.11 Step 2: Download Python Executable Installer and install it. Step 3: Wait for it to complete the installation process. Installing Official Python Step 4: Verify the version of Python installed. ▪ To see if Python has been installed successfully on your computer: – Open the Cmd prompt in your system → Run “ Python -V” Step 5: Run Python. ▪ Congratulations! Python has been installed in your system. ▪ Now go to: ▪ Windows Search → Type IDLE → Open it→ Now run your First Python code. Installing Official Python Step 6: Verify whether PIP was installed. ▪ PIP is a robust software package management system for Python. ▪ PIP is useful, especially when working in virtual environments. ▪ The PIP doesn't come pre-installed with Python's older versions. To verify if PIP is installed: ▪ Type the command pip –version in cmd and hit Enter: ▪ If PIP is installed, the output will show the version number of the PIP. ▪ If not installed, the output will be “'pip' is not a valid internal or external command, programme, or batch file”. Installing Official Python Install pip for Python 3: Type the following to install pip: sudo apt install python3-pip Then verify if it is installed correctly: pip3 --version Installing Python Using Anaconda Navigator ▪ Anaconda Navigator is provides a desktop GUI interface. ▪ It simplifies the process of launching programs and managing packages and environments without the need for command-line tools (CLI). ▪ Python is listed under the package Jupyter Notebook Steps to download Jupyter Notebook Step 1: Go to the official Anaconda website https://www.anaconda.com/download Installing Python Using Anaconda Navigator Step 2: From the menu bar, click on Products > Individual Edition. Installing Python Using Anaconda Navigator Step 3: Click on the Download button on the page. Installing Python Using Anaconda Navigator Step 4: To get additional installers, select your OS and download the package. Installing Python Using Anaconda Navigator Step 5: Open it after downloading the installer. Installing Python Using Anaconda Navigator Step 6: Initiate the installation process on your system. Installing Python Using Anaconda Navigator Step 7: ▪ Congratulations! Anaconda has been successfully installed on your system. Compiling and Running Python Code in Jupyter Example Step 1: Open Jupyter. Go to: New→Notebook→Select Step 2: Type the following python code: print("Hello, World!") Step 3: Save the file as helloworld.ipynb Step 4a: To run the python code, click on the arrow Step 4b: Alternatively, press on ‘Select’ and hit the ‘Enter’ button You should see the output: “Hello, World!” Python Keywords ▪ Each programming language has a few reserved words, known as keywords, that have particular meanings and purposes. ▪ In Python keywords are reserved words that cannot be used for anything else. Note: These reserved keywords in Python are different from built-in functions and data types in Python. Python Keywords Python Keywords List The latest version of Python comprises 35 keywords. Below is a complete list of Python keywords for your reference. Assert; With; else; import; pass; None; break; except; in; raise; True; class; finally; is; return; and; False; del ; elif; try; as; def; from; nonlocal; while; lambda; await; global; not; for; async; continue; If; or; yield Input, Processing, and Output The print function ▪ Programs usually accept inputs from a source, process them, and output results to a destination. ▪ In Python (Jupyter environment) ▪ Inputs are Python expressions or statements. ▪ Outputs are the results displayed in the line immediately after. ▪ The output of a Python expression is obtained with the print() function: print () Example: print("Hi there") Output: Hi there For Jupyter only: One can also obtain the output by just typing the variable. Note that this will show the output for the last typed variable Input, Processing, and Output The print function ▪ The print function can return more than one items. To do this, separate each time with a comma. Example: x=2; y=-4; z= x*y print(x,y,z) Output: 2 -4 -8 Input, Processing, and Output The input function ▪ The ‘input’ function is used to receive an expression/statement from a user. ▪ Note: You need to hit only the ‘Enter’ key after supplying the requested input. Example The following example prompts a user to input string and saves it for further processing: name = input("Enter your name: ") Enter your name: Ken Lambert name 'Ken Lambert' print(name) Output: Ken Lambert Input, Processing, and Output ▪ The parameter to the input() function is a prompt string that prints out a prompt to the user to type something. ▪ Whatever you enter as input, the input function converts it into a string. ▪ If you enter an integer value still input() function converts it into a string. ▪ Therefore, strings that represent numbers must be converted from strings to appropriate number types. Example: Input two integers and displays their sum: first = int(input("Enter the first number: ")) Enter the first number: 23 second = int(input("Enter the second number: ")) Enter the second number: 44 print("The sum is", first + second) Output:The sum is 67 Knowledge Check 1. What does the input function do? 2. What does the print function do? Knowledge Check Answers 1. What does the input function do? Answer: The input function builds a string from the user’s keystrokes and returns it to the program. 2. What does the print function do? Answer: The print function evaluates expressions and displays them, separated by one space, in the console window. Python Statement What is a Statement in Python? ▪ In Python, a statement is a code that the interpreter runs or the instructions that the interpreter follows. ▪ A statement like y = 10 sends the value 10 to the variable y. ▪ In Python, statements come in a variety of forms, including while, if, and so on. Python Statement Multi-line Statement ▪ The continuation character / in Python is used to prolong a statement across multiple lines. ▪ As a result, the statement is now a multi-line statement. ▪ Parentheses (), braces {}, or square brackets [ ] can also be used to define a multi-line statement. Python Statement Multi-line Statement Multi-line Statement ▪ Example using Continuation ▪ Example using braces {} Character (\) for summing x = [12+43+49+ many numbers 33+61+80+ x = 1+2+3+\ 22+16+49] 2+3+1+\ 3+9+1 ▪ Example using parentheses () ▪ Example using square brackets [ ] x = (11+12+13+ x = [12+43+49+ 16+18+32+ 33+61+80+ 73+48+50) 22+16+49] Python Statement Multi-line Statement ▪ A semicolon ; can also be used to specify numerous statements on a single line. Example using semicolon (;) x = 4; y= 8; z = 7 Indentation in Python Programming ▪ Indentation refers to the spaces at the beginning of a code line. ▪ Indentation is an important and fundamental aspect of Python programming. ▪ In Python, indentation is used to indicate a block of code, and thus very important. ▪ Indentation in other languages, such as C, C++, Java, etc., is for the sake of readability. Indentation in Python Programming ▪ In Python, indentation: ▪ enable statements to be in the same indentation level, i.e., statements with an equal number of whitespaces before them, as a single piece of block. ▪ serves as a means of signaling to the Python interpreter that a group of statements belong to a particular block of code. ▪ Thus, indentation must be used carefully in python, especially at where it is placed. ▪ In other words, Python indentation is mandatory and an essential practice that must be followed while writing code. Indentation in Python Programming Python Indentation Examples 1. Statement: Code block 1 statement begins 2. if condition: Code block 1 condition continues 3. if condition: Code block 2 statement begins 4. Statement —---> Code block 3 statement begins 5. else: Code block 2 statement cont. 6. Statement: Code block 3 continues 7. Statement: Code block 1 continues ▪ Statements in line number 1, 2, and 7 belong to code block 1 - zero level indentation. ▪ Statements 3 and 5 are indented one step ahead and form another block - first level indentation. ▪ Statements 4 and 6 form a code block number 3 - second level indentation. Indentation in Python Programming Python Indentation Examples 1. Statement: Code block 1 statement begins 2. if condition: Code block 1 condition continues 3. if condition: Code block 2 statement begins 4. Statement —---> Code block 3 stmt begins 5. else: Code block 2 statement cont. 6. Statement: Code block 3 continues 7. Statement: Code block 1 continues Interpretating the execution of the order of the above statements: ▪ Code execution begins at line 1 followed by checking the if condition at line 2; ▪ If the evaluation of the condition returns true, then control goes inside of the if block. ▪ If line 3 returns true, the flow enters into executing the statement in line 4. ▪ If the evaluation of line 3 returns false, then the control goes into the execution of statement 6. ▪ If the second line itself returns false, then statement 7 would have been executed. ▪ This is how we indent the python code for successful execution. Python Indentation Examples Example 1: Checking if a number is odd, even or zero. Program: x= 10; If x != 0: if x%2 == 0: print(“The number is even”) else: print(“The number is odd”) else: print(“The number is zero, i.e., it is neither even nor odd”) Python Indentation Examples Example 1: Checking if a number is odd, even or zero. Program: x= 10; if x != 0: if x%2 == 0: print(“The number is even”) else: print(“The number is odd”) else: print(“The number is zero, i.e., it is neither even nor odd”) Interpretation: ▪ Since the variable x is not zero, it satisfies the first condition check and enters the first code block. ▪ For the next condition check, x should either be even or odd. ▪ According to the example, x is even, so the second condition is also satisfied ▪ Now it’ll enter the second code block. As both the conditions are true, it will print, ”The number is even”. ▪ In this program, the statements that are inside the bodies of if and else are indented. Python Indentation Examples Example 2: While condition Program: i=3 while(i 2: print("Five is greater than two!") Output: SyntaxError: expected an indented block after 'if' statement on line 1 ▪ The correct way of writing the program is shown below: Correct program: if 5 > 2: print("Five is greater than two!") Correct Output: Five is greater than two! Rules of Indentation in Python ▪ Indentation cannot be used on the very first line of the Python code. ▪ The standard indentation level in Python is four spaces. This indicates that each level of indentation should be of four spaces. ▪ Do not mix tabs and spaces when indenting code in Python. ▪ It is recommended to use only spaces as this ensures consistency across different text editors and IDEs. ▪ To avoid confusion, always use spaces on all the platforms. ▪ Consistency is important while indenting code in Python. All the lines that come under a code block should be indented at the same level. Rules of Indentation in Python ▪ Indentation is an important part of the Python programming language, however, it should be used in moderation and not be overused. ▪ Always avoid extra indentation, as it will make the code harder to read and understand. ▪ Indentation is not optional. It is mandatory in Python, not adhering to it can cause errors. Disadvantages of Python Indentation 1. Inconsistency can lead to errors ▪ If different parts of the code block are indented differently, it can lead to confusion and errors. This will cause a huge problem, especially when working on a large project with a complex code base. 2. Requires Strict adherence ▪ Developers cannot move forward if they don’t follow indentation religiously. It is a strict requirement of the Python programming language. 3. Extra effort ▪ Developers might take indentation as an extra effort in order to maintain consistency throughout the project. 4. Does not improve performance ▪ You might believe that since we have discussed the importance of indentation, it could also have an impact on performance. However, an indentation in Python has no role to play when it comes to the performance of the code. Comments in Python ▪ A comment is added to a Python code using the # symbol. Its role is to provide further information. ▪ Comments aid in the user's comprehension of the code. ▪ Comments can also be used to explain Python code. ▪ Comments can be used to make the code more readable. ▪ Comments can be used to prevent execution when testing code. ▪ Any programming language's comments are ignored and are not compiled or understood. ▪ Assumptions are added via comments. They explain how the application works for the user. This saves the user time. Comments in Python ▪ Consider the following examples, in which each line of code has a remark to describe how the program works: Example 1 Example 3 Program a = 1; b= 3 #Declaring two integers #This is a comment c = a + b #adding two integers print("Hello, World!") print(c) #displaying the result Output Hello, World! Output 4 Example 2 print("Hello, World!") #This is a comment Output Hello, World! Multi-Line comments The hash character (#) at the beginning of each line can be used to add multi-line comments to several lines. Try the following: Example 1 #This program calculates #sum of two integers #and displays the result Example 2 #This is a comment #written in #more than just one line print("Hello, World!") Multi-Line comments ▪ Triple quotes ” ” ” can also be used to create a multi-line comment. ▪ Triple quotes are commonly used to denote multi-line strings, but they can also be used to denote multi-line comments. Example Example """ """Inserting This is a comment Multi line written in more than just one line Comments to """ our program using print("Hello, World!") triple quotes""" Output Hello, World! Detecting and Correcting Syntax Errors ▪ Programmers inevitably make typographical errors when editing programs. This is called syntax errors. ▪ Syntax: rules for forming sentences in a language. Example Program: length = int(input("Enter the length: ")) Enter the length: 44 print(lenth) Output Traceback (most recent call last): File "", line 1, in NameError: name 'lenth' is not defined Detecting and Correcting Syntax Errors Example ▪ The statement below attempts to print the value of the correctly spelled variable, but forgets to put it in a string. Program print(length) NameError: name ‘boy’ is not defined Example ▪ programmer attempts to add two numbers, but forgets to include the second one: Program 3+ SyntaxError: invalid syntax Python Variables ▪ Variables are containers for storing data values. ▪ No need to define variables or their types before utilizing them. ▪ A variable is said to be created when it is assigned a value. ▪ Python has no command for declaring a variable. Example Example x=5 x=4 # x is of type int y = "John" x = "Sally" # x is now of type str print(x) print(x) print(y) Output Output Sally 5 John Python Variables Casting Data Type (More later) ▪ If you want to specify the data type of ▪ You can get the data type of a a variable, this can be done with variable with the type() function. casting. Example Example x=5 x = str(3) y = "John" y = int(3) print(type(x)) z = float(3) print(type(y)) print(x) print(y) Output print(z) Output 3 3 3.0 Python Variables Single or Double Quotes? Case-Sensitive ▪ String variables can be declared either ▪ Variable names are case-sensitive. by using single or double quotes. Example Example a=4 x = "John" A = "Sally" print(x) print(a) #double quotes are the same as single print(A) quotes: Output x = 'John' 4 print(x) Sally Output john Variable Names ▪ A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for defining Python variables: ▪ A variable name must start with a letter or the underscore character ▪ A variable name cannot start with a number ▪ A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) ▪ Variable names are case-sensitive (name, Name, and NAME are three different variables) ▪ A variable name cannot be any of the Python keywords. Variable Names Example: 1x wrong variable #name wrong variable __x wrong variable.x wrong variable X. wrong variable X1 right variable X_ right variable _x right variable Variable Names Legal variable names: Illegal variable names: Multi Words Variable Names Example Program Example Camel Case myvar = "John" 2myvar = "John" ▪ Each word, except the first, my_var = "John" starts with a capital letter: _my_var = "John" my-var = "John" Example myVar = "John" my var = "John" MYVAR = "John" myVariableName = "John" myvar2 = "John" Output print(myvar) Pascal Case print(my_var) #This example will Each word starts with a capital print(_my_var) produce an error in the letter: print(myVar) result Example print(MYVAR) MyVariableName = "John" print(myvar2) Output john Snake Case john Each word is separated by an John underscore character: John Example John my_variable_name = "John" john Many Values to Multiple Variables ▪ Python allows you to assign values to multiple variables in one line: Example 1 Example 2 x, y, z = "Orange", "Banana", "Cherry" x, y, z = "Orange", "Banana", "Cherry" print(x) x = y = z = "Orange" print(y) print(x) print(z) print(y) Output print(z) Orange Output Banana Orange Cherry Orange Orange Many Values to Multiple Variables Unpack a Collection ▪ If you have a collection of values in a list, tuple etc. Python allows you to extract the values into variables. This is called unpacking. Example fruits = ["apple", "banana", "cherry"] x, y, z = fruits print(x) print(y) print(z) Output apple banana cherry Output Variables ▪ The Python print() function is often ▪ Multiple variables can be outputted with used to output variables. the print() function, by separating with a comma: Example Example x = "Python is awesome" x = "Python" print(x) y = "is" Output z = "awesome" Python is awesome print(x, y, z) Output Python is awesome Output Variables ▪ You can also use the + operator to ▪ For numbers, the + character works output multiple variables: as a mathematical operator. Example Example x = "Python " x=5 y = "is " y = 10 z = "awesome" print(x + y) print(x + y + z) Output Output 15 Python is awesome Note: The space character after "Python " and "is ", without them the result would be "Pythonisawesome". Output Variables ▪ The print() function will give an error if you combine a string and a number with the + operator. Example x=5 y = "John" print(x + y) Output TypeError: unsupported operand type(s) for +: 'int' and 'str‘ Output Variables ▪ One can output multiple variables in the print() function by separating the variables with commas. ▪ This works even for variables of different data types: Example x=5 y = "John" print(x, y) Output 5 John Global Variables ▪ Variables created outside of a function (as in all of the examples so far) are known as global variables. ▪ Global variables can be used by everyone, both inside of functions and outside. The Global Keyword ▪ When you create a variable inside a function, that variable is local, and can only be used inside that function. ▪ To create a global variable inside a function, you can use the global keyword. Example def myfunc(): global x x = "fantastic" myfunc() print("Python is " + x)