0% found this document useful (0 votes)
14 views56 pages

Py Slides 1

Python is a high-level, interpreted, interactive, and object-oriented scripting language designed for readability and ease of use, making it suitable for beginners. It supports various programming paradigms and features such as cross-platform compatibility, extensibility, and a rich set of libraries for different applications. The document also covers Python's basic syntax, variable types, operators, and standard data types, providing a comprehensive overview for new programmers.

Uploaded by

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

Py Slides 1

Python is a high-level, interpreted, interactive, and object-oriented scripting language designed for readability and ease of use, making it suitable for beginners. It supports various programming paradigms and features such as cross-platform compatibility, extensibility, and a rich set of libraries for different applications. The document also covers Python's basic syntax, variable types, operators, and standard data types, providing a comprehensive overview for new programmers.

Uploaded by

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

1.

Python Overview
• Python is a high-level, interpreted, interactive and object
oriented-scripting language.

• 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.
• 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.
Compiling and interpreting
• Many languages require you to compile (translate) your
program into a form that the machine understands.
compile execute
source code byte code output
Hello.java Hello.class

• Python is instead directly interpreted into machine


instructions.
interpret
source code output
Hello.py
History of Python:
• Python was developed by Guido van Rossum in the late
eighties and early nineties at the National Research
Institute for Mathematics and Computer Science in the
Netherlands.
• Python is derived from many other languages, including
ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell
and other scripting languages.
• Python is copyrighted, Like Perl, Python source code is now
available under the GNU General Public License (GPL).
• Python is now maintained by a core development team at
the institute, although Guido van Rossum still holds a vital
role in directing it's progress.
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.

• Cross-platform compatibility: Python is compatible with


multiple operating systems (UNIX, Windows, and
Macintosh)
Python Features (cont’d)

• Portable: Python code can run on different operating


systems without needing major changes.

• 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 provides libraries and tools


that allow developers to create these GUI applications
2. Python - Basic Syntax
• Interactive Mode Programming:
>>> print "Hello, Python!";
Hello, Python!
>>> 3+4*5;
23
• 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).
• Example: myVariable, _myVar, _value, X, var_1, x123,
my_variable
• 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.
Python Identifiers (cont’d)

No reserved words (keywords):


• Python keywords (like, if, while, for, class etc ) cannot be
used as identifiers because they have special meaning in
Python. These are reserved by Python for its syntax.

Cannot contain spaces:


• Identifiers cannot have spaces between characters.
Instead, use underscores (_) to separate words (e.g.,
my_variable)
Reserved Words:

Keywords contain lowercase letters


only.
and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
Lines and Indentation:
• A common challenge for new Python programmers is that,
unlike other languages, Python doesn't use braces {} to
define blocks of code. Instead, it relies on indentation to
mark code blocks, and this indentation must be consistent
throughout the program.
• 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
total = 1 + 2 + 3 + \
4+5+6
print(total)
• 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:

• Single-Line Comments:
• Single-line comments begin with the # Symbol
• # This is a single-line comment
• x = 10 # This is an inline comment

• Multi-Line Comments
• ‘’’ or “”” are often used for block comments
• """
• This is a multi-line comment
• using triple quotes.
• It spans multiple lines.
• """
Using Blank Lines:

• Separating Functions or Classes:


• Blank lines are commonly used to separate different functions,
methods, or class definitions
• def greet():
• print("Hello, World!")

• def farewell():
• print("Goodbye, World!")

• Separating Code Blocks:


• result = x + y

– if result > 15:


– print("Result is greater than 15")
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')
3. Python - Variable Types

• 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"
4. Python - Basic Operators
Python language supports following type of operators.
• Arithmetic Operators
• Comparision Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators
Python Arithmetic Operators:

Operator Description Example


