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

Lecture Unit 3

Intro to python

Uploaded by

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

Lecture Unit 3

Intro to python

Uploaded by

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

UNIVERSITY OF LUSAKA

SCHOOL OF SOCIAL SCIENCES AND TECHNOLOGY

LECTURE~UNIT 3: Introduction To Python Programming Language 1


NAME: Longwani C Perry (Mr.)
CONTACT: +260 966589151
§ The programming language you will be learning is Python.
§ Python is an example of a high-level language

§ other high-level languages you might have heard of are


C++, PHP, Pascal, C#, and Java.

§ As you might infer from the name high-level language, there


are also low-level languages, sometimes referred to as
machine languages or assembly languages.
§ Loosely speaking, computers can only execute programs
written in low-level languages.

§ Thus, programs written in a high-level language have to be


translated into something more suitable before they can run.

§ Almost all programs are written in high-level languages


because of their advantages.
§ It is much easier to program in a high-level language so
programs take less time to write, they are shorter and easier
to read, and they are more likely to be correct.

§ High-level languages are portable, meaning that they can


run on different kinds of computers with few or no
modifications.
§ The engine that translates and runs Python is called the
Python Interpreter

§ There are two ways to use it:


§ immediate mode

§ script mode.
§ In immediate mode, you type Python expressions into the
Python Interpreter window, and the interpreter immediately
shows the result:

§ The >>> is called the Python prompt.


§ The interpreter uses the prompt to indicate that it is ready for
instructions.

§ We typed 2 + 2, and the interpreter evaluated our expression,


and replied 4, and on the next line it gave a new prompt,
indicating that it is ready for more input.
§ Alternatively, you can write a program in a file and use the
interpreter to execute the contents of the file. Such a file is
called a script.

§ Scripts have the advantage that they can be saved to disk,


printed, and so on.
§ An Integrated development environments (IDE) is a
collection of applications that facilitates the development of
other applications.

§ Designed to encompass all programming tasks in one


application, one of the main benefits of an IDE is that they
offer a central interface with all the tools a developer needs
§ An IDE constitutes the following:
§ Code editor/ Text editor:
§ Designed for writing and editing source code

§ Code these editors are distinguished from text editors


because they work to either simplify or enhance the
process of writing and editing of code for developers
§ An IDE constitutes the following:
§ Compiler/Interpreter:
§ These are translators that transform source code that is
written in a human readable/writable language in a form
that computers can execute.

§ Interpreters work differently to compilers


§ An IDE constitutes the following:
§ Debugger:
§ Debuggers are used during testing and can help
developers debug their application programs.

§ Programs can have one of the following types of errors


§ Syntax errors
§ Runtime errors
§ Logic errors
§ Python can only execute a program if the program is
syntactically correct
§ otherwise, the process fails and returns an error
message.

§ Syntax refers to the structure of a program and the rules


about that structure.
§ For example, in English, a sentence must begin with a
capital letter and end with a period. this sentence
contains a syntax error. So does this one
§ Python is not so forgiving (programming languages can be
annoying).

§ If there is a single syntax error anywhere in your program,


§ Python will display an error message and quit, and you
will not be able to run your program.
§ During the first few weeks of your programming career, you
will probably spend a lot of time tracking down syntax
errors.

§ As you gain experience, though, you will make fewer errors


and find them faster.
§ The second type of error is a runtime error, so called
because the error does not appear until you run the
program.

§ These errors are also called exceptions because they


usually indicate that something exceptional (and bad) has
happened.
§ Runtime errors are rare in the simple programs you will see
in the first few efforts, so it might be a while before you
encounter one.

§ Often caused by a number of things such as:

§ division by zero

§ trying to use a resource that no longer exists

§ loss of connection to a database or network…etc.


§ The third type of error is the Logic error.

§ If there is a logic/semantic error in your program:


§ it will run successfully, in the sense that the computer will
not generate any error messages,
§ but it will not do the right thing.

§ It will do something else. Specifically, it will do what you told


