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

Introduction To Python

Python is a simple, easy to learn, open source, and interpreted programming language. It has a simple syntax that resembles English, making code easy to read. Python supports both procedural and object-oriented programming. It has a large standard library and is highly extensible. Python code can be run in interactive mode line-by-line or by executing script files with a .py extension. The language uses indentation rather than brackets to denote code blocks.

Uploaded by

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

Introduction To Python

Python is a simple, easy to learn, open source, and interpreted programming language. It has a simple syntax that resembles English, making code easy to read. Python supports both procedural and object-oriented programming. It has a large standard library and is highly extensible. Python code can be run in interactive mode line-by-line or by executing script files with a .py extension. The language uses indentation rather than brackets to denote code blocks.

Uploaded by

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

Introduction to Python

Why Python?
• Simple
• Python is a simple and minimalistic language in nature
• Reading a good python program should be like reading English
• Its Pseudo-code nature allows one to concentrate on the problem rather than the language
• Easy to Learn
• Free & Open source
• Freely distributed and Open source
• Maintained by the Python community
• High Level Language –memory management
• Portable – *runs on anything c code will

2
• Interpreted
• You run the program straight from the source code.
• Python program →Bytecode →a platforms native language
• You can just copy over your code to another system and it will auto-magically work! *with python
platform
• Object-Oriented
• Simple and additionally supports procedural programming
• Extensible – easily import other code
• Embeddable –easily place your code in non-python programs
• Extensive libraries
• (i.e. reg. expressions, doc generation, CGI, ftp, web browsers, ZIP, WAV, cryptography, etc...)
(wxPython, Twisted, Python Imaging library)

3
How to use Python?
• Python can be used in Interactive Mode and Script Mode
• Interactive:
• Type directly to a python one line at a time and it responds
• Script:
• You enter a sequence of statements (lines) into a file using a text editor and tell Python to
execute the statements in the file
• Interactive Python is good for experiments and programs of 3-4 lines long
• Most programs are much longer, so we type them into a file(called as
Python Script) and tell Python to run the commands in the file.
• As a convention, we add “.py” as the suffix on the end of these files to
indicate they contain Python
Python Scripts
• When you call a python program from the command line the
interpreter evaluates each expression in the file
• Familiar mechanisms are used to provide command line arguments
and/or redirect input and output
• Python also has mechanisms to allow a python program to act both
as a script and as a module to be imported and used by another
python program
Reserved Words
You cannot use reserved words as variable names / identifiers

False class return is finally


None if for lambda continue
True def from while nonlocal
and del global not with
as elif try or yield
assert else import pass
break except in raise
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
Enough to Understand the Code
• Indentation matters to code meaning
• Block structure indicated by indentation
• First assignment to a variable creates it
• Variable types don’t need to be declared.
• Python figures out the variable types on its own.
• Assignment is = and comparison is ==
• For numbers + - * / % are as expected
• Special use of + for string concatenation and % for
string formatting (as in C’s printf)
• Logical operators are words (and, or,
not) not symbols
• The basic printing command is print
Basic Datatypes
• Integers (default for numbers)
z = 5 / 2 # Answer 2, integer division
• Floats
x = 3.456
• 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”””
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
Comments
• Start comments with #, rest of line is ignored
• Can include a “documentation string” as the
first line of a new function or class you define
• Development environments, debugger, and
other tools use it: it’s good style to include one
def fact(n):
“““fact(n) assumes n is a positive
integer and returns facorial of n.”””
assert(n>0)
return 1 if n==1 else n*fact(n-1)
Assignment
• Binding a variable in Python means setting a name to hold a reference to
some object
• Assignment creates references, not copies
• Names in Python do not have an intrinsic type, objects have types
• Python determines the type of the reference automatically based on what data is
assigned to it
• You create a name the first time it appears on the left side of an
assignment expression:
x = 3
• A reference is deleted via garbage collection after any names bound to it
have passed out of scope
• Python uses reference semantics (more later)
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
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
Accessing Non-Existent Name
Accessing a name before it’s been properly
created (by placing it on the left side of an
assignment), raises an error
>>> y

