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

L Python PDF

This document provides an introduction to programming with Python. It discusses Python's brief history and key features such as being scalable, object oriented, and functional from the beginning. The basics of Python are then covered, including printing output, using comments, following whitespace conventions, avoiding braces through proper indentation, and basic variable naming rules and data types. Numbers, strings, lists, tuples, and dictionaries are introduced as Python's fundamental data types.

Uploaded by

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

L Python PDF

This document provides an introduction to programming with Python. It discusses Python's brief history and key features such as being scalable, object oriented, and functional from the beginning. The basics of Python are then covered, including printing output, using comments, following whitespace conventions, avoiding braces through proper indentation, and basic variable naming rules and data types. Numbers, strings, lists, tuples, and dictionaries are introduced as Python's fundamental data types.

Uploaded by

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

Introduction to Programming

with Python

1
Brief History of Python
 Invented in the Netherlands, early 90s
by Guido van Rossum
 Named after Monty Python
 Open sourced from the beginning
 Considered a scripting language, but is
much more
 Scalable, object oriented and functional
from the beginning
 Used by Google from the beginning
 Increasingly popular
The Python tutorial is good!
The Basics
Hello World

•Open a terminal window and type “python”


•If on Windows open a Python IDE like IDLE
•At the prompt type ‘hello world!’

>>> 'hello world!'


'hello world!'
Python Overview

• Programs are composed of modules


• Modules contain statements
• Statements contain expressions
• Expressions create and process objects
The Python Interpreter
•Python is an interpreted
language >>> 3 + 7
•The interpreter provides an 10
interactive environment to >>> 3 < 15
play with the language True
>>> 'print me'
•Results of expressions are 'print me'
printed on the screen >>> print 'print me'
print me
interpret
>>>
source code output
Hello.py
print
 print : Produces text output on the console.

 Syntax:
print "Message"
print Expression
 Prints the given text message or expression value on the console, and
moves the cursor down to the next line.
print Item1, Item2, ..., ItemN
 Prints several messages and/or expressions on the same line.

 Examples:
print "Hello, world!"
age = 45
print "You have", 65 - age, "years until retirement"
Output:
Hello, world!
You have 20 years until retirement
8
Documentation

The ‘#’ starts a line comment

>>> 'this will print'


'this will print'
>>> #'this will not'
>>>
Whitespace
Whitespace is meaningful in Python: especially
indentation and placement of newlines
Use a newline to end a line of code
Use \ when must go to next line prematurely
No braces {} to mark blocks of code, use
consistent indentation instead
• First line with less indentation is outside of the block
• First line with more indentation starts a nested block
Colons start of a new block in many constructs,
e.g. function definitions, then clauses
No Braces
• Python uses indentation instead of braces to determine
the scope of expressions
• All lines must be indented the same amount to be part
of the scope (or indented more if part of an inner
scope)
• This forces the programmer to use proper indentation
since the indenting is part of the program!
Lines and Indentation

• Python provides 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. For example −

if True:
print "True"
else:
print "False“
However, the following block generates an error −
• if True: print "Answer" print "True" else: print "Answer" print "False"
Naming Rules
• Names are case sensitive and cannot start with a
number. They can contain letters, numbers, and
underscores.
bob Bob _bob _2_bob_ bob_2 BoB
• There are some reserved words:
and, assert, break, class, continue,
def, del, elif, else, except, exec,
finally, for, from, global, if,
import, in, is, lambda, not, or,
pass, print, raise, return, try,
while
Naming conventions
The Python community has these recommend-ed
naming conventions
•joined_lower for functions, methods and, attributes
•joined_lower or ALL_CAPS for constants
•StudlyCaps for classes
•camelCase only to conform to pre-existing
conventions
•Attributes: interface, _internal, __private
Variables
• Are not declared, just assigned
• The variable is created the first time you assign it
a value
• Are references to objects
• Type information is with the object, not the
reference
• Everything in Python is an object
Variables
 Syntax:

name = value >>> x = 7


>>> x
 Examples: x = 5
