Developed by Guido Van Rossum

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 56

Developed by Guido van Rossum

Python is the language of the Python Interpreter


and those who can converse with it. An
individual who can speak Python is known as a
Pythonista. It is a very uncommon skill, and
may be hereditary. Nearly all known
Pythonistas use software initially developed
by Guido van Rossum.
Part- I
Installation
• Install Python - Windows 8
• Using Python - Macintosh
• Using Python on a Raspberry Pi/Linux/Ubuntu
Install Python - Windows 8
• First download and install a program editor
– Nodepad++
• Download Python suitable to your machine
architecture from
https://www.python.org/downloads/
– You can choose Python 2 or 3. (Slightly different)
– For this classes I will use Python 2.7.6 to
demonstrate examples.
Using Python- Windows 8
• Write a Python Script using Nodepad++

• Running Python Script


– by clicking on Hello.py Script.
– open the command prompt and change to the directory of
Hello.py
– type Hello.py and press Enter .
Using Python - Macintosh
• Download TextWrangler from
http://www.barebones.com/products/textwra
ngler/
• Drag the TextWrangler into Applications
• Run TextWrangler and write
Python code.
Using Python - Macintosh
• Run Python Script, now there’s couple of way
to do it.
– Built-in a way in TextWrangler

– Running from Terminal, open the terminal and


change to the directory of Python Script.
– Write “python ScriptName.py” in the Terminal.
Using Python on a Raspberry
Pi/Linux/Ubuntu
• All needed things are already there no need to
download and install anything.
• Open editor and write a Python Script.

• Run the Python Script.


– Run from terminal

• Open the terminal and change to python script directory and type
“python scriptname.py”
Part-II
Let Us Start Python
• Computers are built for one purpose - to do things for us.
• Computers can be given sets of instructions in human readable
languages that can be translated into the computer's native binary
language.
• Computers do not execute source code, which is made up of
language human programmers can understand.
• Python is one of those languages. Python is a way of giving a sets of
instructions to Python Interpreter in order to solve a problem.
• Python Interpreter translates a Python code into the computer’s
native binary language.
• Python was developed by Guido van Rossum, who was inspired by 
The Monty Python's Flying Circus skits for the name.
Talking to Python
• We can talk to Python Interpreter in two ways
– Interactive mode
• You type directly to Python one line at a time and it responds
•  to test short snippets of code ( Can use bundled development environment called IDLE.)
– Write Python Scripts and run them
• You enter a sequence of statements (lines) into a file using a text editor and tell Python to
execute the statements in the file

• Use quit() to end the interactive session.


Elements of Python
• Vocabulary / Words – Variables and Reserved
words
• Sentence structure - valid syntax patterns
• Story structure - constructing a program for a
purpose
Constants
• Fixed values such as numbers, letters, and
strings are called constants because their
value does not change
• Numeric constants are used as you expect
• String contants use single quotes (‘) or double quotes
(“)
Variables
• A variable is name given to a memory location
where a programmer can store the data and
later retrieve the data using the variable
name.
• Programmers get to choose the names of the
variables.
• Programmer can change the contents of a
variable in a later statement.
Python Variable Name Rules
• Must start with a letter or underscore (_)
• May consists of letters, numbers, and
underscores
• Case Sensitive
• Should use Mnemonic Variable Names
– We name variables to help us remember what we
intend to store in them
Good: spam eggs spam23 _speed
Bad: 23spam #sign var.12
Different: spam Spam SPAM
Reserved Words/Keywords
• Cannot be used as a variable names.
• 33 keywords.
• All the keywords except True, False and None
are in lowercase and they must be written as it
is.
Sentences or Lines or Statements
>>> x = 4 (Assignment statement)
>>> x = x + 2 (Assignment statement with an
expression)
>>> print x (Print Statement)

Variable Operator Constant Reserved Word


Assignment Statements
• We assign a value to a variable using the
assignment statement (=)
• An assignment statement consists of an
expression on the right-hand side and a
variable to store the result
>>> x = 45 * x * (1-x)
variable expression
Numeric Expressions
Order of Evaluation
• When we string operators together - Python must
know which one to do first
– Parenthesis are always respected
– Exponentiation (raise to a power)
– Multiplication, Division, and Remainder
– addition and Subtraction
– Left to right (equal precedence)
• When writing code - use parenthesis
• When writing code - keep mathematical expressions
simple enough that they are easy to understand
Python Integer Division is Weird!
• Integer division truncates
• Floating point division produces floating point
numbers

• This changes in Python 3.0