Traceback (most recent call last):


File "<pyshell#16>", line 1, in -toplevel-
y
NameError: name ‘y' is not defined
>>> y = 3
>>> y
3
Variables
• A variable is a named place in the memory where a programmer can store
data and later retrieve the data using the variable “name”

• Programmers get to choose the names of the variables

• You can change the contents of a variable in a later statement

x = 12.2 x 12.2 100


y = 14
x = 100 y 14
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 = 3.9 * x * ( 1 - x )
A variable is a memory location x 0.6
used to store a value (0.6)

0.6 0.6
x = 3.9 * x * ( 1 - x )

0.4

The right side is an expression.


0.936
Once the expression is evaluated, the
result is placed in (assigned to) x.
A variable is a memory location used to
store a value. The value stored in a x 0.6 0.936
variable can be updated by replacing the
old value (0.6) with a new value (0.936).
0.6 0.6
x = 3.9 * x * ( 1 - x )

0.4
The right side is an expression. Once the
expression is evaluated, the result is
placed in (assigned to) the variable on the
0.936
left side (i.e., x).
Python types
• Str, unicode – ‘MyString’, u‘MyString’
• List – [ 69, 6.9, ‘mystring’, True]
• Tuple – (69, 6.9, ‘mystring’, True) immutable
• Set/frozenset – set([69, 6.9, ‘str’, True])
frozenset([69, 6.9, ‘str’, True]) –no duplicates & unordered
• Dictionary or hash – {‘key 1’: 6.9, ‘key2’: False} - group of key
and value pairs

12/13/2019 CS 331 21
Python types
• Int – 42- may be transparently expanded to long through
438324932L
• Float – 2.171892
• Complex – 4 + 3j
• Bool – True of False

12/13/2019 CS 331 22
What Does “Type” Mean?
• In Python variables, literals, and
constants have a “type” >>> ddd = 1 + 4
>>> print(ddd)
• Python knows the difference between 5
an integer number and a string >>> eee = 'hello ' + 'there'
>>> print(eee)
hello there
• For example “+” means “addition” if
something is a number and
“concatenate” if something is a string
concatenate = put together
Type Matters
• Python knows what “type” >>> eee = 'hello ' + 'there'
>>> eee = eee + 1
everything is
Traceback (most recent call last):
File "<stdin>", line 1, in
• Some operations are <module>TypeError: Can't convert
prohibited 'int' object to str implicitly
>>> type(eee)
• You cannot “add 1” to a string <class'str'>
>>> type('hello')
<class'str'>
• We can ask Python what type >>> type(1)
something is by using the <class'int'>
type() function >>>
Several Types of Numbers
>>> xx = 1
• Numbers have two main types >>> type (xx)
<class 'int'>
- Integers are whole numbers:
>>> temp = 98.6
-14, -2, 0, 1, 100, 401233 >>> type(temp)
<class'float'>
- Floating Point Numbers have
>>> type(1)
decimal parts: -2.5 , 0.0, 98.6, 14.0 <class 'int'>
>>> type(1.0)
• There are other number types - they
<class'float'>
are variations on float and integer
>>>
Type Conversions
>>> print(float(99) + 100)
199.0
• When you put an integer and >>> i = 42
floating point in an >>> type(i)
expression, the integer is <class'int'>
implicitly converted to a float >>> f = float(i)
>>> print(f)
• You can control this with the 42.0
>>> type(f)
built-in functions int() and
<class'float'>
float()
>>>
• For other data types (lists, dictionaries, user-defined types), assignment
works differently.
• These datatypes are “mutable.”
• When we change these data, we do it in place.
• We don’t copy them into a new memory address each time.
• If we type y=x and then modify y, both x and y are changed.

immutable mutable

>>> x = 3 x = some mutable object


>>> y = x y = x
>>> y = 4 make a change to y
>>> print x look at x
3 x will be changed as well
Garbage Collection
• Interestingly, as a Python programmer you do not have to worry about
computer memory getting filled up with old values when new values
are assigned to variables
After
Memory location
• Python will automatically clear old
values out of memory in a process x 2 X will be automatically
reclaimed by the
known as garbage collection garbage collector
2.3
Assigning Input
• So far, we have been using values specified by programmers and printed
or assigned to variables
• How can we let users (not programmers) input values?

