Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Ch5 Python Programming Basics

The document provides an overview of Python programming, including its history, features, advantages, and applications. It highlights Python's readability, versatility, and extensive libraries, making it popular among tech companies. Additionally, it covers Python's syntax, data types, control flow, and keywords used in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Ch5 Python Programming Basics

The document provides an overview of Python programming, including its history, features, advantages, and applications. It highlights Python's readability, versatility, and extensive libraries, making it popular among tech companies. Additionally, it covers Python's syntax, data types, control flow, and keywords used in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Mapua University

Python
Programming
Basics
CS158 - 1 Artificial Intelligence
School of Information Technology
Raymond B. Sedilla, MSIT
Python is one of the achievements
of free software and is purely free
software and both its source code
and interpreter comply with the
GNU General Public License (GPL)
protocol.

Python (programming language)

Founder: Guido Van Rossum


When and Where: Created in Amsterdam during
Christmas in 1989.
Meaning: A big fan of Monty Python’s Flying Circus
Origin: Influenced by Modula -3, Python is a
descendant of ABC that would appeal to Unix / C
hackers.
https://en.wikipedia.org/wiki/Python_(programming_language)
Python can be used on a server to
create web applications.

What can Python can be used alongside


software to create workflows.

Python do? Python can connect to database


systems. It can also read and modify
files.

Python can be used to handle big data


and perform complex mathematics.

Python can be used for rapid


prototyping, or for production-ready
software development.

https://www.w3schools.com/python/python_intro.asp
Works on different platforms
(Windows, Mac, Linux, Raspberry
Pi, etc).

Why Python? Has a simple syntax similar to the


English language.

It has a syntax that allows


developers to write programs
with fewer lines.

It runs on an interpreter
system.

Python can be treated in a


procedural way, an object-
oriented way or a functional way.
https://www.w3schools.com/python/python_intro.asp
Python Syntax compared to other
programming languages

Python was designed Python uses new lines Python relies on


for readability and has to complete a indentation, using
some similarities to command, as opposed whitespace, to define
the English language to other programming scope; such as the
with influence from languages which often scope of loops,
mathematics. use semicolons or functions, and classes.
parentheses. Other programming
languages often use
curly brackets for this
purpose.

https://www.w3schools.com/python/python_intro.asp
Facts about Python
1. Python is currently the most widely used multi-purpose, high-level
programming language.
2. Python allows programming in Object-Oriented and Procedural
paradigms.
3. Python programs generally are smaller than other programming
languages like Java. Programmers have to type relatively less and the
indentation requirement of the language makes them readable all the
time.
4. Python language is being used by almost all tech-giant companies like
– Google, Amazon, Facebook, Instagram, Dropbox, Uber… etc.
Facts about Python
5. The biggest strength of Python is its huge collection of standard
libraries which can be used for the following:
Machine Learning
GUI Applications (like Kivy, Tkinter, PyQt, etc. )
Web frameworks like Django (used by YouTube, Instagram, Dropbox)
Image processing (like OpenCV, Pillow)
Web scraping (like Scrapy, BeautifulSoup, Selenium)
Test frameworks
Multimedia
Scientific computing
Text processing and many more..
Advantages :
Presence of third-party modules
Extensive support libraries(NumPy for numerical calculations, Pandas
for data analytics, etc)
Open source and community development
Versatile, Easy to read, learn and write
User-friendly data structures
High-level language
Dynamically typed language(No need to mention data type based on
the value assigned, it takes data type)
Object-oriented language
Portable and Interactive
Ideal for prototypes – provide more functionality with less coding
Advantages..
Highly Efficient(Python’s clean object-oriented design provides
enhanced process control, and the language is equipped with
excellent text processing and integration capabilities, as well as
its own unit testing framework, which makes it more efficient.)
(IoT)Internet of Things Opportunities
Interpreted Language
Portable across Operating systems
Applications :
GUI based desktop applications
Graphic design, image processing applications, Games, and
Scientific/ computational Applications
Web frameworks and applications
Enterprise and Business applications
Operating Systems
Education
Database Access
Language Development
Prototyping
Software Development
Organizations using Python
Python Keywords
Keywords in Python are reserved words that can not be used as a variable
name, function name, or any other identifier.

