0% found this document useful (0 votes)
119 views

Week 1 Introduction To Python

Uploaded by

Al Imran
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
119 views

Week 1 Introduction To Python

Uploaded by

Al Imran
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 53

OOP II ~ Python

Sheikh Abujar
sheikh[dot]cse[at]diu.edu.bd
cybermanbd[at]gmail.com
In Class !
Why Program?
Real Problems !
Real Problems Cont.

The bark of a dog


The bark you find on a tree
Please Answer :

What’s North of the North Pole?
Please Answer :
Python is a general-purpose interpreted, interactive, language. It was created by Guido
van Rossum during 1985- object-oriented, and high-level programming 1990. Like Perl,
Python source code is also available under the GNU General Public License (GPL).

Python is designed to be highly readable. It uses English keywords frequently


where as other languages use punctuation, and it has fewer syntactical
constructions than other languages.
Computers Want to be Helpful...
What
• Computers are built for one purpose - to Next?
do things for us

• But we need to speak their language to


describe what we want done

• Users have it easy - someone already put What What What


many different programs (instructions) into Next? Next? Next?
the computer and users just pick the ones
they want to use What What What
Next? Next? Next?
Users vs. Programmers
• Users see computers as a set of tools - word processor, spreadsheet,
map, to-do list, etc.

• Programmers learn the computer “ways” and the computer language

• Programmers have some tools that allow them to build new tools

• Programmers sometimes write tools for lots of users and sometimes


programmers write little “helpers” for themselves to automate a task
User

Computer
Programmer
Hardware + Software

Data Information .... Networks


What is Code? Software? A Program?

• A sequence of stored instructions

- It is a little piece of our intelligence in the computer

- We figure something out and then we encode it and then give it to


someone else to save them the time and energy of figuring it out

• A piece of creative art - particularly when we do a good job on user


experience
Hardware Architecture
Generic
Software What
Next? Computer
Input Central
and Output Processing
Devices Unit
Secondary
Memory

Main
Memory
Generic
Software What
Next? Computer
Input Central
and Output Processing
Devices Unit
Secondary
if x< 3: print Memory

Main
Memory
Generic
Software What
Next? Computer
Input Central
and Output Processing
Devices Unit
01001001 Secondary
00111001 Memory

Main
Memory
Machine
Language
Python as a Language
Python is the language of the Python
Interpreter and those who can converse with
it. An individual who can speak Python is
known as a Pythonista. It is a very uncommon
skill, and may be hereditary. Nearly all known
Pythonistas use software initially developed by
Guido van Rossum.
Early Learner: Syntax Errors
• We need to learn the Python language so we can communicate our
instructions to Python. In the beginning we will make lots of mistakes and
speak gibberish like small children.

• When you make a mistake, the computer does not think you are “cute”. It
says “syntax error” - given that it knows the language and you are just
learning it. It seems like Python is cruel and unfeeling.

• You must remember that you are intelligent and can learn. The computer is
simple and very fast, but cannot learn. So it is easier for you to learn Python
than for the computer to learn English...
Talking to Python
csev$ python3
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwinType
"help", "copyright", "credits" or "license" for more information.
>>>
What
next?
csev$ python3
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwinType
"help", "copyright", "credits" or "license" for more information.
>>> x = 1
>>> print(x)
1
>>> x = x + 1 This is a good test to make sure that you have
>>> print(x) Python correctly installed. Note that quit() also
2 works to end the interactive session.
>>> exit()
What Do We Say?
Elements of Python
• Vocabulary / Words - Variables and Reserved words (Chapter 2)

• Sentence structure - valid syntax patterns (Chapters 3-5)

• Story structure - constructing a program for a purpose


Reserved Words
You cannot use reserved words as variable names / identifiers

False class return is finally


None if for lambda continue
True def from while nonlocal
and del global not with
as elif try or yield
assert else import pass
break except in raise
Sentences or Lines

x=2 Assignment statement


x=x+2 Assignment with expression
print(x) Print statement

Variable Operator Constant Function


Programming Paragraphs
Python Scripts
• Interactive Python is good for experiments and programs of 3-4 lines
long.

• Most programs are much longer, so we type them into a file and tell
Python to run the commands in the file.

• In a sense, we are “giving Python a script”.