it to do.
§ The problem is that the program you wrote is not the
program you wanted to write.

§ The meaning of the program (its semantics) is wrong.

§ Identifying semantic errors can be tricky because it


requires you to work backward by looking at the output of
the program and trying to figure out what it is doing.
This is where Debugging comes in!!!
§ Most importantly:
Programming languages are formal languages that have
been designed to express computations.

§ Syntax rules come in two flavors, pertaining to tokens and


structure.
§ Tokens are the basic elements of the language, such as
words, numbers, parentheses, commas, and so on.
§ The second type of syntax rule pertains to the structure of a
statement/instruction

§ i.e. that is, the way the tokens are arranged.

§ The statement 3=+6$ is structurally illegal because you can’t


place a plus sign immediately after an equal sign.
§ Keywords are the reserved words in Python.
§ We cannot use a keyword as a variable name, function name
or any other identifier.

§ They are used to define the syntax and structure of the


Python language. In Python, keywords are case sensitive.
§ Python Statements
§ Instructions that a Python interpreter can execute are
called statements.
§ For example, a = 81 is an assignment statement.
§ Other examples of statements include:
§ if statement,
§ for statement,
§ while statement, etc. which will be discussed later.
§ Multi-line statement
§ In Python, the end of a statement is marked by a newline
character (which is automatically added)

§ But we can make a statement extend over multiple lines


with the line continuation character (\).
§ This is an explicit line continuation.
§ In Python, line continuation is implied inside
parentheses ( ), brackets [ ], and braces { }.
§ Python Indentation
§ Most of the programming languages like C, C++, and Java
use braces { } to define a block of code.

§ Python, however, uses indentation.


§ A code block (body of a function, loop, etc.) starts with
indentation and ends with the first unindented line.

§ The amount of indentation is up to you, but it must be


consistent throughout that block.
§ Python Indentation
§ The enforcement of indentation in Python makes the code
look neat and clean.

§ This results in Python programs that look similar and


consistent.

§ Indentation can be ignored in line continuation, but it's


always a good idea to indent. It makes the code more
readable.
§ Python Comments
§ Comments are very important while writing a program.

§ They describe what is going on inside a program, so that a


person looking at the source code does not have a hard time
figuring it out.
§ You might forget the key details of the program you just
wrote in a month's time. So taking the time to explain these
concepts in the form of comments is always fruitful.
§ In Python, we use the hash (#) symbol to start writing a
comment.
§ Python Interpreter ignores comments.
§ We use the print() function to output data to the standard
output device (screen).
§ We can also output data to a file, but this will be
discussed later.

§ An example of its use is given below.


§ A variable is a named location used to store data in the
memory.

§ It is helpful to think of variables as a container that holds data


that can be changed later (anytime) in the program.

§ In this example we created a variable named number. We


have assigned the value 10 to the variable.
§ To assign a value to a variable we use the assignment
operator =

§ Examples of declaring and assigning value to a variable

§ Python is a type-inferred language, so you don't have to


explicitly define the variable type.
§ It automatically knows that apple.com is a string and
declares the website variable as a string.
§ Python allows you to assign multiple values to multiple
variables using one line of code (This is not a good practice)

§ You can equally assign the same value to multiple variables


using one line of code
§ A constant is a type of memory location whose value cannot
be changed.
§ Constants can be thought of to be containers that hold
information which cannot be changed later.

§ You can think of constants as a bag to store some books


which cannot be replaced once placed inside the bag.
§ In Python, constants are usually declared and assigned in a
module (separate file).

§ Here, the module is a new file containing variables, functions,


etc. which is imported to the main file.

§ Inside the module, constants are written in all capital letters


and underscores separating the words.
§ Create a constant.py:

§ Create a main.py:
§ Constant and variable names should have a combination of
letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to
9) or an underscore (_).
§ Create a name that makes sense (meaningful of the data they
hold)
§ If you want to create a variable name having two words, use
underscore to separate them.
§ Use capital letters possible to declare a constant.
§ Never use special symbols like !, @, #, $, %, etc.
§ Don't start a variable name with a digit.
§ Every value in Python has a datatype.
§ A data type is simply a form or format in which data
exists

