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

02 Python Programming Basics Part I

The document provides an overview of the Python programming language. It discusses Python's history, features, data types, variables, and number conversions. Python was created in the late 1980s and is an easy to learn, high-level programming language. It supports features like object-oriented programming, functions, and databases. Core data types in Python include numbers, strings, lists, tuples, and dictionaries.

Uploaded by

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

02 Python Programming Basics Part I

The document provides an overview of the Python programming language. It discusses Python's history, features, data types, variables, and number conversions. Python was created in the late 1980s and is an easy to learn, high-level programming language. It supports features like object-oriented programming, functions, and databases. Core data types in Python include numbers, strings, lists, tuples, and dictionaries.

Uploaded by

Ridee Reka
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Python Programming

Basics

By:
Sanka Sandamal
Prerequisites
• You should have a basic understanding of Computer Programming
terminologies. A basic understanding of any of the programming
languages is a plus.

Python Programming By: Sanka Sandamal


Overview
• Python is a high-level, interpreted, interactive and object-oriented
scripting language. Python is designed to be highly readable. It uses
English keywords frequently whereas the other languages use
punctuations. It has fewer syntactical constructions than other languages.

Python Programming By: Sanka Sandamal


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 now maintained by a core development team at the institute,
although Guido van Rossum still holds a vital role in directing its progress.
• Python 1.0 was released in November 1994. In 2000, Python 2.0 was
released. Python 2.7.11 is the latest edition of Python 2.
• Meanwhile, Python 3.0 was released in 2008. Python 3 is not backward
compatible with Python 2.

Python Programming By: Sanka Sandamal


Python Features
• Easy-to-learn , Easy-to-read , Easy-to-maintain
• Interactive Mode
• Extendable
• Databases
• GUI Programming
• It supports functional and structured programming methods as well as
OOP.
• It can be used as a scripting language or can be compiled to byte-code for
building large applications.
• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

Python Programming By: Sanka Sandamal


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, “Car”
and “car” are two different identifiers in Python.
• Here are naming conventions for Python identifiers −

1. Class names start with an uppercase letter. All other identifiers start
with a lowercase letter.
2. There are some reserved words which you cannot use as a variable
name because Python uses them for other things.

Python Programming By: Sanka Sandamal


Reserved Words
• The following list shows the Python keywords. These are reserved words
and you cannot use them as constants or variables or any other identifier
names. All the Python keywords contain lowercase letters only.

and exec not as finally or


assert for pass break from print
class global raise continue if return
def import try del in while
elif is with else lambda yield
except

Python Programming By: Sanka Sandamal


Simple Program.
• Python is a very simple language, and has a very straightforward syntax.
• Display text

print("This line will be printed.")

Python Programming By: Sanka Sandamal


Indentation
• Python uses indentation for blocks, instead of curly braces. Both tabs and
spaces are supported, but the standard indentation requires standard
Python code to use four spaces. For example:

Python Programming By: Sanka Sandamal


Multi-Line Statements

Python Programming By: Sanka Sandamal


Comments in Python
• A hash sign (#) that is not inside a string literal is the beginning of a
comment. All characters after the #, up to the end of the physical line, are
part of the comment and the Python interpreter ignores them.

Python Programming By: Sanka Sandamal


Waiting for the User
• The following line of the program displays the prompt and, the statement
saying “Press the enter key to exit”, and then waits for the user to take
action,

input("\n\nPress the enter key to exit.")

• Here, "\n\n" is used to create two new lines before displaying the actual
line. Once the user presses the key, the program ends. This is a nice trick
to keep a console window open until the user is done with an application.

Python Programming By: Sanka Sandamal


Multiple Statements on a Single Line
• The semicolon ( ; ) allows multiple statements on a single line given that
no statement starts a new code block. Here is a sample snip using the
semicolon.

x = 'This is Text'; print(x)

Python Programming By: Sanka Sandamal


Multiple Statement Groups as Suites(Compound Statements)
• Groups of individual statements, which make a single code block are called
suites in Python. Compound or complex statements, such as if, while, def,
and class 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 x > 100 :
print('Excellent')
elif x > 50 :
print('Good')
elif x > 30 :
print('Must improve')
else :
print('Fail')

Python Programming By: Sanka Sandamal


Assigning Values to Variables
• The equal sign (=) is used to assign values to variables.

X = 50
y = ‘100’
text = “Hello world”

• Python allows you to assign a single value to several variables


simultaneously.

a=b=c=1
a, b, c = 1, 2, "john"

Python Programming By: Sanka Sandamal


Data Types
• Immutable Data Types.
Immutable objects cannot have their state changed and include:
1) Numbers
2) Strings
3) Tuples
4) Booleans