True: This keyword is used to represent a boolean true. If a statement


is true, “True” is printed.
False: This keyword is used to represent a boolean false. If a
statement is false, “False” is printed.
None: This is a special constant used to denote a null value or a void.
It’s important to remember, that 0, any empty container(e.g empty
list) does not compute to None. It is an object of its datatype –
NoneType. It is not possible to create multiple None objects and can
assign them to variables.
and, or, not, in, is
and: This a logical operator in python. “and” Return the first false
value. If not found return last. The truth table for “and” is depicted
below.
and, or, not, in, is
or: This a logical operator in python. “or” Return the first True
value.if not found return last. The truth table for “or” is depicted
below.
and, or, not, in, is
not: This logical operator inverts the truth value. The truth table for
“not” is depicted below.
in: This keyword is used to check if a container contains a value. This
keyword is also used to loop through the container.
is: This keyword is used to test object identity, i.e to check if both the
objects take the same memory location or not.
Iteration Keywords – for, while, break, continue
for: This keyword is used to control flow and for looping.
while: Has a similar working like “for”, used to control flow and for
looping.
break: “break” is used to control the flow of the loop. The statement
is used to break out of the loop and passes the control to the
statement following immediately after the loop.
continue: “continue” is also used to control the flow of code. The
keyword skips the current iteration of the loop but does not end the
loop.
Conditional keywords – if, else, elif
if: It is a control statement for decision-making. Truth expression
forces control to go in the “if” statement block.
else: It is a control statement for decision-making. False expression
forces control to go in the “else” statement block.
elif: It is a control statement for decision-making. It is short for “else
if“
def
def keyword is used to declare user-defined functions.
Return Keywords – Return, Yield
return: This keyword is used to return from the function.
yield: This keyword is used as a return statement but is used to return
a generator.
class
class keyword is used to declare user defined classes.
with
with keyword is used to wrap the execution of a block of code within
methods defined by the context manager. This keyword is not used
much in day to day programming.
as
as keyword is used to create the alias for the module imported. i.e
giving a new name to the imported module. E.g import math as
mymath.
pass
pass is the null statement in python. Nothing happens when this is
encountered. This is used to prevent indentation errors and used as a
placeholder.
lambda
Lambda keyword is used to make inline returning functions with no
statements allowed internally.
import, From
import: This statement is used to include a particular module into the
current program.
from: Generally used with import, from is used to import particular
functionality from the module imported.
Exception Handling Keywords
try: This keyword is used for exception handling, used to catch the errors in
the code using the keyword except. Code in the “try” block is checked, and
if there is any type of error, except block, is executed.
except: As explained above, this works together with “try” to catch
exceptions.
finally: No matter what is the result of the “try” block, the block termed
“finally” is always executed.
raise: We can raise an exception explicitly with the raise keyword
assert: This function is used for debugging purposes. Usually used to check
the correctness of code. If a statement is evaluated to be true, nothing
happens, but when it is false, “AssertionError” is raised. One can also print
a message with the error, separated by a comma.
del
del is used to delete a reference to an object. Any variable or list value can
be deleted using del.
Python Indentention
A block is a combination of all these statements. Block can be regarded
as the grouping of statements for a specific purpose. Most programming
languages like C, C++, and Java use braces { } to define a block of code.
One of the distinctive features of Python is its use of indentation to
highlight the blocks of code. Whitespace is used for indentation in
Python. All statements with the same distance to the right belong to the
same block of code. If a block has to be more deeply nested, it is simply
indented further to the right.
Python Comments
Python developers often make use of the comment system as, without the
use of it, things can get real confusing, real fast. Comments are the useful
information that the developers provide to make the reader understand
the source code. It explains the logic or a part of it used in the code.
Comments are usually helpful to someone maintaining or enhancing your
code when you are no longer around to answer questions about it.
Python Comments
Single line comments: Python single line comment starts with a hashtag symbol
with no white spaces (#) and lasts till the end of the line. If the comment
exceeds one line then put a hashtag on the next line and continue the comment.
Python’s single-line comments are proved useful for supplying short
explanations for variables, function declarations, and expressions.

Multi-line string as a comment: Python multi-line comment is a piece of text


enclosed in a delimiter (“””) on each end of the comment. Again there should be
no white space between delimiter (“””). They are useful when the comment text
does not fit into one line; therefore need to span across lines. Multi-line
comments or paragraphs serve as documentation for others reading your code.
See the following code snippet demonstrating multi-line comment:
Taking input in python
input ( ): This function first takes the input from the user and converts it into a
string. The type of the returned object always will be <type ‘str’>. It does not
evaluate the expression it just returns the complete statement as String.
Taking input in Python
raw_input ( ) : This function works in older version (like Python 2.x). This
function takes exactly what is typed from the keyboard, converts it to string and
then return it to the variable in which we want to store.
Python Variables

Variables Variable Names


Variables are containers for storing data A variable can have a short name (like x and y) or a
values. more descriptive name (age, carname, total_volume).
Rules for Python variables:
Creating Variables A variable name must start with a letter or the
underscore character
Python has no command for declaring a A variable name cannot start with a number
variable. A variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ )
A variable is created the moment you first Variable names are case-sensitive (age, Age, and
assign a value to it AGE are three different variables)