+ Addition - Adds values on either side of the a + b will give 30
operator
- Subtraction - Subtracts right hand operand a - b will give -10
from left hand operand
* Multiplication - Multiplies values on either a * b will give 200
side of the operator
/ Division - Divides left hand operand by right b / a will give 2
hand operand
% Modulus - Divides left hand operand by b % a will give 0
right hand operand and returns remainder
** Exponent - Performs exponential (power) a**b will give 10 to the
calculation on operators power 20
// Floor Division - The division of operands 9//2 is equal to 4 and
where the result is the quotient in which 9.0//2.0 is equal to 4.0
the digits after the decimal point are
removed.
Python Comparison Operators:
Operato
Description Example
r
== Checks if the value of two operands are equal or not, if (a == b) is not true.
yes then condition becomes true.
!= Checks if the value of two operands are equal or not, if (a != b) is true.
values are not equal then condition becomes true.
<> Checks if the value of two operands are equal or not, if (a <> b) is true. This is
values are not equal then condition becomes true. similar to != operator.
> Checks if the value of left operand is greater than the (a > b) is not true.
value of right operand, if yes then condition becomes
true.
< Checks if the value of left operand is less than the (a < b) is true.
value of right operand, if yes then condition becomes
true.
>= Checks if the value of left operand is greater than or (a >= b) is not true.
equal to the value of right operand, if yes then
condition becomes true.
<= Checks if the value of left operand is less than or equal (a <= b) is true.
to the value of right operand, if yes then condition
becomes true.
Python Assignment Operators:
Operato
Description Example
r
= Simple assignment operator, Assigns values from right c = a + b will
side operands to left side operand assigne value of a +
b into c
+= Add AND assignment operator, It adds right operand to c += a is equivalent
the left operand and assign the result to left operand to c = c + a
-= Subtract AND assignment operator, It subtracts right c -= a is equivalent
operand from the left operand and assign the result to left to c = c - a
operand
*= Multiply AND assignment operator, It multiplies right c *= a is equivalent
operand with the left operand and assign the result to left to c = c * a
operand
/= Divide AND assignment operator, It divides left operand c /= a is equivalent
with the right operand and assign the result to left to c = c / a
operand
%= Modulus AND assignment operator, It takes modulus c %= a is equivalent
using two operands and assign the result to left operand to c = c % a
**= Exponent AND assignment operator, Performs c **= a is equivalent
exponential (power) calculation on operators and assign to c = c ** a
value to the left operand
//= Floor Division and assigns a value, Performs floor division c //= a is equivalent
on operators and assign value to the left operand to c = c // a
Python Bitwise Operators:

Operat
Description Example
or
& Binary AND Operator copies a bit to the (a & b) will give0 which
result if it exists in both operands. is 0000 0000
| Binary OR Operator copies a bit if it exists (a | b) will give 30 which
in either operand. is 0001 1110
^ Binary XOR Operator copies the bit if it is (a ^ b) will give 30
set in one operand but not both. which is 0001 1110
~ Binary Ones Complement Operator is unary (~a ) will give -10 which
and has the effect of 'flipping' bits. is 0101
<< Binary Left Shift Operator. The left a << 2 will give 40
operands value is moved left by the which is 0010 1000
number of bits specified by the right
operand.
>> Binary Right Shift Operator. The left a >> 2 will give 2 which
operands value is moved right by the is 0000 0010
number of bits specified by the right
operand.
Python Logical Operators:

Operat
Description Example
or
and Called Logical AND operator. If both the (a and b) is true. X=5,
operands are true then then condition a>3 and a<10
becomes true.
or Called Logical OR Operator. If any of the two (a or b) is true.
operands are non zero then then condition
becomes true.
not Called Logical NOT Operator. Use to not(a and b) is false.
reverses the logical state of its operand. If a
condition is true then Logical NOT operator
will make false.
Python Membership
Operators:
In addition to the operators discussed previously, Python has
membership operators, which test for membership in a
sequence, such as strings, lists, or tuples.
Operato
Description Example
r
in Evaluates to true if it finds a variable in the x in y, here in results in a
specified sequence and false otherwise. 1 if x is a member of
sequence y.