gpa = 3.14
7
>>> x = 'hello'
x 5 gpa 3.14 >>> x
'hello'
A variable that has been given a >>>
value can be used in expressions.
x + 4 is 9
• Data type is a property of the object
and not of the variable
Data types
• Python has five standard data types −
• Numbers
• String
• List
• Tuple
• Dictionary
Numbers
• Python supports four different numerical types −
• int (signed integers)
• long (long integers, they can also be represented in
octal and hexadecimal)
• float (floating point real values)
• complex (complex numbers)
int long float complex
10 51924361L 0.0 3.14j
Basic Datatypes
• Integers (default for numbers)
z = 5 / 2 # Answer 2, integer division in python 2
• Floats
x = 3.456
Numbers: Integers
• Integer – the equivalent of
a C long >>> 132224
• Long Integer – an 132224
unbounded integer value. >>> 132323 ** 2
17509376329L
>>>
Numbers: Floating Point
• int(x) converts x to an >>> 1.23232
integer 1.2323200000000001
>>> print 1.23232
• float(x) converts x to a 1.23232
floating point >>> 1.3E7
• The interpreter shows 13000000.0
>>> int(2.0)
a lot of digits
2
>>> float(2)
2.0
Numbers: Complex
• Built into Python
• Same operations are >>> x = 3 + 2j
supported as integer and >>> y = -1j
>>> x + y
float
(3+1j)
>>> x * y
(2-3j)
Assignment
 You can assign to multiple names at the
same time
>>> x, y = 2, 3
>>> x
2
>>> y
3
This makes it easy to swap values
>>> x, y = y, x
 Assignments can be chained
>>> a = b = x = 2
String Literals
 Strings are immutable
 There is no char type like in C++ or Java
 + is overloaded to do concatenation
 Strings
• Can use “” or ‘’ to specify with “abc” == ‘abc’
• Unmatched can occur within the string: “matt’s”
• Use triple double-quotes for multi-line strings or strings than
contain both ‘ and “ inside of them:
“““a‘b“c”””

>>> x = 'hello'
>>> x = x + ' there'
>>> x
'hello there'
Strings
 string: A sequence of text characters in a program.
 Strings start and end with quotation mark " or apostrophe ' characters.
 Examples:
"hello"
"This is a string"
"This, too, is a string. It can be very long!"

 A string may not span across multiple lines or contain a " character.
"This is not
a legal String."
"This is not a "legal" String either."

 A string can represent characters by preceding them with a backslash.


 \t tab character
 \n new line character
 \" quotation mark character
 \\ backslash character

 Example: "Hello\tthere\nHow are you?"

25
Indexes
 Characters in a string are numbered with indexes starting at 0:
 Example:
name = "P. Diddy"
index 0 1 2 3 4 5 6 7
character P . D i d d y >>> s = '012345'
>>> s[3]
'3'
 Accessing an individual character of a string: >>> s[1:4]
variableName [ index ]
'123'
 Example: >>> s[2:]
print name, "starts with", name[0] '2345'
Output: >>> s[:4]
P. Diddy starts with P '0123'
>>> s[-2]
'4'
26
String properties
 len(string) - number of characters in a string
(including spaces)
 str.lower(string) - lowercase version of a string
 str.upper(string) - uppercase version of a string

 Example:
name = "Martin Douglas Stepp"
length = len(name)
big_name = str.upper(name)
print big_name, "has", length, "characters"

Output:
MARTIN DOUGLAS STEPP has 20 characters

27
List
• Compound data types.
• A list contains items separated bycommas
and enclosed within square brackets []..
• items belonging to a list can be of different
data type.
List Example
• list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
• tinylist = [123, 'john']
• print list # Prints complete list
• ['abcd', 786, 2.23, 'john', 70.200000000000003]
• print list[0] # Prints first element of the list
• abcd
• print list[1:3] # Prints elements starting from 2nd till 3rd
• [786, 2.23]
• print list[2:] # Prints elements starting from 3rd element
• [2.23, 'john', 70.200000000000003]
• print tinylist * 2 # Prints list two times print
• [123, 'john', 123, 'john']
• print list + tinylist # Prints concatenated lists
• ['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']
Tuples
• Another sequence data type that is similar to
the list.
• A tuple consists of a number of values
separated by commas.
• 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.
List vs Tuple
• tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
• list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]

• tuple[2] = 1000 # Invalid syntax with tuple

• list[2] = 1000 # Valid syntax with list


Dictionaries
• tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

• print tinydict
– # Prints com plete dictionary

• print tinydict.keys()
– # Prints all the keys

• print tinydict.values()
– # Prints all the values
Dictionary Example
>>> s={'a' : 1 , 'b' :2}
>>> s.keys()
dict_keys(['b', 'a'])
>>> s.values()
dict_values([2, 1])
>>> s['a']
1
Data Type Summary

• Integers: 2323, 3234L


• Floating Point: 32.3, 3.1E2
• Complex: 3 + 2j, 1j
• Lists: l = [ 1,2,3]
• Tuples: t = (1,2,3)
• Dictionaries: d = {‘hello’ : ‘there’, 2 : 15}
Expressions
• expression: A data value or set of operations to compute a
value.
Examples: 1 + 4 * 3
42

