0% found this document useful (0 votes)
10 views43 pages

Lec 01 - Intro and Basics (3)

Chapter One introduces Python as a high-level, interpreted, and object-oriented programming language that emphasizes readability and simplicity. It covers basic elements of Python, including control statements, data types, and syntax, while highlighting its features such as portability, ease of learning, and a broad standard library. The chapter also explains Python's interpretive nature, variable assignment, and key data structures like lists, tuples, and dictionaries.

Uploaded by

kalkidanasdro11
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views43 pages

Lec 01 - Intro and Basics (3)

Chapter One introduces Python as a high-level, interpreted, and object-oriented programming language that emphasizes readability and simplicity. It covers basic elements of Python, including control statements, data types, and syntax, while highlighting its features such as portability, ease of learning, and a broad standard library. The chapter also explains Python's interpretive nature, variable assignment, and key data structures like lists, tuples, and dictionaries.

Uploaded by

kalkidanasdro11
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 43

Chapter One

Python Basics
Contents
 Introduction:
 Basic elements of Python
 Control statements
 Boolean and conditional expressions
 the if, if…else statement,
 while loops, for loop, Nested loops, Infinite loops
Introduction
 Python is a high-level, interpreted, interactive and
object oriented-scripting language.
 A programming language that emphasize readable
code
 Combines power with clear syntax
 Interpreted not compiled
 Python was designed to be highly readable which
uses English keywords frequently where as other
languages use punctuation and it has fewer
syntactical constructions than other languages.
Cont..
 Python is Interpreted: This means that it is processed at
runtime by the interpreter and you do not need to compile your
program before executing it. This is similar to PERL and PHP.
 Python is Interactive: This means that you can actually sit at
a Python prompt and interact with the interpreter directly to
write your programs.
 Python is Object-Oriented: This means that Python supports
Object-Oriented style or technique of programming that
encapsulates code within objects.
 Python is Beginner's Language: Python is a great language
for the beginner programmers and supports the development of
a wide range of applications, from simple text processing to
WWW browsers to games.
Interpretive vs compiled languages
 Python is an interpretive language.
 This means that your code is not directly run by the
hardware. It is instead passed to a virtual machine, which is
just another program that reads and interprets your code. If
your code used the ‘+’ operation, this would be recognized
by the interpreter at run time, which would then call its own
internal function ‘add(a,b)’, which would then execute the
machine code ‘ADD’.
 This is in contrast to compiled languages, where your code is
translated into native machine instructions, which are then
directly executed by the hardware. Here, the ‘+’ in your code
would be translated directly in the ‘ADD’ machine code.
Cont..
 Many languages require you to compile (translate) your
program into a form that the machine understands.
Python Features
 Easy-to-learn: Python has relatively few keywords, simple
structure, and a clearly defined syntax.
 Easy-to-read: Python code is much more clearly defined and
visible to the eyes.
 Easy-to-maintain: Python's success is that its source code is
fairly easy-to-maintain.
 A broad standard library: One of Python's greatest strengths is
the bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
 Interactive Mode: Support for an interactive mode in which
you can enter results from a terminal right to the language,
allowing interactive testing and debugging of snippets of code.
Cont..
 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.
Advantages of Python?
 Because Python is an interpretive language, it has a
number of advantages:
 Automatic memory management.
 Expressivity and syntax that is ‘English’.
 Ease of programming.
 Minimises development time.
 Python also has a focus on importing modules, a feature
that makes it useful for scientific computing.
Python - Basic Syntax
 Interactive Mode Programming:
>>> print "Hello, Python!";
Hello, Python!
>>> 3+4*5;
23
Cont..
 Script Mode Programming :
 Invoking the interpreter with a script parameter begins
execution of the script and continues until the script is finished.
When the script is finished, the interpreter is no longer active.

 For example, put the following in one test.py, and run,


print "Hello, Python!";
print "I love COMP3050!";

 The output will be:


Hello, Python!
I love COMP3050!
Python 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.
Cont..
 Here are following identifier naming convention for
Python:
 Class names start with an uppercase letter and all other
identifiers with a lowercase letter.
 Starting an identifier with a single leading underscore
indicates by convention that the identifier is meant to be
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:
 Keywords contain lowercase letters only.
Lines and Indentation:
 One of the first caveats programmers encounter when learning
Python is the fact that there are 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. Both blocks in this example are fine:
if True:
print "Answer“;
print "True" ;
else:
print "Answer“;
print "False"
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. For
example:
total = item_one + \
item_two + \
item_three
 Statements contained within the [], {}, or () brackets do not
need to use the line continuation character. For example:
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Quotation 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 can be used to span the string across
multiple lines. For example, all the following are legal:
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is made
up of multiple lines and sentences."""
Comments in Python:
 A hash sign (#) that is not inside a string literal begins a
comment. All characters after the # and up to the
physical line end 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.
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:
import sys; x = 'foo'; sys.stdout.write(x + '\
n')
Multiple Statement Groups as Suites:
 Groups of individual statements making up a single code block are
called suites in Python.
Compound or complex statements, such as if, while, def, and class, are
those which 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.
if expression :
suite
elif expression :
suite
else :
suite
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 to Variables:
 Python variables do not have to be explicitly declared 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.
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print counter
print miles
print name
Multiple Assignment:
 You can also assign a single value to several variables
simultaneously. For example:
a = b = c = 1
a, b, c = 1, 2, "john"
Variable types
Cont..
Cont..
Arithmetic operators
A quick note on the increment operator
shorthand
Boolean operators
 Boolean operators are useful when making conditional
statements, we will cover these in-depth later.
 and
 or
 not
Comparison operators
Standard Data Types:
Python has five standard data types:
 Numbers
 String
 List
 Tuple
 Dictionary
Python Numbers:
 Number data types store numeric values. They are immutable data types,
which means that changing the value of a number data type results in a
newly allocated object.
 Number objects are created when you assign a value to them. For
example:
var1 = 1
var2 = 10
Python supports four different numerical types:
 int (signed integers)
 long (long integers [can also be represented in octal and hexadecimal])
 float (floating point real values)
 complex (complex numbers)
Number Examples:
Python Strings:
 Strings in Python are identified as a contiguous set of
characters in between 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.
Example:
str = 'Hello World!'
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 6th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string

Output:
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
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.
Cont..
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.
Con…
Python Dictionary:
 Python 's dictionaries are hash table type. They work like
associative arrays or hashes found in Perl and consist of
key-value pairs.
 Keys 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 ( [] ).
Con…
Question??
Thanks!

You might also like