• As a convention, we add “.py” as the suffix on the end of these files


to indicate they contain Python.
Interactive versus Script

• Interactive

- You type directly to Python one line at a time and it responds

• Script

- You enter a sequence of statements (lines) into a file using a text


editor and tell Python to execute the statements in the file
Program Steps or Program Flow
• Like a recipe or installation instructions, a program is a sequence
of steps to be done in order.

• Some steps are conditional - they may be skipped.

• Sometimes a step or group of steps is to be repeated.

• Sometimes we store a set of steps to be used over and over as


needed several places throughout the program (Chapter 4).
Sequential Steps
x=2 Program:
Output:
print(x) x=2
print(x) 2
x=x+2 x=x+2 4
print(x)
print(x)

When a program is running, it flows from one step to the next. As


programmers, we set up “paths” for the program to follow.
x=5
Conditional Steps
Yes
x < 10 ?

print('Smaller') Program:
No Output:
x=5
Yes if x < 10: Smaller
x > 20 ? print('Smaller') Finis
if x > 20:
print('Bigger') print('Bigger')
No
print('Finis')

print('Finis')
n=5 Repeated Steps
No Yes Output:
n>0? Program:
5
print(n) n=5 4
while n > 0 :
3
print(n)
n = n -1 n=n–1 2
print('Blastoff!') 1
Blastoff!
Loops (repeated steps) have iteration variables that
print('Blastoff')
change each time through a loop.
name = input('Enter file:')
handle = open(name, 'r') Sequential
Repeated
counts = dict()
for line in handle: Conditional
words = line.split()
for word in words:
counts[word] = counts.get(word,0) + 1

bigcount = None
bigword = None
for word,count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count

print(bigword, bigcount)
name = input('Enter file:') A short Python “Story”
handle = open(name, 'r') about how to count
counts = dict()
words in a file
for line in handle:
words = line.split() A word used to read
for word in words: data from a user
counts[word] = counts.get(word,0) + 1

bigcount = None A sentence about


bigword = None updating one of the
for word,count in counts.items(): many counts
if bigcount is None or count > bigcount:
bigword = word
bigcount = count A paragraph about how
to find the largest item
print(bigword, bigcount) in a list
Python is the language of the Python Interpreter and
those who can converse with it. An individual who can
speak Python is known as a Pythonista. It is a very
uncommon skill, and may be hereditary. Nearly all
known Pythonistas use software initially developed by
Guido van Rossum  and released in 1991.
It is used for:
•web development (server-side),
•software development,
•mathematics,
•system scripting.
Why Python?
•Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, (etc.)
•Python has a simple syntax similar to the English language.
•Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
•Python runs on an interpreter system, meaning that code can be executed as soon
as it is written. This means that prototyping can be very quick.
•Python can be treated in a procedural way, an object-orientated way or a
functional way.
Python Syntax

>>> print("Hello, World!")


Hello, World!
Python Variables
Variables are containers for storing data values.
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.

Example
x = 40  # x is of type int
x = 50
x = ”shifat”  # x is now of type str
y = “Bangladesh"
print(x)
print(x)
Print(type(x))
print(y)
Built-in Data Types

Text Type: str

Numeric int, float, complex
Types:
Sequence list, tuple, range
Types:
Mapping dict
Type:
Set Types: set, frozenset
Boolean bool
Type:
Binary bytes, bytearray, memoryview
Types:
Arithmetic operators
OPERATOR DESCRIPTION SYNTAX

+ Addition: adds two operands x+y

- Subtraction: subtracts two operands x-y

Multiplication: multiplies two


* x*y
operands

Division (float): divides the first


/ x/y
operand by the second

Division (floor): divides the first


// x // y
operand by the second

Modulus: returns the remainder when


% x%y
first operand is divided by the second

Power : Returns first raised to power


** x ** y
second
Relational Operators

OPERATOR DESCRIPTION SYNTAX


Greater than: True if left
> operand is greater than the x>y
right
Less than: True if left operand
< x<y
is less than the right
Equal to: True if both
== x == y
operands are equal
Not equal to - True if
!= x != y
operands are not equal
Greater than or equal to: True
>= if left operand is greater than x >= y
or equal to the right
Less than or equal to: True if
<= left operand is less than or x <= y
equal to the right
Assignment operators
OPERATOR DESCRIPTION SYNTAX
Assign value of right side of expression to left side
= operand
x=y+z