• In Python, input is accomplished via an assignment statement


combined with a built-in function called input
<variable> = input(<prompt>)
• When Python encounters a call to input, it prints <prompt> (which is a
string literal) then pauses and waits for the user to type some text and
press the <Enter> key
Assigning Input
• Here is a sample interaction with the Python interpreter:

>>> name = input("Enter your name: ")


Enter your name: Mohammad Hammoud
>>> name
'Mohammad Hammoud'
>>>

• Notice that whatever the user types is then stored as a string


• What happens if the user inputs a number?
Assigning Input
• Here is a sample interaction with the Python interpreter:

>>> number = input("Enter a number: ")


Enter a number: 3
>>> number
Still a string! '3'
>>>

• How can we force an input number to be stored as a number and not as


a string?
• We can use the built-in eval function, which can be “wrapped around” the
input function
Assigning Input
• Here is a sample interaction with the Python interpreter:

>>> number = eval(input("Enter a


number: "))
Enter a number: 3
>>> number
Now an int
3
(no single quotes)!
>>>
Assigning Input
• Here is a sample interaction with the Python interpreter:

>>> number = eval(input("Enter a


number: "))
Enter a number: 3.7
>>> number
And now a float
3.7
(no single quotes)!
>>>
Assigning Input
• Here is another sample interaction with the Python interpreter:

>>> number = eval(input("Enter an equation: "))


Enter an equation: 3 + 2
>>> number
5
>>>

The eval function will evaluate this formula and


return a value, which is then assigned to the variable “number”
Datatype Conversion
• Besides, we can convert the string output of the input function into an
integer or a float using the built-in int and float functions
>>> number = int(input("Enter a number: "))
Enter a number: 3
>>> number
An integer
3
(no single quotes)!
>>>
Datatype Conversion
• Besides, we can convert the string output of the input function into an
integer or a float using the built-in int and float functions
>>> number = float(input("Enter a number: "))
Enter a number: 3.7
>>> number
A float
3.7
(no single quotes)!
>>>
Datatype Conversion
• As a matter of fact, we can do various kinds of conversions between
strings, integers and floats using the built-in int, float, and str functions
>>> x = 10 >>> y = "20" >>> z = 30.0
>>> float(x) >>> float(y) >>> int(z)
10.0 20.0 30
>>> str(x) >>> int(y) >>> str(z)
'10' 20 '30.0'
>>> >>> >>>

integer ➔ float string ➔ float float ➔ integer


integer ➔ string string ➔ integer float ➔ string
Simultaneous Assignment
• Python allows us also to assign multiple values to multiple variables all
at the same time
>>> x, y = 2, 3
>>> x
2
>>> y
3
>>>

• This form of assignment might seem strange at first, but it can prove
remarkably useful (e.g., for swapping values)
Simultaneous Assignment
• Suppose you have two variables x and y, and you want to swap their
values (i.e., you want the value stored in x to be in y and vice versa)

>>> x = 2
>>> y = 3
>>> x = y
>>> y = x
>>> x X CANNOT be done with
two simple assignments
3
>>> y
3
Simultaneous Assignment
• Suppose you have two variables x and y, and you want to swap their
values (i.e., you want the value stored in x to be in y and vice versa)
>>> x = 2
Thus far, we have been using >>> y = 3
different names for >>> temp = x CAN be done with
variables. These names >>> x = y three simple assignments,
are technically called
identifiers
>>> y = temp
>>> x
✓ but more efficiently with
simultaneous assignment
3
>>> y
2
>>>
Arithmetic Operators
Relational Operators
Logical Operators
Identity Operators
Membership Operators
Bitwise Operators
Order of Evaluation
• When we string operators together - Python must know which one
to do first

• This is called “operator precedence”

• Which operator “takes precedence” over the others?

x = 1 + 2 * 3 - 4 / 5 ** 6
Used Functions/Operators Today

You might also like