• Mutable objects can have their state changed and include:


1) Dictionaries
2) Lists

Python Programming By: Sanka Sandamal


Numbers
• Number data types store numeric values. They are immutable data types.

Int: (signed integers) −


They are often called just integers or ints. They are positive or negative
whole numbers with no decimal point. Integers in Python 3 are of
unlimited size. Python 2 has two integer types - int and long.

float (floating point real values) −


Also called floats, they represent real numbers and are written with a
decimal point dividing the integer and the fractional parts. Floats may also
be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5
x 102 = 250).

complex (complex numbers) −


These are of the form a + bJ, where a and b are floats and J (or j)
represents the square root of -1 (which is an imaginary number).

Python Programming By: Sanka Sandamal


Number Type Conversion
• Number abs() Method
The abs() method returns the absolute value of x i.e. the positive distance
between x and zero.

• Number ceil() Method


The ceil() method returns the ceiling value of x i.e. the smallest integer not
less than x. This function is not accessible directly, so we need to import
math module and then we need to call this function using the math static
object.
math.ceil(100.12) -> 101

• The fabs() method


Returns the absolute value of x. Although similar to the abs() function,
there are differences between the two functions. abs() is a built in
function whereas fabs() is defined in math module. fabs() function works
only on float and integer whereas abs() works with complex number also.
Python Programming By: Sanka Sandamal
Number Type Conversion (Cont.)
• The floor() method
Returns the floor of x i.e. the largest integer not greater than x.
math.floor(100.12) -> 100
• Number max() Method -
The max() method returns the largest of its arguments i.e. the value
closest to positive infinity.
max(80, 100, 1000)
• The method min() returns the smallest of its arguments i.e. the value
closest to negative infinity.
min(80, 100, 1000)
• The modf() method returns the fractional and integer parts of x in a two-
item tuple. Both parts have the same sign as x. The integer part is returned
as a float.
math.modf(100.12) -> (0.12000000000000455, 100.0)

Python Programming By: Sanka Sandamal


Number Type Conversion (Cont.)
• Number pow() Method –
This method returns the value of xy.
math.pow(100, 2)

• Round() is a built-in function in Python. It returns x rounded to n digits


from the decimal point.
round(56.659,1)

• The sqrt() method returns the square root of x for x > 0.


math.sqrt(100)

• Number choice() Method – (import random)