• Arithmetic operators we will use:


• + - * / addition, subtraction/negation, multiplication, division
– % modulus, a.k.a. remainder
– ** exponentiation
• precedence: Order in which operations are computed.

– * / % ** have a higher precedence than + -


1 + 3 * 4 is 13

– Parentheses can be used to force a certain order of evaluation.


35
(1 + 3) * 4 is 16
Python language supports the
following types of operators.
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Logic
• Many logical expressions use relational
operators:
Operator Meaning Example Result
== equals 1 + 1 == 2 True
!= does not equal 3.2 != 2.5 True
< less than 10 < 5 False
> greater than 10 > 5 True
<= less than or equal to 126 <= 100 False
>= greater than or equal to 5.0 >= 5.0 True

• Logical expressions can be combined with


logical operators: Operator Example Result
and 9 != 6 and 2 < 3 True
or 2 == 3 or -1 < 5 True
not not 7 > 0 False
37
User Input
• The input(string) method returns a line of user
input as a string
• The parameter is used as a prompt
• The string can be converted by using the
conversion methods int(string), float(string), etc.
Input: Example
print "What's your name?"
name = input("> ")

print "What year were you born?"


birthyear = int(input("> "))

print ("Hi”,name, “! You are”, 2016-birthyear, “years old!”)


~: python input.py
What's your name?
> Michael
What year were you born?
>1980
Hi Michael! You are 31 years old!
input
 input : Reads a number from user input.
 You can assign (store) the result of input into a variable.
 Example:
age = input("How old are you? ")
print "Your age is", age
print "You have", 65 - age, "years until retirement"
Output:
How old are you? 53
Your age is 53
You have 12 years until retirement

40
Control Flow: if
 if statement: Executes a group of statements only if a certain
condition is true. Otherwise, the statements are skipped.
 Syntax:
if condition:
statements

 Example:
gpa = 3.4
if gpa > 2.0:
print "Your application is accepted."

41
if/else
 if/else statement: Executes one block of statements if a certain
condition is True, and a second block of statements if it is False.
 Syntax:
if condition:
statements
else:
statements

 Example:
gpa = 1.4
if gpa > 2.0:
print "Welcome to Mars University!"
else:
print "Your application is denied."

 Multiple conditions can be chained with elif ("else if"):


if condition:
statements
elif condition:
statements
else:
statements
42
Control Flow: If Statements
import math
x = 30
if x <= 15 : >>> import ifstatement
y = x + 15 y = 0.999911860107
elif x <= 30 : >>>
y = x + 30 In interpreter
else :
y=x
print ‘y = ‘,
print math.sin(y)

In file ifstatement.py
Range Test

if (3 <= Time <= 5):


print “Office Hour“

Or
if(Time>=3 and Time<=5)
A Code Sample (in IDLE)
x = 34 - 23 # A comment.
y = “Hello” # Another one.
z = 3.45
if z == 3.45 or y == “Hello”:
x=x+1
y = y + “ World” # String concat.
print x
print y
while
 while loop: Executes a group of statements as long as a condition is True.
 good for indefinite loops (repeat an unknown number of times)

 Syntax:
while condition:
statements

 Example:
number = 1
while number < 200:
print number,
number = number * 2

 Output:
1 2 4 8 16 32 64 128

46
While Loops
>>> import whileloop
x=1 1
while x < 10 : 2
print x 3
x=x+1 4
5
6
In whileloop.py
7
8
9
>>>
In interpreter
The Loop Else Clause
• The optional else clause runs only if the loop exits
normally (not by break)

x=1
~: python whileelse.py
while x < 3 : 1
print x 2
x=x+1 hello
else: Run from the command line
print 'hello'
In whileelse.py
The Loop Else Clause

x=1
while x < 5 :
print x
x=x+1 ~: python whileelse2.py
break 1
else :
print 'i got here'

whileelse2.py
For Loop
for letter in 'Python': # First Example
print 'Current Letter :', letter

fruits = ['banana', 'apple', 'mango']


for fruit in fruits: # Second Example print
'Current fruit :', fruit

for num in range(10,20):


#to iterate between 10 to 20
Even numbers
n = int(input("Enter a number: "))
print("List of Even numbers is")
for i in range(1,n):
if (i%2 ==0) :
print(i)
factorial
fact =1
i=1
n=int(input("Enter a number: "))

while i<=n :
fact=fact*i
i=i+1
else:
print("Factorial of ", n, " is ", fact)

You might also like