0% found this document useful (0 votes)
26 views

COMP002 Lesson 3 Basic Prog PPT3

Uploaded by

jolosantos098
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

COMP002 Lesson 3 Basic Prog PPT3

Uploaded by

jolosantos098
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

LESSON 3

in

Computer Program Basics using


PYTHON
Prepared by
Elaine B. Bolambot, MIT
Faculty
At the end of the lesson, the learner
will be able to:
 Identify the basic structure of programming
languages and the different rules in naming
convention of a variables;
 Describe the different data types in a computer
program; and
 Apply an input and output from the console window
and other various programming scenarios.
PYTHON INTRODUCTION
an interpreted high-level programming language for
general-purpose programming. Created by Guido van
Rossum and first released in 1991, Python has a
design philosophy that emphasizes code readability,
notably using significant whitespace. It provides
constructs that enable clear programming on both
small and large scales. In July 2018, the creator Guido
Rossum stepped down as the leader in the language
community after 30 years.
PYTHON INTRODUCTION

ACCORDING TO:

Van Rossum, was looking for a "hobby" programming project that


would keep him occupied during the week around Christmas. His
office ... would be closed, Hence he decided to write an
interpreter for the new scripting language he had been thinking
about lately: a descendant of ABC that would appeal to Unix. He
chose Python as a working title for the project, being a big Monty
Python’s flying circus (A Sketch Comedy Group Series) Fan.
ORIGIN
PYTHON INTRODUCTION
WHY WAS PYTHON CREATED?
"My original motivation for creating Python was the perceived
need for a higher level language in the Amoeba [Operating
Systems] project. I realized that the development of system
administration utilities in C was taking too long. Moreover, doing
these things in the Bourne shell wouldn't work for a variety of
reasons. ... So, there was a need for a language that would bridge
the gap between C and the shell”

- Guido Van Rossum


USES AND APPLICATIONS

Web and Internet Development: Python lets you develop a web


application without too much trouble. It has libraries for internet
protocols like HTML and XML, JSON, e-mail processing, FTP, IMAP,
and easy-to-use socket interface. Yet, the package index has more
libraries
Scientific and Numeric Applications : This is one of the the
very common applications of python programming. With its
power, it comes as no surprise that python finds its place in
the scientific community.
Python Applications in Education : Thanks to its simplicity,
brevity, and large community, Python makes for a great
introductory programming language. Applications of python
programming in education has huge scope as it is a great
USES AND APPLICATIONS

Games and 3D Graphics : PyGame, PyKyra are two frameworks


for game-development with Python. Apart from these, we also
get a variety of 3D-rendering libraries.
Software Development Application : Software developers
make use of python as a support language. They use it
for build-control and management, testing, and for a lot
of other things
Business Applications : Python is also used to build ERP
and e-commerce systems.

In Conclusion, Python is almost everywhere and


now that we know Python applications. We can do with it,
WHY DO PEOPLE USE
PYTHON?
The following primary factors cited by Python
users seem to be these:
Python is object-oriented - Structure supports such concepts
as polymorphism, operation overloading, and multiple
inheritance. It's free (open source) - Downloading and
installing Python is free and easy Source code is easily
accessible.
It's powerful - Dynamic typing, Built-in types and tools,
Library utilities, Third-party utilities (e.g. Numeric, NumPy,
SciPy), Automatic memory management
It's portable - Python runs virtually every major platform
used today, As long as you have a compatible Python
interpreter installed, Python programs will run in exactly the
WHY DO PEOPLE USE
PYTHON?
Readability: Python's syntax is clear and readable. The way
Python's syntax is organized imposes some order to programmers.
Experts and beginners can easily understand the code, and
everyone can become productive in Python very quickly.
It Is Simple to Get Support: The Python community always provides
support to Python users. As we already know, Python code is freely
available for everyone. Therefore, thousands of developers
worldwide are working hard to find bugs and create patches to fix
those bugs.
Reusability: Python encourages program reusability by
implementing modules and packages. A large set of modules has
already been developed and is provided as The Standard Python
Library, which is part of the Python distribution. You can easily
share functionality between your programs by breaking the
DIFFERENCE OF PYTHON FROM OTHER
LANGUAGES
▪ Python code does not declare the types of variables -- just
assign to them and go.
▪ Python raises a runtime error if the code tries to read
from a variable that has not been given a value.
▪ Like C++ and Java, Python is case sensitive so "a" and
"A" are different variables.
▪ The end of a line marks the end of a statement, so unlike
C++ and;
▪ Java, Python does not require a semicolon at the end of
each statement.
▪ You can include semicolons at the end of Python
statements (perhaps just out of habit), but it's not the best
. PYTHON DATA TYPES
Number Python
Numbers variables are created by the standard Python method.
Most of the time using the standard Python number type is fine.
Python will automatically convert a number from one type to
another if it needs. But, under certain circumstances where a
specific number type is needed (ie. complex, hexadecimal), the
format can be forced into a format by using additional syntax.
String
Create string variables by enclosing characters in quotes.
Python uses single quotes ' double quotes " and triple
quotes """ to denote literal strings. Only the triple quoted
strings """ also will automatically continue across the
end-of-line statement List Lists are a very useful variable
type in Python.
PYTHON DATA TYPES