The choice() method returns a random item from a list, tuple, or string.
random.choice(range(100) , random.choice('Hello World') ,
random.choice([1, 2, 3, 5, 9])

Python Programming By: Sanka Sandamal


Number Type Conversion (Cont.)
• The shuffle() method
Randomizes the items of a list in place.
import random
list = [20, 16, 10, 5]
random.shuffle(list)

• Number uniform() Method


The uniform() method returns a random float r, such that x is less than or
equal to r and r is less than y.
random.uniform(5, 10)

Python Programming By: Sanka Sandamal


Strings
• Strings in Python are identified as a contiguous set of characters
represented in the quotation marks. Python allows either pair 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.
• 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

Python Programming By: Sanka Sandamal


Strings (Cont.)
• You can "update" an existing string by (re)assigning a variable to another
string. The new value can be related to its previous value or to a
completely different string altogether.

var1 = 'Hello World!‘


print ("Updated String :- ", var1[:6] + 'Python')

• Escape Characters
Following table is a list of escape or non-printable characters that can be
represented with backslash notation.An escape character gets interpreted;
in a single quoted as well as double quoted strings.
\b , \e , \n , \s , \t

Python Programming By: Sanka Sandamal


Strings (Cont.)
• String Special Operators

“+”
Concatenation - Adds values on either side of the operator

“*”
Repetition - Creates new strings, concatenating multiple copies of the
same string

“[ ]”
Slice - Gives the character from the given index

“[ : ]”
Range Slice - Gives the characters from the given range

Python Programming By: Sanka Sandamal


Strings (Cont.)
• “in”
Membership - Returns true if a character exists in the given string

“not in”
Membership - Returns true if a character does not exist in the given string

Python Programming By: Sanka Sandamal


Strings (Cont.)
• String Formatting Operator
One of Python's coolest features is the string format operator %. This
operator is unique to strings and makes up for the pack of having functions
from C's printf() family.

print ("My name is %s and weight is %d kg!" % ('Zara', 21))

%c – character
%s - string conversion via str() prior to formatting
%i , %d - signed decimal integer
%f - floating point real number

Python Programming By: Sanka Sandamal


Strings (Cont.)
• Triple Quotes

Python's triple quotes comes to the rescue by allowing strings to span


multiple lines, including verbatim NEWLINEs, TABs, and any other special
characters.

para_str = """this is a long string that is made up of


several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [ \n ], or just a NEWLINE within
the variable assignment will also show up.
”””
print (para_str)

Python Programming By: Sanka Sandamal


Strings (Cont.)
• String capitalize()
It returns a copy of the string with only its first character capitalized.
str = "this is string example....wow!!!“
print ("str.capitalize() : ", str.capitalize())
Result: str.capitalize() : This is string example....wow!!!

String center()
The method center() returns centered in a string of length width. Padding
is done using the specified fillchar. Default filler is a space.
str = "this is string example....wow!!!“
print ("str.center(40, 'a') : ", str.center(40, 'a'))
Result : aaaathis is string example....wow!!!aaaa

Python Programming By: Sanka Sandamal


Strings (Cont.)
• String endswith()
It returns True if the string ends with the specified suffix, otherwise return
False optionally restricting the matching with the given indices start and
end.

Python Programming By: Sanka Sandamal


Strings (Cont.)
• String isalnum()
The isalnum() method checks whether the string consists of alphanumeric
characters.

• The isalpha() method checks whether the string consists of alphabetic


characters only.

Python Programming By: Sanka Sandamal


Strings (Cont.)
• String isdigit()
The method isdigit() checks whether the string consists of digits only.

• The islower() method checks whether all the case-based characters


(letters) of the string are lowercase.

Python Programming By: Sanka Sandamal


Strings (Cont.)
• The isnumeric() method checks whether the string consists of only
numeric characters.

• The istitle() method checks whether all the case-based characters in the
string following non-casebased letters are uppercase and all other case-
based characters are lowercase.

Python Programming By: Sanka Sandamal


Strings (Cont.)
• The isupper() method checks whether all the case-based characters
(letters) of the string are uppercase.

• The join() method returns a string in which the string elements of


sequence have been joined by str separator.

Python Programming By: Sanka Sandamal


Strings (Cont.)
• The len() method returns the length of the string.

• The method lower() returns a copy of the string in which all case-based
characters have been lowercased.

• The maketrans() method returns a translation table that maps each


character in the intabstring into the character at the same position in the
outtab string. Then this table is passed to the translate() function.

Python Programming By: Sanka Sandamal


Strings (Cont.)
• The max() method returns the max alphabetical character from the string
str.

• The min() method returns the min alphabetical character from the string
str.

• The swapcase() method returns a copy of the string in which all the case-
based characters have had their case swapped.

Python Programming By: Sanka Sandamal


Lists
• The list is the most versatile datatype available in Python, which can be
written as a list of comma-separated values (items) between square
brackets. Important thing about a list is that the items in a list need not be
of the same type.

• To access values in lists, use the square brackets for slicing along with the
index or indices to obtain value available at that index.

Python Programming By: Sanka Sandamal


Lists
• You can update single or multiple elements of lists by giving the slice on
the left-hand side of the assignment operator, and you can add to
elements in a list with the append() method.

• To remove a list element, you can use either the del statement if you know
exactly which element(s) you are deleting.

Python Programming By: Sanka Sandamal


Lists
• Basic List Operations

Lists respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new list,
not a string.

Python Programming By: Sanka Sandamal


Tuples
• A tuple is a sequence of immutable Python objects. Tuples are sequences,
just like lists. The main difference between the tuples and the lists is that
the tuples cannot be changed unlike lists. Tuples use parentheses, whereas
lists use square brackets.
• Creating a tuple is as simple as putting different comma-separated values.
Optionally, you can put these comma-separated values between
parentheses also.

Python Programming By: Sanka Sandamal


Tuples
• To access values in tuple, use the square brackets for slicing along with the
index or indices to obtain the value available at that index.

• Tuples are immutable, which means you cannot update or change the
values of tuple elements. You are able to take portions of the existing
tuples to create new tuples as the following example demonstrates –

• Removing individual tuple elements is not possible.


Python Programming By: Sanka Sandamal
Tuples
• Tuples respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new
tuple, not a string.

Python Programming By: Sanka Sandamal


Dictionary
• Each key is separated from its value by a colon (:), the items are separated
by commas, and the whole thing is enclosed in curly braces. An empty
dictionary without any items is written with just two curly braces, like this:
{}.
• Keys are unique within a dictionary while values may not be. The values of
a dictionary can be of any type, but the keys must be of an immutable data
type such as strings, numbers, or tuples.

Python Programming By: Sanka Sandamal


Dictionary
• To access dictionary elements, you can use the familiar square brackets
along with the key to obtain its value.

• You can update a dictionary by adding a new entry or a key-value pair,


modifying an existing entry, or deleting an existing entry as shown in a
simple example given below.

Python Programming By: Sanka Sandamal


Dictionary
• You can either remove individual dictionary elements or clear the entire
contents of a dictionary. You can also delete entire dictionary in a single
operation.

Python Programming By: Sanka Sandamal


Basic Operators
• Arithmetic Operators

“+” Addition
Adds values on either side of the operator.

“-” Subtraction
Subtracts right hand operand from left hand operand.

“*” Multiplication
Multiplies values on either side of the operator

“/” Division
Divides left hand operand by right hand operand

“%” Modulus
Divides left hand operand by right hand operand and returns remainder

Python Programming By: Sanka Sandamal


Basic Operators
• “**” Exponent
Performs exponential (power) calculation on operators

“// ” Floor Division


The division of operands where the result is the quotient in which the
digits after the decimal point are removed. But if one of the operands is
negative, the result is floored, i.e., rounded away from zero (towards
negative infinity)

Python Programming By: Sanka Sandamal


Basic Operators
• Comparison Operators

“==”
If the values of two operands are equal, then the condition becomes true.

“!=”
If values of two operands are not equal, then condition becomes true.

“>”
If the value of left operand is greater than the value of right operand, then
condition becomes true.

“<”
If the value of left operand is less than the value of right operand, then
condition becomes true.

Python Programming By: Sanka Sandamal


Basic Operators
• “>=”
If the value of left operand is greater than or equal to the value of right
operand, then condition becomes true.

“<=”
If the value of left operand is less than or equal to the value of right
operand, then condition becomes true.

Python Programming By: Sanka Sandamal


Basic Operators
• Assignment Operators

“=”
Assigns values from right side operands to left side operand

“+=”
It adds right operand to the left operand and assign the result to left
operand

“-=”
It subtracts right operand from the left operand and assign the result to
left operand

“*=”
It multiplies right operand with the left operand and assign the result to
left operand

Python Programming By: Sanka Sandamal


Basic Operators
• “/=”
It divides left operand with the right operand and assign the result to left
operand

“%=”
It takes modulus using two operands and assign the result to left operand

“**=”
Performs exponential (power) calculation on operators and assign value to
the left operand

“//=”
It performs floor division on operators and assign value to the left operand

Python Programming By: Sanka Sandamal


Basic Operators
• Bitwise Operators

“& Binary AND”


Operator copies a bit, to the result, if it exists in both operands

“| Binary OR”
It copies a bit, if it exists in either operand.

“^ Binary XOR”
It copies the bit, if it is set in one operand but not both.

Python Programming By: Sanka Sandamal


Basic Operators
• Bitwise Operators

“<< Binary Left Shift”


The left operand's value is moved left by the number of bits specified by
the right operand.

“>> Binary Right Shift”


The left operand's value is moved right by the number of bits specified by
the right operand.

Python Programming By: Sanka Sandamal


Basic Operators
• Logical Operators

“and Logical AND”


If both the operands are true then condition becomes true.

“or Logical OR”


If any of the two operands are non-zero then condition becomes true.

“not Logical NOT”


Used to reverse the logical state of its operand.

Python Programming By: Sanka Sandamal


Basic Operators
• Membership Operators

Python’s membership operators test for membership in a sequence, such


as strings, lists, or tuples. There are two membership operators as
explained below −

“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.

Python Programming By: Sanka Sandamal


Basic 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.

Python Programming By: Sanka Sandamal


Operators Precedence
Operator Description
** Exponentiation (raise to the power)
* / % // 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

Python Programming By: Sanka Sandamal


The End!
Python Programming
Basics

Thank You.
By:
Sanka Sandamal

You might also like