MODULE 5 Integrative Programming & Technology PYTHON BASIC BSIT 3A Prepared by: REYNEL M. MARGELINO Faculty Python Basic Lesson Objectives: At the end of this lesson, you will be able to: • • • • • • • Install python software. Understand the benefits of learning python Learn Python Basic Syntax Learn Python Variable Types Learn Python Operators Learn Python Input () & Selection Function Learn Python iteration (looping) PYTHON OVERVIEW WHAT IS PYTHON? • Is a general-purpose interpreted, interactive, object-oriented, and highlevel programming language. • It was created by Guido van Rossum during 1985- 1990. • Source code is also available under the General Public License (GPL). WHY TO LEARN PYTHON? • A high-level, interpreted, interactive and object-oriented scripting language. • Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages KEY ADVANTAGES OF LEARNING PYTHON • Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is similar to PERL and PHP. • Python is Interactive – You can actually sit at a Python prompt and interact with the interpreter directly to write your programs. • Python is Object-Oriented − Python supports Object-Oriented style or technique of programming that encapsulates code within objects. • Python is a Beginner's Language − Python is a great language for the beginner-level programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games. PYTHON APPLICATION 1. 2. 3. 4. 5. 6. GUI based desktop applications (Games, Scientific Applications) Web frameworks and applications Enterprise and Business applications Operating Systems Language Development Prototyping ORGANIZATIONS USING PYTHON 1. 2. 3. 4. 5. 6. 7. 8. 9. Google (Components of Google spider and Search Engine) Yahoo(Maps) YouTube Mozilla Dropbox Microsoft Cisco Spotify Quora PYTHON-ENVIRONMENT SETUP Python is available on a wide variety of platforms including Linux and Mac OS X. Let's understand how to set up our Python environment. INSTALLING PYTHON Python distribution is available for a wide variety of platforms. You need to download only the binary code applicable for your platform and install Python. The most up-to-date and current source code, binaries, documentation, news, etc., is available on the official website of Python https://www.python.org/ You can download Python documentation from https://www.python.org/doc/. The documentation is available in HTML, PDF, and PostScript formats. UNIX AND LINUX INSTALLATION Here are the simple steps to install Python on Unix/Linux machine. • Open a Web browser and go to https://www.python.org/downloads/. • Follow the link to download zipped source code available for Unix/Linux. • Download and extract files. • Editing the Modules/Setup file if you want to customize some options. • run ./configure script • make • make install This installs Python at standard location /usr/local/bin and at /usr/local/lib/pythonXX where XX is the version of Python. its libraries WINDOWS INSTALLATION Here are the steps to install Python on Windows machine. • Open a Web browser and go to https://www.python.org/downloads/. • Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to install. • To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save the installer file to your local machine and then run it to find out if your machine supports MSI. • Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is finished, and you are done. MACINTOSH INSTALLATION Recent Macs come with Python installed, but it may be several years out of date. See http://www.python.org/download/mac/ for instructions on getting the current version along with extra tools to support development on the Mac. For older Mac OS's before Mac OS X 10.3 (released in 2003), MacPython is available. Jack Jansen maintains it and you can have full access to the entire documentation at his website − http://www.cwi.nl/~jack/macpython.html. You can find complete installation details for Mac OS installation. PYTHON-BASIC SYNTAX Variables and Data Structures • In other programming languages like C, C++ and Java, you will need to declare the type of variables but in Python you don’t need to do that. Just type in the variable and when values will be given to it, then it will automatically know whether the value given would be a int, float or char or even a String. PYTHON-VARIABLE TYPES • • • Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables. Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables. ASSIGNING VALUES TO VARIABLES • Example counter = 100 # An integer assignment miles = 1000.0 # A floating point name = "John" # A string MULTIPLE ASSIGNMENT • Python allows you to assign a single value to several variables simultaneously Example: A=B=C=1 STANDARD DATA TYPES 1. Numbers 2. String 3. List 4. Tuple 5. Dictionary NUMBERS PYTHON PROGRAM TO DECLARE VARIABLES a. myNumber = 3 print(myNumber) b. myNumber2 = 4.5 print(myNumber2) c. myNumber ="helloworld" print(myNumber) PYTHON OPERATORS Operators are used to perform operations on variables and values. Python divides the operators in the following groups: • • • • • • • Arithmetic operators Assignment operators Comparison operators Logical operators Identity operators Membership operators Bitwise operators PYTHON ARITHMETIC OPERATORS Arithmetic operators are used with numeric values to perform common mathematical operations: PYTHON ASSIGNMENT OPERATORS Assignment operators are used to assign values to variables: PYTHON COMPARISON OPERATORS Comparison operators are used to compare two values: PYTHON LOGICAL OPERATORS Logical operators are used to combine conditional statements: PYTHON IDENTITY OPERATORS Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location: PYTHON MEMBERSHIP OPERATORS Membership operators are used to test if a sequence is presented in an object: PYTHON BITWISE OPERATORS Bitwise operators are used to compare (binary) numbers: PYTHON INPUT () FUNCTION The input() function allows user input. Example x = input('Enter your name:') print('Hello, ' + x) OUTPUT Create a program using python to get the product of two numbers 1. Open your Python IDLE 2. Click File new file and save it as product .py 3. Copy the code below num1 = int(input("Enter num1: ")) num2 = int(input("Enter num2: ")) num3 = num1 * num2 print("Product is: ", num3) 4. To run press f5 OUTPUT PYTHON SELECTION FUNCTION Selection in Python is made using the two keywords ‘if’ and ‘elif’ and else (elseif) With the same instruction copy the code below and run by pressing f5 CODE OUTPUT num1 = 34 if(num1<12): print("Num1 is good") elif(num1<35): print("Num2 is better") else: print("Num2 is great") PYTHON ITERATION (LOOPING) THE WHILE LOOP • With the while loop we can execute a set of statements as long as a condition is true. Example Print i as long as i is less than 6: i=1 while i < 6: print(i) i += 1 OUTPUT WHILE LOOP: THE BREAK STATEMENT • With the break statement we can stop the loop even if the while condition is true: Example Exit the loop when i is 3: i=1 while i < 6: print(i) if i == 3: break i += 1 OUTPUT WHILE LOOP: THE CONTINUE STATEMENT With the continue statement we can stop the current iteration, and continue with the next: Example Continue to the next iteration if i is 3: i=0 while i < 6: i += 1 if i == 3: continue print(i) # Note that number 3 is missing in the result OUTPUT WHILE LOOP: THE ELSE STATEMENT With the else statement we can run a block of code once when the condition no longer is true: Example Print a message once the condition is false i=1 while i < 6: print(i) i += 1 else: print("i is no longer less than 6") OUTPUT PYTHON FOR LOOPS A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages. With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc. Example Print each fruit in a fruit list: fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) OUTPUT The for loop does not require an indexing variable to set beforehand. LOOPING THROUGH A STRING Even strings are iterable objects, they contain a sequence of characters: Example Loop through the letters in the word "banana": for x in "banana": print(x) OUTPUT PYTHON FOR LOOPS: THE BREAK STATEMENT With the break statement we can stop the loop before it has looped through all the items: Example Exit the loop when x is "banana": fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": break OUTPUT PYTHON FOR LOOPS: THE CONTINUE STATEMENT With the continue statement we can stop the current iteration of the loop, and continue with the next: Example Do not print banana: fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x) OUTPUT PYTHON FOR LOOPS: THE RANGE() FUNCTION To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. Example Using the range() function: for x in range(6): print(x) OUTPUT Note that range(6) is not the values of 0 to 6, but the values 0 to 5. The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6): Example Using the start parameter: for x in range(2, 6): print(x) OUTPUT The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3): Example Increment the sequence with 3 (default is 1): for x in range(2, 30, 3): print(x) OUTPUT PYTHON FOR LOOPS: ELSE IN FOR LOOP The else keyword in a for loop specifies a block of code to be executed when the loop is finished: Example Print all numbers from 0 to 5, and print a message when the loop has ended: for x in range(6): print(x) else: print("Finally finished!") OUTPUT NESTED LOOPS A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop": Example Print each adjective for every fruit: adj = ["red", "big", "tasty"] fruits = ["apple", "banana", "cherry"] for x in adj: for y in fruits: print(x, y) OUTPUT THE PASS STATEMENT for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error. Example for x in [0, 1, 2]: pass OUTPUT # having an empty for loop like this, would raise an error without the pass statement SUMMARY • • • • • • • • Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. Python is designed to be highly readable. In python the variables and data structures in other programming languages like c, c++ and java need to declare the type of variables but in python you don’t need to do that. Python allows you to assign a single value to several variables simultaneously Python operators are used to perform operations on variables and values Python input() function allows user input. Python selection is made using the two keywords ‘if’ and ‘elif’ and else (elseif) Python Iteration (Looping) can execute a set of statements as long as a condition is true. Enrichment Activity I. Quiz (TRUE OR FALSE) Instructions: ✓ Write the letter A if your answer is True and B if False on the separate. 1. Python is a general-purpose compiled, interactive, object-oriented, and high-level programming language. 2. Python is a high-level, interpreted, interactive and object-oriented scripting language. 3. Python is not designed to be highly readable. 4. YouTube is considered as one of the company that uses python language. 5. Python didn’t supports Object-Oriented style. 6. Python variables need to explicit declaration to reserve memory space. 7. Python allows you to assign a single value to several variables simultaneously. 8. Python Operators are used to perform operations on variables and values. 9. Python assignment operators are used to assign values to variables 10. output()function allows user input. MULTIPLE CHOICE Instructions: ✓ Write the letter of the correct answer on the separate sheet. ✓ Choose the best answer 11. A. B. C. D. we can stop the loop even if the while condition is true: Break Statement Continue Statement Else Statement None of these 12. A. B. C. D. 13. A. B. C. D. we can run a block of code once when the condition no longer is true Break Statement Continue Statement Else Statement None of these statement we can stop the current iteration, and continue with the next Break Statement Continue Statement Else Statement None of these 14. The range() function is usually used in A. FOR LOOPS B. WHILE LOOPS C. DO WHILE D. None of these 15. A. FOR LOOPS B. WHILE LOOPS C. DO WHILE D. None of these is a loop inside a loop. 16. What would be the output of the following code? for x in range(3): print(x) else: print("Finally finished!") A. B. C. D. E. None of These 17. What would be the possible code for the output below? A. myNumber ="Hello World" print(myNumber) B. myNumber ="Hello World" print ”myNumber” C. myNumber ="Hello Wold" print(myNumber) D. myNumber ="Helo World" print(myNumber) E. None of These 18. In Python Operators “=” belongs to A. B. C. D. E. Logical operators Identity operators Membership operators Bitwise operators None of These 19. In Python Operators “and” belongs to A. B. C. D. E. group Logical operators Identity operators Membership operators Bitwise operators None of These 20. In Python Operators “in” belongs to A. B. C. D. E. group Logical operators Identity operators Membership operators Bitwise operators None of These group