List
A list can contain a series of values. List variables are
declared by using brackets [ ] following the variable name.
Tuple
Tuples are a group of values like a list and are manipulated
in similar ways. But, tuples are fixed in size once they are
assigned. In Python the fixed size is considered immutable
as compared to a list that is dynamic and mutable. Tuples
are defined by parenthesis ().
PYTHON DATA TYPES
Dictionary
Dictionaries in Python are lists of Key: Value pairs. This is
a very powerful datatype to hold a lot of related
information that can be associated with keys. The main
operation of a dictionary is to extract a value based on
the key name. Unlike lists, where index numbers are
used, dictionaries allow the use of a key to access its
members. Dictionaries can also be used to sort, iterate,
and compare data.

-Dictionaries are created by using braces ({}) with pairs


separated by a comma (,) and the key values associated
with a colon(:). In Dictionaries, the Key must be unique.
KEYWORDS IN PYTHON

Print : print to console


While: controlling the flow of the program
For: iterate over items of a collection so that they appear
Break: interrupt the (loop) cycle, if needed
Continue: used to interrupt the current cycle, without jumping
out of the whole cycle. A new cycle will begin.
If: used to determine, which statements are going to be
executed.
Elif: stands for else if.If the first test evaluates to False, then it
continues with the next one
Else: is optional. The statement after the else keyword is
executed, unless the condition is True
Is: tests for object identity
KEYWORDS IN PYTHON

Not: negates a boolean value


Or: at least one condition must be met.
Import: import other modules into a Python script
From: for importing a specific variable, class, or function from
a module
Def: used to create a new user-defined function
Return: exits the function and returns a value
Global: access variables defined outside functions
Try: specifies exception handlers
Except: catches the exception and executes codes
Finally: is always executed in the end. Used to clean up
resources.
What can Python do?

•Python can be used on a server to create web


applications.
•Python can be used alongside software to create
workflows.
•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.
Python Install

• you can download it for free from the following website:


https://www.python.org/
• Find the Pycharm Community version.
Python Quickstart

Python is an interpreted programming language, this means that


as a developer you write Python (.py) files in a text editor and then
put those files into the Python interpreter to be executed.
The way to run a Python file is like this on the command line:
C:\Users\Your Name>python helloworld.py
Where "helloworld.py" is the name of your Python file.
Let's write our first Python file, called helloworld.py, which can be
done in any text editor.

helloworld.py
print("Hello, World!")
Python Syntax

Execute Python Syntax

As we learned in the previous page, Python syntax can be


executed by writing directly in the Command Line:

>>> print("Hello, World!")


Hello, World!
Python Indentation

Indentation refers to the spaces at the beginning of a code line.


Where in other programming languages the indentation in code is
for readability only, the indentation in Python is very important.
Python uses indentation to indicate a block of code.
ExampleGet
if 5 > 2:
print("Five is greater than two!")

