0% found this document useful (0 votes)
52 views21 pages

Python Programming Language

The document discusses key concepts about the Python programming language including: - Python is an interpreted, interactive, object-oriented language suitable for beginners. - It uses indentation rather than brackets to delimit blocks and has optional semicolons. - Core data types include strings, numeric, list, tuples, dictionaries, and Boolean. - Control structures allow conditional execution and repetition through statements like if/else. - Functions can take arguments, return values, and exceptions can be handled. - Files can be opened and read from within Python programs.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
52 views21 pages

Python Programming Language

The document discusses key concepts about the Python programming language including: - Python is an interpreted, interactive, object-oriented language suitable for beginners. - It uses indentation rather than brackets to delimit blocks and has optional semicolons. - Core data types include strings, numeric, list, tuples, dictionaries, and Boolean. - Control structures allow conditional execution and repetition through statements like if/else. - Functions can take arguments, return values, and exceptions can be handled. - Files can be opened and read from within Python programs.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 21

Zain Al-Junaid

 Python Overview
 Python Data Types
 Python Control Structures
 Python Input\output
 Python Functions
 Python File Handling
 Python Exception Handling
Python is a high-level programming language which is:

 Interpreted: Python is processed at runtime by the interpreter

 Interactive: You can use a Python prompt and interact with


the interpreter directly to write your programs.

 Object-Oriented: Python supports Object-Oriented technique


of programming.

 Beginner‟s Language: Python is a great language for the


beginner-level programmers and supports the development
of a wide range of applications.
 Indentation is used in Python to delimit blocks. The number
of spaces is variable, but all statements within the same block
must be indented the same amount.

 The header line for compound statements, such as if, while,


def, and class should be terminated with a colon : .

 The semicolon ( ; ) is optional at the end of statement.

 Printing to the Screen: print(“Hello,Python”)

 Comments: Comments starts with a #


 Variables are containers for storing data values.
 Python is dynamically typed. You do not need to declare
variables!
 The declaration happens automatically when you assign a value
to a variable.
 Variables can change type, simply by assigning them a new value
of a different type.
 Python allows you to assign a single value to several variables
simultaneously.
 You can also assign multiple objects to multiple variables.
 In programming, data type is an important concept. Variables
can store data of different types, and different types can do
different things. Python has the following data types built-in
by default, in these categories:
Text Type string
Numeric Types int, float, complex
Sequence Types list, tuple, range
Mapping Type dict
Set Types set, frozenset
Boolean Type bool
Binary Types bytes, bytearray,
memoryview
 Python Strings are Immutable objects that cannot change their
values.
 You can update an existing string by (re)assigning a variable to
another string.
 Python does not support a character type; these are treated as
