🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

CC102 - Computer Programming 1 (Python).pptx

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Document Details

TollFreeObsidian8214

Uploaded by TollFreeObsidian8214

Sorsogon State University

Tags

python programming computer programming software engineering programming languages

Full Transcript

INTRODUCTION TO PYTHON PROGRAMMING BSIT CC102 – Computer Programming 1 Prepared By: KENNETH L. GISALAN INSTRUCTOR I All About Python Python is a general-purpose, versatile, and powerful programming language. It’s a grea...

INTRODUCTION TO PYTHON PROGRAMMING BSIT CC102 – Computer Programming 1 Prepared By: KENNETH L. GISALAN INSTRUCTOR I All About Python Python is a general-purpose, versatile, and powerful programming language. It’s a great first language because it’s concise and easy to read. Whatever you want to do, Python can do it. From web development to machine learning to data science, Python is the language for you. Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently whereas other languages use punctuation, and it has fewer syntactical constructions than other languages. All About Python Python is a MUST for students and working professionals to become a great Software Engineer specially when they are working in Web Development Domain. It will list down some of the key advantages of learning Python: - Python is Interpreted - Python is Interactive - Python is Object-Oriented - Python is a Beginner’s Language History of Python Python was developed by Guido van Rossum in the late 80s and early 90s at the National Research Institute for Mathematics and Computer Science in the Netherlands Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other scripting languages. Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public License (GPL). Python is now maintained by a core development team at the institute, although Guido van Rossum still holds a vital role in directing its Python Features Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language quickly Easy-to-read − Python code is more clearly defined and visible to the eyes Easy-to-maintain − Python’s source code is fairly easy-to- maintain. A broad standard library − Python’s bulk of the library is very portable and cross-platform Interactive Mode − Python has support for an interactive mode which allows interactive testing and debugging of snippets of code. Python Features Portable − Python can run on a wide variety of hardware platforms and has the same interface on all platforms. Extendable − You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient. Databases − Python provides interfaces to all major commercial databases. GUI Programming − Python supports GUI applications that can be created and ported to many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix. Scalable − Python provides a better structure and support for large programs than shell scripting. Lesson 1 Environment Setup and Basic Syntax (Week 2) Python Environment Setup Installing Python Download the latest version of Python from python.org. Run the installer by double-clicking on the downloaded file and following the steps. Installing Python After installation is completed, we will get a setup successfully install message. Let’s open the command line or terminal and type the below command to check the version of Python. Installing PyCharm IDE Download the latest version of PyCharm Community Edition from their official website https://www.jetbrains.com/py charm/download. Once you’ve downloaded the installer as per the operating system, Next run an installer by double-clicking on the downloaded file and following the steps. Python Basic Syntax First Python Program Use the print() function and write a message in its opening and closing brackets shown below. A message is a string that is a sequence of characters. In Python, strings are enclosed inside single quotes, double quotes, or triple quotes. print(“Hello World!”) Identifiers A Python identifier is a name used to identify a variable, function, class, module or other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9). Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python. Identifiers Here are naming conventions for Python identifiers: Class names start with an uppercase letter. All other identifiers start with a lowercase letter. Starting an identifier with a single leading underscore indicates that the identifier is private. Starting an identifier with two leading underscores indicates a strongly private identifier. If the identifier also ends with two trailing underscores, the identifier is a language-defined special name. Reserved Words The following list shows the Python keywords. These are reserved words and you cannot use them as constant or variable or any other identifier names. All the Python keywords contain lowercase letters only. Lines and Indentations Python provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced. The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. Multi-Line Statements Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. Statements contained within the [], {}, or () brackets do not need to use the line continuation character. Quotations in Python Python accepts single (‘), double (“) and triple (‘’’ or “””) quotes to denote string literals, as long as the same type of quote starts and ends the string. The triple quotes are used to span the string across multiple lines. Comments in Python A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them. Using blank lines A line containing only whitespace, possibly with a comment, is known as a blank line and Python totally ignores it. In an interactive interpreter session, you must enter an empty physical line to terminate a multiline statement. Waiting for the User The following line of the program displays the prompt, the statement saying “Press the enter key to exit”, and waits for the user to take action. raw_input(“\n\nPress the enter key to exit.”) Here, “\n\n” is used to create two new lines before displaying the actual line. Once the user presses the key, the program ends. This is a nice trick to keep a console window open until the user is done with an application. Multiple Statements on a Single Line The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new code block. Here is a sample snip using the semicolon: name = “Juan” ; age = 24 Multiple Statements Groups as Suites A group of individual statements, which make a single code block are called suites in Python. Compound or complex statements, such as if, while, def, and class require a header line and a suite. Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by one or more lines which make up the suite. Multiple Statements Groups as Suites A group of individual statements, which make a single code block are called suites in Python. Compound or complex statements, such as if, while, def, and class require a header line and a suite. Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by one or more lines which make up the suite. Lesson 2 Variables and Operators (Week 3-4) Python Variables Python Variables Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals or characters in these variables. Assigning Values 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. The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable. Multiple Assignments Python allows you to assign a single value to several variables simultaneously. Python also allows you to assign multiple objects to multiple variables. Standard Data Types Python Numbers Standard Data Types Python Strings - Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end. - The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. Standard Data Types Python Lists - Lists are the most versatile of Python’s compound data types. A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type. - The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator. Standard Data Types Python Tuples - A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses. - The main differences between lists and tuples are Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. Standard Data Types Python Dictionary - Python’s dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object. - Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). Data Types Convertion There are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted value. Data Types Convertion Data Types Convertion Data Types Convertion Data Types Convertion Python Operators Python Arithmetic Operators Assume variable a holds 10 and variable b holds Python Arithmetic Operators Assume variable a holds 10 and variable b holds Python Comparison Operators Assume variable a holds 10 and variable b holds Python Assignment Operators Assume variable a holds 10 and variable b holds Python Assignment Operators Assume variable a holds 10 and variable b holds Python Bitwise Operators Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in binary format they will be as follows: a = 0011 1100 b = 0000 1101 a&b = 0000 1100 a|b = 0011 1101 a^b = 0011 0001 ~a = 1100 0011 Python Bitwise Operators Python Logical Operators Assume variable a holds 10 and variable b holds 20 Python Membership Operators Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples. Python Identity Operators Identity operators compare the memory locations of two objects. Python Operators Precedence Python Operators Precedence Python Operators Precedence Lesson 3 Functions, Modules and Packages (Week 5-6) Python Functions Functions Python Functions is a block of related statements designed to perform a computational, logical, or evaluative task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over and over again. Functions Syntax def function_name(parameters) : “””docstring””” statement(s) Docstring The first string after the function header is called the docstring and is short for documentation string. It is used to explain in brief, what a function does. Docstring def greet(name): ””“This function greets to the person passed in as parameter!””” print(“Hello, “ + name + “. Good morning) The Return Statement The return statement is used to exit a function and go back to the place from where it was called. Syntax of Return return [expression_list] How Function works in Python? Python Function Arguments Required arguments Keyword arguments Default arguments Variable-length arguments Required Arguments Required arguments are the arguments passed to a function in correct positional order. Keyword Arguments Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name. Default Arguments A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. Variable-length Arguments You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments. Default Arguments A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. Variable-length Arguments You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments. The Anonymous Functions These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions. PYTHON MODULES A module is a file containing Python definitions and statements. The file name is the module name with the suffix.py appended. Within a module, the module’s name (as a string) is available as the value of the global variable __name__. Import fibo A module is a file containing Python definitions and statements. The file name is the module name with the suffix.py appended. Within a module, the module’s name (as a string) is available as the value of the global variable _name__. PYTHON PACKAGES Packages are a way of structuring Python’s module namespace by using “dotted module names”. Importing* From a Package Intra-package References Packages in Multiple Directories PYTHON DICTIONARIES Dictionary A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values. Accessing Data Items with Keys Syntax print(dictionary_name[key]) Using Methods to Access Elements Syntax: dict_name.keys() dict_name.values() dict_name.items() Adding and Changing Dictionary Elements Syntax: dictionary_name[key] = new_value Deleting Dictionary Elements Syntax: dictionary_name.pop(key) dictionary_name.popitem() The dict() Constructor Syntax: dictionary = dict(items) Dictionary Methods Dictionary Methods Aliasing and Copying Alias and opposites refer to the same object; a copy refers to a fresh copy of the same dictionary. If we modify alias, opposites is also changed. If we modify a copy, opposites is unchanged. PYTHON SETS Sets Sets are a collection of distinct (unique) objects. These are useful to create lists that only hold unique values in the dataset. It is an unordered collection but a mutable one, this is very helpful when going through a huge dataset. Defining a Set You can define a set as simple as by naming all of its elements in brackets. The only exception is empty set, which can be created using the function set(). If set(..) has a list, a string or a tuple as a parameter, it will return a set composed of its elements. Creating a Set A set is created by using the set() function or placing all the elements within a pair of curly braces. Set Size and Membership The “len()” function returns the number of elements in a set, and the “in” and not in operators can be used to test for membership. Methods for Sets add(s) discard(s) union(s) intersection(s) clear(s) Accessing Values in a Set We cannot access individual values in a set. We can only access all the elements together as shown above. But we can also get a list of individual elements by looping through the set. Compare Sets We can check if a given set is a subset or superset of another set. The result is True or False depending on the elements present in the sets. PYTHON FILES Files Files are traditionally a part of data structures. And although big data is commonplace in the data science industry, a programming language without the capability to store and retrieve previously stored information would hardly be useful. You still have to make use of the all the data sitting in files across databases and you will learn how to do this. Basic functions in working with Files open() to open files in your system the filename is the name of the file to be opened read() to read entire files readline() to read one line at a time write() to write a string to a file, and return the number of characters written close() to close the file. The open function The open function takes two arguments. The first is the name of the file, and the second is the mode. Mode ‘w’ means that we are opening the file for writing. Mode ‘r’ means reading, and mode ‘a’ means appending. Reading Data from Files Python file descriptors have three methods for reading in data from a file. The read() method, returns the entire contents of the file as a single string. The readline() method returns one line of the file at a time. Each time you call it readline() returns the next line. Calls made to readline() after reaching the end of the file return an empty string (‘’). Reading Data from Files MIDTERM EXAM

Use Quizgecko on...
Browser
Browser