not in Evaluates to true if it does not finds a x not in y, here not in


variable in the specified sequence and false results in a 1 if x is a
otherwise. member of sequence y.
Python Operators Precedence
Operator Description
** Exponentiation (raise to the power)
~+- Ccomplement, unary plus and minus (method names for
the last two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += Assignment operators
*= **=
is is not Identity operators
in not in Membership operators
not or and Logical operators
Standard Data Types:

Python has five standard data types:


• Numbers
• String
• List
• Tuple
• Set
• 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:

int long float complex


10 51924361L 0 3.14j
100 -0x19323L 15.2 45.j
-786 0122L -21.9 9.322e-36j
80 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j
-490 535633629843L -90 -.6545+0J
-0x260 -052318172735L -3.25E+101 3e+26J
0x69 -4721885298529L 70.2-E12 4.53e-7j
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
5th
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 If ... Else

• Python supports the usual logical


conditions from mathematics:
• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
• a = 33
b = 200
if b > a:
print("b is greater than a")
Indentation

• Python relies on indentation (whitespace


at the beginning of a line) to define scope
in the code.
• Other programming languages often use
curly-brackets for this purpose.
• a = 33
b = 200
if b > a:
print("b is greater than a") # you will get
an error
Elif

• a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Else

• The else keyword catches anything which


isn't caught by the preceding conditions.
• a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Short Hand If ... Else

•a=2
b = 330
print("A") if a > b else print("B")

• a = 330
b = 330
print("A") if a > b else print("=") if a ==
b else print("B")
And

• The and keyword is a logical operator, and


is used to combine conditional
statements:

• a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Or

• The or keyword is a logical operator, and


is used to combine conditional
statements:

• a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is
True")
Not

• The Not keyword is a logical operator, and


is used to combine conditional
statements:

• a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
Nested If

• You can have if statements inside if


statements, this is called nested if
statements.
• x = 41

if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
Python While Loops

• With the while loop we can execute a set


of statements as long as a condition is
true.

• Print i as long as i is less than 6:


•i=1
while i < 6:
print(i)
i += 1
The break Statement

• With the break statement we can stop the


loop even if the while condition is true:

•i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
The continue Statement

• With the continue statement we can stop


the current iteration, and continue with
the next:

•i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
The else Statement

• With the else statement we can run a


block of code once when the condition no
longer is true:

•i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
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.
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']

print list # Prints complete list


print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists

Output:
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
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.
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')

print tuple # Prints complete list


print tuple[0] # Prints first element of the list
print tuple[1:3] # Prints elements starting from 2nd till 3rd
print tuple[2:] # Prints elements starting from 3rd element
print tinytuple * 2 # Prints list two times
print tuple + tinytuple # Prints concatenated lists

OUTPUT:
('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
Python Sets:

• Sets are used to store multiple items in a single variable.

• A set is a collection which is unordered, unchangeable,


and unindexed.

• thisset = {"apple", "banana", "cherry"}


print(thisset)
• List is a collection which is ordered and
changeable. Allows duplicate members.
• Tuple is a collection which is ordered and
unchangeable. Allows duplicate members.
• Set is a collection which is unordered,
unchangeable, and unindexed. No
duplicate members.
• Dictionary is a collection which is
ordered and changeable. No duplicate
members.
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 ( [] ).
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two“
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values

OUTPUT:
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
Data Type Conversion:
Function Description
int(x [,base]) Converts x to an integer. base specifies the base if x is a string.
long(x [,base] ) Converts x to a long integer. base specifies the base if x is a string.
float(x) Converts x to a floating-point number.
complex(real Creates a complex number.
[,imag])
str(x) Converts object x to a string representation.
repr(x) Converts object x to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples.
frozenset(s) Converts s to a frozen set.
chr(x) Converts an integer to a character.
unichr(x) Converts an integer to a Unicode character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.

You might also like