Python will give you an error if you skip the indentation:


Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
Python Indentation (continuation)
The number of spaces is up to you as a programmer, the most
common use is four, but it has to be at least one.

Example
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
You have to use the same number of spaces in the same block of code, otherwise,
Python will give you an error:
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Python Variables
In Python, variables are created when you assign a value to it:
Variables
Variables are containers for storing data values.

Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.

Example
Variables in Python:
x = 5
y = "Hello, World!“
print(x)
print(y)
Python Variables(continuation)
Variables do not need to be declared with any particular type, and can
even change type after they have been set.

Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Casting
If you want to specify the data type of a variable, this can be done with casting.

Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Comments

Python has commenting capability for in-code documentation.


Comments start with a #, and Python will render the rest of the
line as a comment:
Comments can be placed at the end of a line, and Python will
ignore the rest of the line:
Example

Comments in Python:
#This is a comment.
print("Hello, World!")
Python - Variable Names

Variable Names
•A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume). Rules for 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 (age, Age, and AGE are three different
variables)
•A variable name cannot be any of the Python keywords.
ExampleGe
t your own Python Serve
Legal variable names:
myvar = "John"
my_var = "John" Example
_my_var = "John" Illegal variable names:
myVar = "John"
MYVAR = "John" 2myvar = "John"
myvar2 = "John“ my-var = "John"
my var = "John"
print(myvar)
print(my_var)
print(_my_var)
print(myVar)
print(MYVAR)
print(myvar2) Remember that variable names are case-sensitive
Multi Words Variable Names
Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:

Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "John"

Pascal Case
Each word starts with a capital letter:
MyVariableName = "John"

Snake Case
Each word is separated by an underscore character:
my_variable_name = "John"
Python Variables - Assign Multiple
Values
Python allows you to assign values to multiple variables in one line:
ExampleGet your own Python Serve
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

Note: Make sure the number of variables matches the number of values, or else you will
get an error.
One Value to Multiple Variables
And you can assign the same value to multiple variables in one
line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
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
Unpack a list:
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
Python - Unpack Tuples
Unpacking a Tuple
When we create a tuple, we normally assign values to it. This is called
"packing" a tuple:
ExampleGet your own Python Serve
Packing a tuple:
fruits = ("apple", "banana", "cherry")
in Python, we are also allowed to extract the values back into
variables. This is called "unpacking":
Example
Unpacking a tuple:
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow) Note:The number of variables must match the number
of values in the tuple, if not, you must use an asterisk
print(red) to collect the remaining values as a list.
Using Asterisk*
If the number of variables is less than the number of values, you can add
an * to the variable name and the values will be assigned to the variable
as a list:

Example
Assign the rest of the values as a list called "red":
fruits =
("apple", "banana", "cherry", "strawberry", "raspberry")

(green, yellow, *red) = fruits

print(green)
print(yellow)
print(red)
If the asterisk is added to another variable name than the last, Python
will assign values to the variable until the number of values left
matches the number of variables left.
Example
Add a list of values the "tropic" variable:
fruits =
("apple", "mango", "papaya", "pineapple", "cherry")

(green, *tropic, red) = fruits

print(green)
print(tropic)
print(red)
»
SEATWORK # 3- Python Syntax
1. # Fix the indentation errors in the following code:
def greet(name):
print(“Hello”, name + “!”)
print(“Welcome to Python!”)
greet(“Alice”)

2. # Correct the indentation in the code below:


if 10 >9:
print(“Ten is greater than nine! ”)
else:
print (“Ten is greater than nine! ”)
SEATWORK # 3- Python Syntax
3. # Assign the values 10 and 20 to variables named "a" and "b"
respectively.
# Then, swap the values of the variables without using a
temporary variable.
4. # Create
# Print a tupleofnamed
the values "colors"
"a" and containing
"b" after the elements
the swap.
"red", "green", and "blue".
# Print the tuple.

5. # Create a variable named "name" and assign your name to


it.
# Then, create a variable named "age" and assign your age to
it.
# Print a sentence that combines these two variables.
Thank you!

You might also like