Add AND: Add right side operand with left side


+= operand and then assign to left operand
a+=b     a=a+b

Subtract AND: Subtract right operand from left


-= operand and then assign to left operand
a-=b       a=a-b

Multiply AND: Multiply right operand with left


*= operand and then assign to left operand
a*=b       a=a*b

Divide AND: Divide left operand with right operand


/= and then assign to left operand
a/=b         a=a/b

Modulus AND: Takes modulus using left and right


%= operands and assign result to left operand
a%=b   a=a%b

Divide(floor) AND: Divide left operand with right


//= operand and then assign the value(floor) to left a//=b       a=a//b
operand

Exponent AND: Calculate exponent(raise power) value


**= using operands and assign value to left operand
a**=b     a=a**b
Print Function
The built-in print function displays its argument(s) as a line of text:

In [1]: print('Welcome to Python!')


Welcome to Python!

Printing a Comma-Separated List of Items

In [2]: print('Welcome', 'to', 'Python!')


Welcome to Python!

Printing Many Lines of Text with One Statement


When a backslash (\) appears in a string, it’s known as the escape character.

In [3]: print('Welcome\nto\n\nPython!')
Welcome
To

Python!
Other Escape Sequences

Escape sequence Description

\n Insert a newline character in a string. When the string is


displayed , for each newline, move the screen cursor to the
beginning of the next line.

\t Insert a horizontal tab. When the string is displayed, for each


tab, move the screen cursor to the next tab stop.

\\ Insert a backslash character in a string.

\” Insert a double quote character in a string.

\’ Insert a single quote character in a string.


Printing the Value of an Expression and some Escape Sequences

In [1]: print('Sum is', 7 + 3)


Sum is 10
In [2]: print('Display \'hi\' in quotes')
Display 'hi' in quotes
Ln [3]: print("Display \"hi\" in quotes")
Display "hi" in quotes

In [4]: print("""Display "hi" and 'bye' in quotes""")


Display "hi" and 'bye' in quotes
Getting Input from the User

In [1]: name = input("What's your name? ")


What's your name? Paul
In [2]: print(name)
Paul

In [3]: value1 = input('Enter first number: ')


Enter first number: 7
In [4]: value2 = input('Enter second number: ‘)
Enter second number: 3
In [5]: value1 + value2
Out[9]: '73'
Multiple Input from the User

In [1]: a , b = input().split()
5 10
In [2]: Print(a , b)
5 10
In [3]: Print(type(a))
<class ‘str’>
Objects and Dynamic Typing
• In [1]: type(7)
• Out[1]: int
• In [2]: type(4.1)
• Out[2]: float
• In [3]: type('dog')
• Out[3]: str

Values such as 7 (an integer), 4.1 (a floating-point number) and 'dog' are all objects. Every object has a type and a
value. An object’s value is the data stored in the object. The snippets above show objects of Python built-in types
int (for integers), float (for floating-point numbers) and str (for strings).
Variables Refer to Objects

Assigning an object to a variable binds (associates) that variable’s name to the object. As you’ve seen, you can
then use the variable in your code to access the object’s value:
• In [4]: x = 7
• In [5]: x + 10
• Out[5]: 17
• In [6]: x
• Out[6]: 7
After snippet [4]’s assignment, the variable x refers to the integer object containing 7. As shown in snippet [6],
snippet [5] does not change x’s value. You can change x as follows:
• In [7]: x = x + 10
• In [8]: x
• Out[8]: 17
Dynamic Typing

• Python uses dynamic typing—it determines the type of the object a variable refers to while executing your
code. We can show this by rebinding the variable x to different objects and checking their types:
• In [9]: type(x)
• Out[9]: int
• In [10]: x = 4.1
• In [11]: type(x)
• Out[11]: float
• In [12]: x = 'dog'
• In [13]: type(x)
• Out[13]: str
Getting Your Questions Answered
Online forums enable you to interact with other Python programmers and get your Python questions answered.
Popular Python and general programming forums include:

• python-forum.io
• StackOverflow.com
• https://www.dreamincode.net/forums/forum/29-python/

Colab Notebook for lab

Thank You

You might also like