https://www.w3schools.com/python/python_intro.asp
Python Numbers

INT FLOAT COMPLEX

Int, or integer, is a Float, or "floating- Complex numbers are


whole number, point number" is a written with a "j" as
positive or negative, number, positive or the imaginary part:
without decimals, of negative, containing
unlimited length. one or more decimals.

https://www.w3schools.com/python/python_intro.asp
Python Strings
'hello' is the same as "hello".

You can display a string literal with the print() function:

https://www.w3schools.com/python/python_intro.asp
Python Booleans
In programming, you often need to know if an expression is True or
False.

You can evaluate any expression in Python, and get one of two
answers, True or False.

When you compare two values, the expression is evaluated and Python
returns the Boolean answer:

https://www.w3schools.com/python/python_intro.asp
Python Operators
Python divides the operators in the following groups:

Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators

https://www.w3schools.com/python/python_intro.asp
Python Lists
Lists are used to store multiple items in a single variable.

Lists are created using square brackets:


Lists items are ordered, changeable, and allow duplicate values.
Lists items are indexed, the first item has index [0], the second item has
index [1] etc.

https://www.w3schools.com/python/python_intro.asp
Python Tuple
Tuples are used to store multiple items in a single variable.

Tuple is a collection which is ordered and unchangeable.


Tuples are written with round brackets.
Tuple items are indexed, the first item has index [0], the second item
has index [1] etc.

https://www.w3schools.com/python/python_intro.asp
Python Sets
Sets are used to store multiple items in a single variable.

Set is a collection which is both unordered and unindexed.


Sets are written with curly brackets.
Sets are unordered, so you cannot be sure in which order the items will
appear.
Once a set is created, you cannot change its items, but you can add new
items.

https://www.w3schools.com/python/python_intro.asp
Python Dictionaries
Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection that is ordered*, changeable, and does not allow


duplicates.
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and
earlier, dictionaries are unordered.

Dictionaries are written with curly brackets, and have keys and values:

https://www.w3schools.com/python/python_intro.asp
Python If ... Else
Python supports the usual logical conditions from mathematics:

These conditions can be used in several ways, most commonly in "if


statements" and loops.

Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b

https://www.w3schools.com/python/python_intro.asp
Python Loops
Python has two primitive loop commands:

While loop we can execute a set of statements as long as a condition is true.


For loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
The for loop does not require an indexing variable to set beforehand.
To loop through a set of code a specified number of times, we can use the
range() function,

https://www.w3schools.com/python/python_intro.asp

You might also like