§ Since everything is an object in Python programming,


data types are actually classes and variables are
instance (object) of these classes.

§ There are various data types in Python.


§ Integers, floating point numbers and complex numbers fall can
be manipulated in Python.

§ They are defined respectively as int, float and complex classes in


Python.
§ We can use the type() function to know which class a variable
or a value belongs to.

§ Similarly, the isinstance() function is used to check if an object


belongs to a particular class.
§ Integers can be of any length, it is only limited by the
memory available.

§ A floating-point number is accurate up to 15 decimal places.


Integer and floating points are separated by decimal points.
§ 1 is an integer, 1.0 is a floating-point number.

§ Complex numbers are written in the form, x + yj, where x is


the real part and y is the imaginary part.
§ Python List:
§ A List is an ordered sequence of items. It is one of the most
used datatype in Python and is very flexible.

§ All the items in a list do not need to be of the same type.


§ Python Tuple:
§ Tuple is an ordered sequence of items same as a list. The
only difference is that tuples are immutable.

§ Tuples once created cannot be modified.

§ Tuples are used to write-protect data and are usually


faster than lists as they cannot change dynamically.
§ Python Strings:
§ String is sequence of Unicode characters.

§ We can use single quotes or double quotes to represent


strings. Multi-line strings can be denoted using triple
quotes, ''' or """.
§ Python Set:
§ Set is an unordered collection of unique items.

§ Set is defined by values separated by comma inside


braces { }. Items in a set are not ordered.

§ We can perform set operations like union, intersection on


two sets. Sets have unique values.

§ They eliminate duplicates.


§ Python Dictionary:
§ Dictionary is an unordered collection of key-value pairs.
§ It is generally used when we have a huge amount of data.

§ Dictionaries are optimized for retrieving data.


§ We must know the key to retrieve the value.

§ In Python, dictionaries are defined within braces {} with each item


being a pair in the form key: value. Key and value can be of any type.
§ The process of converting the value of one data type
(integer, string, float, etc.) to another data type is called
type conversion or type casting.

§ Python has two types of type conversion.

§ Implicit Type Conversion

§ Explicit Type Conversion


§ In Implicit type conversion, Python automatically converts
one data type to another data type.

§ This process doesn't need any user involvement (automatic).

§ This type of conversion involves the conversion of the lower


data type (e.g. integer) to a higher data type (e.g. float) to
avoid data loss.
§ Given the following example where we try adding a string
and an integer, how does Python deal with it?

§ This program run until the point were it would not work. It
would give the following as output and error notification:
§ In Explicit Type Conversion, users convert the data type of an
object to required data type.

§ We use the predefined functions like int(), float(), str(), etc. to


perform explicit type conversion.

§ This type of conversion is also called typecasting because


the user casts (changes) the data type of the objects.
§ The Python programming language provides
numerous built-in functions (predefined functions) that
are readily available to us at the Python prompt.

§ Some of the functions like input() and print() are widely


used for standard input and output operations
respectively.
§ To perform input operations (feeding data into a
program), python provides an input() function.
§ General Syntax:
input(“Message Prompt”)
§ where Message Prompt is an optional string that is
displayed on screen at the time of taking input.

§ This is an example of performing both input and output


at the same time
§ Here, we can see that the entered value 10 is a string, not a
number.

§ To convert this into a number we can


use int() or float() functions.
§ This same operation can be performed using
the eval() function.

§ But eval takes it further. It can evaluate even expressions,


provided the input is a string
§ Using the example of a program that calculates the age of the
user. The following is the equivalent python program.

§ In the text editor window, to test your program you click the
run command.
Questions????

Subscribe to my YouTube Channel !!!


For more ICT lessons

Perlongs Computing

52

You might also like