Mixing Integer and Floating
• The integer is converted to a floating point
before the operation
Other Operators
• Comparison Operators (<> not equal to)
• Assignment Operators
• Bitwise Operators
• Logical Operators
– (a and b)
– (a or b)
– not(a and b)

Other Operators
• Membership Operators
– in
• Evaluates to true if it finds a variable in the specified sequence and false otherwise.
– not in
• Evaluates to true if it does not finds a variable in the specified sequence and false
otherwise.
>>>a=20
>>>list = [1, 2, 3, 4, 5 ];
>>> if ( a in list ):
print "Line 1 - a is available in the given list“
>>> else:
print "Line 1 - a is not available in the given list“
Output: Line 1 - a is not available in the given list
Other Operators
• Identity Operators
– Identity operators compare the memory locations
of two objects. There are two Identity operators as
explained below
– is
• Evaluates to true if the variables on either side of the
operator point to the same object and false otherwise.
– is not
• Evaluates to false if the variables on either side of the
operator point to the same object and true otherwise.
Identity Operators
What does “Type” Mean?
• In Python variables, literals and constants have
a “type”
• Python knows the difference between an
integer number and a string
• For example “+” means “addition” if
something is a number and “concatenate” if
something is a string
Type Matters
• Python knows what “type” everything is
• Some operations are prohibited
• You cannot “add 1” to a string
• We can ask Python what type something is by
using the type() function
Type Conversions
• When you put an integer and floating point in
an expression, the integer is implicitly
converted to a float
• You can control this with the built-in functions
int() and float()
String
Conversions
• You can also use int() • You will get an error
and float() to convert if the string does not
between strings and contain numeric
integers characters
User Input
• We can instruct • The raw_input()
Python to pause and function returns a
read data from the string
user using the
raw_input() function
Converting User Input
• If we want to read a • Later we will deal
number from the with bad input data
user, we must
convert it from a
string to a number
using a type
conversion function
Comments in Python
• Anything after a # is ignored by Python
• Why comment?
– Describe what is going to happen in a sequence of
code
– Document who wrote the code or other ancillary
information
– Turn off a line of code - perhaps temporarily
String Operations
• Some operators apply to strings
– + implies “concatenation”
– * implies “multiple concatenation”
• Python knows when it is dealing with a string
or a number and behaves appropriately
Program Steps or Program Flow
• Like a recipe, a program is a sequence of steps to
be done in order.
• Some steps are conditional - they may be
skipped.
• Sometimes a step or group of steps are to be
repeated. (loops)
• Sometimes we store a set of steps to be used
over and over as needed several places
throughout the program (functions)
Sequential Steps
Conditional Steps
Indentation
• Increase indent after an if statement or for
statement (after : )
• Maintain indent to indicate the scope of the
block (which lines are affected by the if/for)
• Decrease to indicate end of block
• Blank lines and comments are ignored - they
do not affect indentation
Warning: Turn Off Tabs!!
• Most text editors can turn tabs into spaces -
make sure to enable this feature
– NotePad++: Settings -> Preferences -> Language
Menu/Tab Settings
– TextWrangler: TextWrangler -> Preferences -> Editor
Defaults
• Python cares a *lot* about how far a line is
indented. If you mix tabs and spaces, you may get
“indentation errors” even if everything looks fine
Warning: Turn Off Tabs!!
Comparison Operators
• Boolean expressions using comparison
operators evaluate to - True / False - Yes / No
Nested Decisions
>>>x = 42
>>>if x > 1 :
print 'More than one'
if x < 100 :
print 'Less than 100'
>>>print 'All done'
One vs. Two vs. Multi way decisions
The try / except Structure
• Surround a dangerous section of code with try
and except
– If the code in the try works - the except is skipped
– If the code in the try fails - it jumps to the except
section
>>>astr = 'Hello Bob'
>>>try:
istr = int(astr)
>>>except:
istr = -1
Loops

• Iterate until a condition evaluates to False.


• Iterate through a list of values
Break
Continue
Loop Examples
Loop Examples
Loop Examples
Loop Examples
Loop Examples
Functions
• Built-in functions- input(), type(), int().
• User defined functions.
• In Python a function is some reusable code that takes argument(s)
as input does some computation and then return a result(s).
• We define function using def keyword.
• We call/invoke function by using the function name, parenthesis
and arguments in an expression.

>>>big =max(‘Hello World’);


>>> print big
‘w’
Functions
Parameters and return values
Python List
Basic List Operations

Python Expression Results Description


len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', Repetition
'Hi!']
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: 123 Iteration
print x,

You might also like