This document provides an overview of the Python programming language. It discusses Python's history, features, and why it is a good programming language. Key points covered include:
- Python was created in the late 1980s and draws from many other languages.
- It is an open source, interpreted, object-oriented, and portable language with a large online community and library support.
- Python code is compiled to bytecode for performance. It has dynamic typing, automatic memory management, and is powerful yet easy to learn.
- The document reviews Python statements, expressions, variables, basic data types, functions, modules and exceptions. It provides examples of Python code.
Best Data Science Ppt using Python
Data science is an inter-disciplinary field that uses scientific methods, processes, algorithms and systems to extract knowledge and insights from many structural and unstructured data. Data science is related to data mining, machine learning and big data.
Best Data Science Ppt using Python
Data science is an inter-disciplinary field that uses scientific methods, processes, algorithms and systems to extract knowledge and insights from many structural and unstructured data. Data science is related to data mining, machine learning and big data.
In this chapter we will review how to work with text files in C#. We will explain what a stream is, what its purpose is, and how to use it. We will explain what a text file is and how can you read and write data to a text file and how to deal with different character encodings. We will demonstrate and explain the good practices for exception handling when working with files. All of this will be demonstrated with many examples in this chapter
Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive standard library.
A slightly modified version of original "An introduction to Python
for absolute beginners" slides. For credits please check the second page. I used this presentation for my company's internal Python course.
Python 101: Python for Absolute Beginners (PyTexas 2014)Paige Bailey
If you're absolutely new to Python, and to programming in general, this is the place to start!
Here's the breakdown: by the end of this workshop, you'll have Python downloaded onto your personal machine; have a general idea of what Python can help you do; be pointed in the direction of some excellent practice materials; and have a basic understanding of the syntax of the language.
Please don't forget to bring your laptop!
Audience: "Python 101" is geared toward individuals who are new to programming. If you've had some programming experience (shell scripting, MATLAB, Ruby, etc.), then you'll probably want to check out the more intermediate workshop, "Python 101++".
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
Python
Language
is uesd in engineeringStory adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they s
In this chapter we will review how to work with text files in C#. We will explain what a stream is, what its purpose is, and how to use it. We will explain what a text file is and how can you read and write data to a text file and how to deal with different character encodings. We will demonstrate and explain the good practices for exception handling when working with files. All of this will be demonstrated with many examples in this chapter
Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive standard library.
A slightly modified version of original "An introduction to Python
for absolute beginners" slides. For credits please check the second page. I used this presentation for my company's internal Python course.
Python 101: Python for Absolute Beginners (PyTexas 2014)Paige Bailey
If you're absolutely new to Python, and to programming in general, this is the place to start!
Here's the breakdown: by the end of this workshop, you'll have Python downloaded onto your personal machine; have a general idea of what Python can help you do; be pointed in the direction of some excellent practice materials; and have a basic understanding of the syntax of the language.
Please don't forget to bring your laptop!
Audience: "Python 101" is geared toward individuals who are new to programming. If you've had some programming experience (shell scripting, MATLAB, Ruby, etc.), then you'll probably want to check out the more intermediate workshop, "Python 101++".
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
Python
Language
is uesd in engineeringStory adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they s
إذا كُنت من هواة البرمجة ولم تُحلّق في هذا العالم بعد فالطريق ما زال مفتوحًا أمامك، فالفضاء موجود أمامك لتختار أحد المسارات وتسلكها فورًا.
اختيار المسار بحد ذاته هو الحاجز الذي نقف عنده في الغالب، بل ويستغرق وقتًا أطول من وقت التعلّم والمُمارسة، لكن ليس هُناك أجمل من الاستفادة من التقنيات الموجودة بين أيدينا حاليًا لتطوير أدوات نستطيع الاستفادة منها.
لمزيد من المعلومات اشتركوا في قائمتنا البريدية:
https://www.apptrainers.com/
Helpmeinhomework Experts provides the most trusted and reliable online Programming assignment help . Programming is one of the most widely taught subjects across the universities. The complexity of subjects make students seek for quality and affordable online guidance. We at helpmeinhomework.com Experts cater to such needs of the students. Our programming experts provide assignment help to students across UK, USA and Australia for multiple programming languages i.e. Java, Python, HTML, PHP, Assembly language, C ,Linux ,Unix etc.
Kosmik is the best institute for Python training in Hyderabad Kukatpally/KPHB. kosmik provides lab facilities with complete real-time training with live sessions
call now: +91-8712186898, +91-8179496603, +91-6309565721
This file contains the first steps any beginner can take as he/she starts a journey into the rich and beautiful world of Python programming. From basics such as variables to data types and recursions, this document touches briefly on these concepts. It is not, by any means, an exhaustive guide to learn Python, but it serves as a good starting point and motivation.
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
This is a presentation by Dada Robert in a Your Skill Boost masterclass organised by the Excellence Foundation for South Sudan (EFSS) on Saturday, the 25th and Sunday, the 26th of May 2024.
He discussed the concept of quality improvement, emphasizing its applicability to various aspects of life, including personal, project, and program improvements. He defined quality as doing the right thing at the right time in the right way to achieve the best possible results and discussed the concept of the "gap" between what we know and what we do, and how this gap represents the areas we need to improve. He explained the scientific approach to quality improvement, which involves systematic performance analysis, testing and learning, and implementing change ideas. He also highlighted the importance of client focus and a team approach to quality improvement.
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
The Art Pastor's Guide to Sabbath | Steve ThomasonSteve Thomason
What is the purpose of the Sabbath Law in the Torah. It is interesting to compare how the context of the law shifts from Exodus to Deuteronomy. Who gets to rest, and why?
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
2. UNIT – IV Contents
Introduction to python language
python-syntax
statements
functions, Built-in-functions and Methods
Modules in python
Exception Handling
3. UNIT IV Outcomes
From the IV unit Student can
Understand python programming features and its statements
Write and execute programs with basic concepts, functions,
Modules and Exception Handling.
Analyze the problem statements and can write solution in the
form of a python program.
Arrives to a conclusion about programming languages
principles by comparing python with other Programming
languages already he/she learnt in the previous semesters.
4. Python
Python was developed by Guido van Rossum in the late
eighties at the National Research Institute for Mathematics
and Computer Science in Netherlands.
Python is derived from many other Programming
languages including, C, C++, Algol-68, Smalltalk, Unix
shell and other scripting languages
5. Why Python?
Python is object-oriented
Structure supports Encapsulation, polymorphism,
Abstraction, multiple inheritance
It's open source, so downloading and installing Python
is free and easy
Source code is easily accessible
Online Python community is huge to support the
Python programmers
It's portable
Python runs on every major platform
6. Python programs will run in the same manner, irrespective of
platform
It's powerful
Dynamic typing
Built-in types and tools
Library utilities
Third party utilities (numeric, NumPy, SciPy)
Automatic memory management
Can design data structures, web applications, Database
programs, games etc…
Why Python?
7. Python's library is very portable and cross-platform compatible
on UNIX, Windows, and Macintosh.
Support for an interactive mode which allows interactive
testing and debugging the code.
Python can be linked to components written in other languages
easily
Linking to fast, compiled code is useful to computationally
intensive problems
Python is good for code steering and for merging multiple
programs
Why Python?
8. WARP is implemented in a mixture of Python and Fortran
Python programs are compiled automatically to an intermediate
form called bytecode, which the interpreter then reads
This gives Python the development speed of an interpreter
without the performance loss inherent in purely interpreted
languages
It's easy to learn also.
Structure and syntax are pretty intuitive and easy to grasp
Why Python?
9. Running Python
Unix: IDLE is the very first Unix IDE for Python.
Windows: PythonWin is the first Windows interface for
Python and is an IDE with a GUI.
Macintosh: The Macintosh version of Python along
with the IDLE IDE is available from the
main website, downloadable as either
MacBinary or BinHex'd files.
10. 10
source code: The sequence of instructions in a program.
syntax: The set of legal structures and commands that can be used
in a particular programming language.
output: The messages printed to the user by a program.
console: The text box onto which output is printed.
Some source code editors pop up the console as an external
window, and others contain their own console window.
Programming basics
11. 11
Compiling and interpreting
Many languages require you to compile (translate) program
into a form that the machine understands.
Python is instead directly interpreted into machine instructions.
compile execute
outputsource code
Hello.java
byte code
Hello.class
interpret
outputsource code
Hello.py
12. Reserved Words
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
13. 13
Expressions
expression: A data value or set of operations to compute a
value.
Examples: 1 + 4 * 3
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.
(1 + 3) * 4 is 16
14. 14
Real numbers
Python can also manipulate real numbers.
Examples: 6.022-15.9997 42.0 2.143e17
The operators + - * / % ** ( ) all work for real
numbers.
The / produces an exact answer: 15.0 / 2.0 is 7.5
The same rules of precedence also apply to real
numbers:
Evaluate ( ) before * / % before + -
When integers and reals are mixed, the result is a real
number.
Example: 1 / 2.0 is 0.5
15. 15
Math commands (import math)
Python has useful commands for performing calculations.
Command name Description
abs(value) absolute value
ceil(value) rounds up
cos(value) cosine, in radians
floor(value) rounds down
log(value) logarithm, base e
log10(value) logarithm, base 10
max(value1, value2) larger of two values
min(value1, value2) smaller of two values
round(value) nearest whole number
sin(value) sine, in radians
sqrt(value) square root
Constant Description
e 2.7182818...
pi 3.1415926...
16. 16
Variables
variable:A named piece of memory that can store a
value.
Usage:
Compute an expression's result,
store that result into a variable,
and use that variable later in the program.
assignment statement: Stores a value into a variable.
Syntax: name = value
Examples: x = 5
gpa = 3.14
x 5 gpa 3.14
A variable that has been given a value can be used in
expressions.
x + 4 is 9
17. 17
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.
Example:
print "Hello, world!"
age = 45
print "You have", 65 - age, "years until retirement"
Output:
Hello, world!
You have 20 years until retirement
print
18. 18
Reads a number from user input.
You can assign (store) the result of input into a variable.
Example Program:
import sys
age = int(input("How old are you? "))
print "Your age is", age
print (“No. of years for retirement”, 65-age)
Output:
How old are you? 53
Your age is 53
No. of years for retirement: 12
input statement
19. Programming Basics
Programs are composed of modules
Modules contain statements
Statements contain expressions
Expressions create and process objects
20. Built-in Objects
Make programs easy to write
Components of extensions
More efficient
Standard part of language
21. Program statements
You can run programs at command prompt or IDLE Window
print(“hello world!”)
Arithmetic operations:
5+4 or print(5+4)
5-4 or print(5-4)
5*4 or print(5*4)
5/4 or print(5/4) displays 1.25
5//4 or print(5//4) displays 1
5%4 or print(5%4)
22. Program Statements
2**8 displays 256
Name=‘sasidhar’
Name displays sasidhar
‘sasidhar|’ * 8 displays sasidhar|sasidhar| for 8 times
Import os
os.getcwd() displays the current python version with
its path
23. Python Script
Type the following program in idle and save it as script1.py
Import sys # Load a library module
print(sys.platform)
Print(2**100)
X=‘Sasidhar|’
print(x*8)
24. Core data types & Built-in Objects in Python
Object type Example literals / creation
Numbers 1234, 3.145, 3+4j
Strings ‘anil’, ‘ax01c’
Lists [1, [2, ‘three’], 4]
Dictionaries {‘food’: ‘spam’, ‘taste’:}
Tuples (1, ‘anil’, 77, ‘ecm’)
Files myfile = open(‘ecm’, ‘r’)
Sets set(‘abc’), {‘a’, ‘b’, ‘c’}
Other core types Booleans, types, None
Program unit types Functions, modules, classes
Implementation types Compiled code, stacktracebacks
25. Strings and its operations
Strings are used to record textual information as well as
bytes.
s=“anil”
len(s)
s[0] displays a
s[4] or s[-1] displays l
s[1:3] displays ni
s + xyz anilxyz
s.find(il) found at 2
s.replace(‘an’, ‘man’)
26. String operations
s.split splits based on delimeter
s.upper() displays in capital letters.
s.lower() displays in small case letters
s.isalpha() tests the text.
s.rstrip() removes the whitespace characters on right side
27. Lists (Data Structures)
Lists are ordered collections of arbitrarily typed objects
and they have no fixed size.
Lists are mutable.
Lists supports all sequence of operations similar to
strings. The difference is the result will be displayed in
lists.
Ex: L=[13, ‘anil’, 88]
L[1] displays anil
L[:-1] displays anil, 88
L + [4,5,6 ] displays [13,anil,88, 4,5,6]
28. Operations on Lists
L.append(‘kk’) adds element kk at the end of the list
L displays anilkk
L.pop (2) deletes the 2nd
element from the list
L.sort() sorts in ascending order
L.reverse() in reverse order.
30. Nesting
Nesting of lists is possible in python. Application is matrix.
A = [ [1,2,3],
[4,5,6],
[7,8,9]]
>>> A displays [[1,2,3], [4,5,6], [7,8,9] ]
>>> A[1] displays [4,5,6]
>>> A[1,2] displays [6]
31. Comprehensions
Useful to process the matrix like structures.
Example1: to extract 2nd
column from the matrix:
Col2= [ row[1] for row in A ]
Col2 displays [2,5,8]
Example2: [row[1] + 1for row in A]
Example3:
[row[1] for row in A if row[1]%2 ==0] [2,8]
32. List built-in functions
cmp(list1, list2) Compares elements of both lists.
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(seq) Converts a tuple into list.
33. Control statements
if condition
if expression:
statement
if-else statement
if expression:
statement
else:
statement
elif statement
if expression1:
statement
elif expression2:
statement
elif expression3:
statement
else:
statement
34. Looping Statements
while loop
while expression:
statements
Example:
count = 0
while (count < 10):
print ‘Count is:', count
count = count + 1
36. Tuples
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
37. Tuples vs. Lists
Lists slower but more powerful than tuples
Lists can be modified, and they have lots of handy
operations and mehtods
Tuples are immutable and have fewer features
To convert between tuples and lists use the list()
and tuple() functions:
li = list(tu)
tu = tuple(li)
38. Dictionaries
Python's dictionaries are kind of hash table type.
They work like associative arrays or hashes and consist of
key-value pairs.
A dictionary key 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 ([]).
39. Dictionaries Example
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 only keys: name,code,dept
print tinydict.values() # Prints all the values
40. Working with Time namespace
import time
>>> ticks = time.time()
>>> print("no.of ticks since 12am, march31, 2015:", ticks)
Getting current time:
import time;
localtime = time.localtime(time.time())
print "Local current time :", localtime
Formatted time:
localtime = time.asctime( time.localtime(time.time()) )
41. Working with calendar namespace in python
import calendar
cal = calendar.month(2016, 3)
print "Here is the calendar:"
print cal;
42. Python’s Statements
Statement Role Example
Assignment Creating references a, *b = 'good', 'bad',
'ugly'
Calls and other expressions Running functions log.write("spam, ham")
print calls Printing objects print('The Killer', joke)
if/elif/else Selecting actions if "python" in text:
print(text)
for/else Sequence iteration for x in mylist:
print(x)
while/else General loops while X > Y:
print('hello')
Pass Empty placeholder while True:
pass
break Loop exit while True:
if exittest(): break
Continue Loop continue while True:
if skiptest(): continue
43. Python’s Statements …
def Functions and methods def f(a, b, c=1, *d):
print(a+b+c+d[0])
return Functions results def f(a, b, c=1, *d):
return a+b+c+d[0]
yield Generator functions def gen(n):
for i in n: yield i*2
global Namespaces x = 'old'
def function():
global x, y; x = 'new'
import Module access import sys
from Attribute access from sys import stdin
class Building objects class Subclass(Superclass):
staticData = []
def method(self): pass
44. Statements of Python
try/except/ finally Catching exceptions try:
action()
except:
print('action error')
raise Triggering exceptions raise
EndSearch(location)
assert Debugging checks assert X > Y, 'X
too small'
with/as Context managers (2.6+) with
open('data') as myfile:
process(myfile)
45. Command Line arguments in Python
import sys
print ('Number of arguments:', len(sys.argv), 'arguments.‘)
print 'Argument List:', str(sys.argv)
46. Functions
Function blocks begin with the keyword def followed by
the function name and parentheses ( ( ) ).
Any input parameters or arguments should be placed
within these parentheses. Can also define parameters
inside these parentheses.
The first statement of a function can be an optional
statement - the documentation string of the function or
docstring.
The code block within every function starts with a colon
(:) and is indented.
47. The statement return [expression] exits a function,
optionally passing back an expression to the caller.
A return statement with no arguments is the same as
return None.
def printme( str ):
"This prints a passed string into this function"
print str
return
Functions
48. Function calling
# function definition
def display(str):
"this prints sasidhar“ # value for str argument
print(str);
return;
# function calling
display("hi this is sasidhar");
display("second time sasidhar");
49. Pass by reference
All parameters (arguments) in the Python language are
passed by reference.
If you change the parameter that refers to within a
function, the change also reflects back in the calling
function.
50. Example
# function definition
def changelist( mylist ):
# "This changes a passed list into this function"
mylist.append([1,2,3,4]);
Print( "Values inside the function: ", mylist)
return
#call changelist function
mylist = [10,20,30];
changelist( mylist );
print( "Values outside the function: ", mylist)
Output:
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
51. Example for passed by reference and
overwritten inside the function.
mylist = [1,2,3,4]; # global variable
def changeme( mylist ):
print "Values inside the function: ", mylist
return
# Now call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
Output:
Values inside the function: [10, 20, 30]
Values outside the function: [10, 20, 30]
53. Required arguments
Required arguments are the arguments passed to a
function in correct positional order. Here, the number of
arguments in the function call should match exactly with
the function definition.
54. Keyword arguments
Keyword arguments are related to the function calls.
When you use keyword arguments in a function call, the
caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of
order because the Python interpreter is able to use the
keywords provided to match the values with parameters.
55. Example for keyword argument
def printme( str ):
"This prints a passed string into this function"
print str;
return;
# Now call printme function
printme( str = "My string");
56. Default arguments
A default argument is an argument that assumes a default
value if a value is not provided in the function call for that
argument. The following example gives an idea on default
arguments, it prints default age if it is not passed:
57. Example
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name;
print "Age ", age;
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" );
printinfo( name="miki" );
58. Variable Length Arguments
To process a function for more arguments than specified
while defining the function.
These arguments are called variable-length arguments
An asterisk (*) is placed before the variable name that
holds the values of all non-keyword variable arguments.
59. Example for variable length arguments
def printinfo( arg1, *vartuple ):
print "Output is: "
print arg1 #“This prints variable passed arguments"
for var in vartuple:
print (var)
return;
# Now call printinfo function
printinfo( 10 );
printinfo( 70, 60, 50 );
60. Anonymous functions : lambda
The functions that are not declared in the standard manner by
using the def keyword are called anonymous functions.
The lambda keyword is used to create small anonymous
functions.
Lambda forms can take any number of arguments but return
just one value in the form of an expression. They cannot
contain commands or multiple expressions.
An anonymous function cannot be a direct call to print because
lambda requires an expression.
Lambda functions have their own local namespace and cannot
access variables other than those in their parameter list and
those in the global namespace.
61. Anonymous functions : lambda
These functions are not like inline functions in c++
Syntax: lambda [arg1 [,arg2,.....argn]] :expression
sum=lambda arg1, arg2: arg1+ arg2
print(" value of total:", sum(10,22))
print("value of total:", sum(20,20))
62. Return statement
def sum( arg1, arg2 ):
total = arg1 + arg2
print "Inside the function : ", total
return total
total = sum( 10, 20 );
print( "Outside the function : ", total )
63. Scope of variables
Variables declared inside the function are local and can
be accessible with in that function
Variables declared outside the function are global and can
be accessible from the calling or outside of the function.
64. Module
A module allows to logically organize the Python code.
Grouping related code into a module makes the code easier to
understand and use. A module is an object with arbitrarily
named attributes that you can bind and reference. A module
can define functions, classes and variables.
# Import built-in module math
import math
content = dir(math)
print content;
65. Simple calculator Program Using functions
"""This function adds two numbers"""
def add(x,y):
return x + y
def subtract(x, y):
"""This function subtracts two numbers"""
return x - y def multiply(x, y):
"""This function multiplies two numbers""“
return x * y def divide(x, y):
"""This function divides two numbers"""
return x / y # take input from the user print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4):")
67. Files I/O
Reading input from keyboard:
Input, raw_input
The raw_input([prompt]) function reads one line from
standard input and returns it as a string (removing the
trailing newline).
Example:
str = raw_input("Enter your input: ");
print "Received input is : ", str
68. Opening files
A file can be opened using open() function.
Syntax:
file object = open(file_name [, access_mode][, buffering])
access mode = file has to be opened in read or write or
append mode.
f1 = open(“ecm.txt", "wb")
print "Name of the file: ", f1.name
print "Closed or not : ", f1.closed
print "Opening mode : ", f1.mode
69. File open modes
Mode Description
r Opens a file for reading only. The file pointer is
placed at the beginning of the file. This is the
default mode.
rb Opens a file for reading only in binary format. The
file pointer is placed at the beginning of the file. This
is the default mode.
r+ Opens a file for both reading and writing. The file
pointer is placed at the beginning of the file.
rb+ Opens a file for both reading and writing in binary
format. The file pointer is placed at the beginning of
the file.
70. File access modes
Mode Description
w Opens a file for writing only. Overwrites the file if
the file exists. If the file does not exist, creates a
new file for writing.
wb Opens a file for writing only in binary format.
Overwrites the file if the file exists. If the file does
not exist, creates a new file for writing.
w+ Opens a file for both writing and reading.
Overwrites the existing file if the file exists. If the file
does not exist, creates a new file for reading and
writing.
71. Mode Description
wb+
Opens a file for both writing and reading in binary
format. Overwrites the existing file if the file exists.
If the file does not exist, creates a new file for
reading and writing.
a Opens a file for appending. The file pointer is at the
end of the file if the file exists. That is, the file is in
the append mode. If the file does not exist, it creates
a new file for writing.
a+ Opens a file for both appending and reading. The
file pointer is at the end of the file if the file exists.
The file opens in the append mode. If the file does
not exist, it creates a new file for reading and
writing.
72. Closing, reading and writing files
close() method of file object closes the file
Syntax: fileObject.close();
write() and read() methods are used to read and write
files.
fileObject.read([count]);
Passed parameter is the number of bytes to be read from
the opened file. This method starts reading from the
beginning of the file and if count is missing, then it tries to
read as much as possible, maybe until the end of file.
73. Write() is used to write the data into the file.
fileObject.write(string);
fo = open(“python.txt", "wb")
fo.write( "Python is a good language.!n");
# Close opend file
fo.close()
Closing, reading and writing files
74. fo = open(“python.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()
Closing, reading and writing files
75. File Positions
tell() method tells you the current position within the file
seek(offset[, from]) method changes the current file position.
The offset argument indicates the number of bytes to be
moved.
The from argument specifies the reference position from
where the bytes are to be moved.
76. Example
# Open a file
fo = open(“ecm.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Check current position
position = fo.tell();
print "Current file position : ", position
# Reposition pointer at the beginning once again
position = fo.seek(0, 0);
str = fo.read(10);
print "Again read String is : ", str
# Close opend file
fo.close()
77. Renaming and Deleting Files
rename() method takes two arguments, the current
filename and the new filename.
os.rename(current_file_name, new_file_name)
Example:
import os
# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )
78. remove() Method
remove() method is used to delete files by supplying the
name of the file to be deleted as the argument.
os.remove(file_name)
Example:
import os
# Delete file test2.txt
os.remove("text2.txt")
79. Exception Handling
An exception is an event, that occurs during the execution of a
program and that disrupts the normal flow of the program
Execution.
An exception is a Python object that represents an error.
When an exception raises in python program, it must either
handle the exception immediately otherwise it terminates and
quits.
Handling an Exception
If any suspicious code that may raise an exception, then, place
the suspicious code in a try: block.
After the try: block, include an except: statement, followed by
a block of code which handles the problem as elegantly as
possible.
80. try and except blocks
try:
<block of statements> #main code to run
except <name1>: #handler for exception
<block of statements>
except <name2>,<data>: #handler for exception
<block of statements>
except (<name3>,<name4>): #handler for exception
<block of statements>
except: #handler for exception
<block of statements>
else: # optional, runs if no exception occurs
<block of statements>
81. Example
>>>try:
action()
except NameError(): …
except IndexError(): …
except KeyError(): …
except (AttributeError,TypeError,SyntaxError):…
else: ….
General catch-all clause: add empty except.
It may catch unrelated to your code system exceptions.
It may catch exceptions meant for other handler (system
exit)
83. elseelse is used to verify if no exception occurred in trytry.
You can always eliminate elseelse by moving its logic at the
end of the trytry block.
However, if “else statement” triggers exceptions, it
would be misclassified as exception in try block.
try/else
84. try/finally
In try/finallytry/finally, finallyfinally block is always run whether an
exception occurs or not
try:
<block of statements>
finally:
<block of statements>
Ensure some actions to be done in any case
It can not be used in the trytry with exceptexcept and elseelse.
85. Example for try .. finally
def division(x,y):
try:
return x/y
except ZeroDivisionError:
print("division by zero")
finally:
print("it executes compulsory")
89. Raise
raise triggers exceptions explicitly
raise <name>
raise <name>,<data> # provide data to handler
raise #re-raise last exception
>>>try:
raise ‘zero’, (3,0)
except ‘zero’: print “zero argument”
except ‘zero’, data: print data
Last form may be useful if you want to propagate cought
exception to another handler.
Exception name: built-in name, string, user-defined class