strings of length one.
 Python accepts single ('), double (") and triple (''' or """) quotes to
denote string literals.
 String indexes starting at 0 in the beginning of the string and
working their way from -1 at the end.
 Assume string variable a holds 'Hello' and
variable b holds 'Python‟
Operator Description Example
+ Concatenation - Adds a + b will give HelloPython
values on either side of the
operator

* Repetition - Creates new a*2 will give HelloHello


strings, concatenating
multiple copies of the same
string

[] Slice - Gives the character a[1] will give e


from the given index a[-1] will give o

[:] Range Slice - Gives the a[1:4] will give ell


characters from the given
range

in Membership - Returns true „H‟ in a will give True


if a character exists in the
given string
Method Description
str.count(sub, beg= 0,end=len(str)) Counts how many times sub occurs in string or in a
substring of string if starting index beg and ending
index end are given.

str.isalpha() Check if all the characters in the text is alphabetic.

str.isdigit() Returns True if string contains only digits and False


otherwise.

str.lower() Converts all uppercase letters in string to lowercase.

str.upper() Converts lowercase letters in string to uppercase.

str.replace(old, new) Replaces all occurrences of old in string with new

str.split(str=„ ‟) Splits string according to delimiter str (space if not


provided) and returns list of substrings.

str.strip() Returns a trimmed version of the string.

str.title() Returns "titlecased" version of string.


 A list in Python is an ordered group of items or elements, and these list
elements don't have to be of the same type.
 Python Lists are mutable objects that can change their values.
 A list contains items separated by commas and enclosed within square
brackets.
 List indexes like strings starting at 0 in the beginning of the list and working
their way from -1 at the end.
 Similar to strings, Lists operations include slicing ([ ] and [:]) , concatenation
(+), repetition (*), and membership (in).
Write a python program to access, update, slice and delete list elements
 Lists can have sublists as elements and these sublists may contain other
sublists as well.
Method Description
len(list) Gives the total length of the list.
max(list) Returns item from the list with max
value.
min(list) Returns item from the list with min
value.
list(tuple) Converts a tuple into list.
list.append(obj) Appends object obj to list
list.insert(index, obj) Inserts object obj into list at offset
index
list.count(obj) Returns count of how many times obj
occurs in list
list.index(obj) Returns the lowest index in list that obj
appears
Method Description
list.remove(obj) Removes object obj from list
list.reverse() Reverses objects of list in place
list.sort() Sorts objects of list in place
 Python Tuples are Immutable objects that cannot be changed once they have
been created.

 A tuple contains items separated by commas and enclosed in parentheses


instead of square brackets.

 You can update an existing tuple by (re)assigning a variable to another tuple.

 Tuples are faster than lists and protect your data against accidental changes
to these data.

 The rules for tuple indices are the same as for lists and they have the same
operations, functions as well.

 To write a tuple containing a single value, you have to include a comma, even
though there is only one value. e.g. t = (3, )
 Python's dictionaries are kind of hash table type which consist of key-value
pairs of unordered elements.
• Keys : must be immutable data types ,usually numbers or strings.

• Values : can be any arbitrary Python object.

 Python Dictionaries are mutable objects that can change their values.

 A dictionary is enclosed by curly braces ({ }), the items are separated by


commas, and each key is separated from its value by a colon (:).

 Dictionary‟s values can be assigned and accessed using square braces ([])
with a key to obtain its value.

Write a program to access, update and delete dictionary elements.


Method Description
dict.keys() Returns list of dict's keys

dict.values() Returns list of dict's values

dict.items() Returns a list of dict's (key, value) tuple pairs

dict.get(key, default=None) For key, returns value or default if key not in


dict

dict.update(dict2) Adds dict2's key-values pairs to dict

dict.clear() Removes all elements of dict


 In Python, True and False are Boolean objects of class 'bool' and they are
immutable.
 Python assumes any non-zero and non-null values as True, otherwise it is
False value.
 Python does not provide switch or case statements as in other languages.
 Syntax:

if statement if ..else if ..elseif..else


statement Statement
if expression: if expression: if expression1:
statement(s) statement(s) statement(s)
else elif(expression2):
statement(s) statement(s)
elif(expression3)
statement(s):
else:
statement(s)
 Function Arguments:
 Required arguments: the arguments passed to the function in correct
positional order.
 Keyword arguments: the function call identifies the arguments by the
parameter names.
 Default arguments: the argument has a default value in the function
declaration used when the value is not provided in the function call.
 Variable-length arguments: This used when you need to process unspecified
additional arguments. An asterisk (*) is placed before the variable name in
the function declaration
 To open the file, use the built-in open() function. The open() function returns a file
object, which has a read() method for reading the content of the file.
 Read Only Parts of the File
• By default the read() method returns the whole text, but you can also specify how
many characters you want to return.

 Read Lines:
• You can return one line by using the readline() method.

 Close Files
• Close the file when you are finish with it

 Write to an Existing File


• To write to an existing file, you must add a parameter to the open() function:
o "a" - Append - will append to the end of the file
o "w" - Write - will overwrite any existing content
 To create a new file in Python, use the open() method, with one of the following parameters:
 "x" - Create - will create a file, returns an error if the file exist.
 "a" - Append - will create a file if the specified file does not exist.
 "w" - Write - will create a file if the specified file does not exist.
Create a file called "myfile.txt“.

 Delete a File : To delete a file, you must import the OS module, and run its os.remove() function:
import os
os.remove("demofile.txt")
 Check if File exist
 To avoid getting an error, you might want to check if the file exists before you try to delete it:
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
 Delete Folder
 To delete an entire folder, use the os.rmdir() method:
import os
os.rmdir("myfolder")
 Note: You can only remove empty folders.
 The try block lets you test a block of code for errors.

 The except block lets you handle the error.

 The finally block lets you execute code, regardless of the result of the try-
and except blocks.

 When an error occurs, or exception as we call it, Python will normally stop
and generate an error message.

These exceptions can be handled using the try statement

You might also like