Python Programming Notes
Python Programming Notes
(LAB)
Week 1
What is Python?
• Python is a popular programming language.
It was created by Guido van Rossum, and
released in 1991.
• Python general purpose language used for:
• Web development (server-side),
• Software development,
• Mathematics,
• System scripting,
• AI Applications
Some facts about Python
• Python is currently the most widely used multi-purpose,
high-level programming language.
• It is being used by almost all tech-giant companies like –
Google, Amazon, Facebook, Instagram, Dropbox, Uber…
etc.
• The biggest strength of Python is huge collection of
standard library which can be used for the following –
• Machine Learning
• GUI Applications (like Kivy, Tkinter, PyQt etc. )
• Web frameworks like Django (used by YouTube,
Instagram, Dropbox)
• Image processing (like OpenCV, Pillow)
• Web scraping (like Scrapy, BeautifulSoup, Selenium)
• Test frameworks
• Multimedia
• Scientific computing
• Text processing and many more..
What is 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
Good to know about
Python?
• The most recent major version of Python is Python
3, Python 2 is older one,
• It is possible to write Python in an Integrated
Development Environments, which are particularly
useful when managing larger collections of Python
files.
• Spyder
• IDLE
• Thonny,
• Pycharm,
• Netbeans or
• Eclipse etc.
FIRST PROGRAM
Download and Installation
# Simple Program
print("Hello, Python!")r >python helloworld.py
•Save your file. Open your command line, navigate to the
directory where you saved your file, and run::\Users\Your
Name>python helloworld.py
Interactive Python (Command Line)
• To test a short amount of code in python sometimes
it is quickest and easiest not to write the code in a
file. This is made possible because Python can be
run as a command line itself
• Or, if the "python" command did not work, you can
try "py":C:\Users\Your Name
• Whenever you are done in the python command
line, use exit()exit()
Python Indentation
• :\Your
• Indentation refers to the spaces at the beginning of a code line.
• Where in other programming languages the indentation in code
is for readability only, the indentation in Python is very
important.
• Python uses indentation to indicate a block of code.
• Python uses new lines to complete a command, as opposed to
other programming languages which often use semicolons or
parentheses.
• Python relies on indentation, using whitespace, to define scope;
such as the scope of loops, functions and classes. Other
programming languages often use curly-brackets for this
purpose
Execute Python Syntax
•if 5 > 2:
print("Five is greater than two!")
•Python will give you an error if you skip the indentation:
•if 5 > 2:
print("Five is greater than two!")
•The number of spaces is up to you as a programmer, but
it has to be at least one.
•if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
•You have to use the same number of spaces in the same
block of code, otherwise it is an error:
•if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Python Comments
• Single Line Comments: (# Comment)
• Multiline Comments: (“”” Comment “””)
• Multiline Comments: (“”” Comment “””)
BUILT-IN DATA
TYPES
Built-in Datatypes
x="Muhammad Abdullah"
Method Output
print("Complete String:", x) Complete String: Muhammad
Abdullah
print("Index String:", x[0]) Index String: M
print("Index String:", x[-5]) Index String: u
print("Slicing String:", x[0:8]) Slicing String: Muhammad
print("Slicing String:", x[-8:-1]) Slicing String: Abdulla
print("Slicing String:", x[:8]) Slicing String: Muhammad
print("Slicing String:", x[9:]) Slicing String: Abdullah
String Datatype
• String Length
a = “ Hello, Python! "
print(len(a))
• String Methods
• print(a.strip()) # Removes beginning and ending spaces
• print(a.lower())
• print(a.upper())
• print(a.replace("H", "J"))
• Check String
in/not in: To check if a certain phrase or character is
present .
print("Python" in a) True
String Datatype
• Concatenation
a = "Hello"
b = "World"
c=a+""+b
print(c)
• We cannot concatenate number with string use
format for this purpose
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
String Datatype
Escape
Character
s
Dictionaries
• Dictionaries are lists of key-valued pairs.
In:
Out:
Exercise
In: Out:
In: Out:
Lists
• Lists are essentially containers
of arbitrary type.
• They are probably the
container that you will use In:
most frequently.
• The elements of a list can be
of different types.
• The difference between Out:
tuples and lists is in
performance; it is much faster
to ‘grab’ an element stored in
a tuple, but lists are much • Create a list and populate it with
more versatile. some elements.
• Note that lists are denoted by
[] and not the () used by
tuples.
Adding elements to a list
• Lists are mutable; i.e. their contents can be
changed. This can be done in a number of ways.
• With the use of an index to replace a current
element with a new one.
In: Out:
In: Out:
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
# Examples of Arithmetic Operator
a=9
b=4 Arithmetic Operat
add = a + b
sub = a - b
mul = a * b
div1 = a / b
div2 = a // b
mod = a % b
# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
# Examples of Relational Operators
a = 13
b = 33 Comparison
print(a > b) Operators
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
Logical
• # Examples of Logical Operator Operators
• a = True
• b = False
• print(a and b)
• print(a or b)
• print(not a)
Identity and Membership
Operators
• a , b=60 , 13
• print("a=",bin(a),"\nb=",bin(b))
• print("a&b=",bin(a&b)) Bitwise Operators
• print("a|b=",bin(a|b))
Operator Description Example
• print("a^b=",bin(a^b)) (a & b) (means 0000
& Binary AND
• print("a|b=",bin(a|b)) 1100)
(a | b) = 61 (means
| Binary OR
• print("~a=",bin(~a)) 0011 1101)
(a ^ b) = 49 (means
^ Binary XOR
• print("a<<2=",bin(a<<2)) 0011 0001)
(~a ) = -61 (means 1100
• print("a>>b=",bin(a>>2)) Binary Ones 0011 in 2's complement
~
Complement form due to a signed
binary number.
Binary Left a << 2 = 240 (means
<<
Shift 1111 0000)
Binary Right a >> 2 = 15 (means
>>
Shift 0000 1111)
Assignment
Operators
Operator Example
= c = a + b assigns value of a + b into c
+= c += a is equivalent to c = c + a
-= c -= a is equivalent to c = c - a
*= c *= a is equivalent to c = c * a
c /= a is equivalent to c = c / ac /= a is
/=
equivalent to c = c / a
%= c %= a is equivalent to c = c % a
**= c **= a is equivalent to c = c ** a
//= c //= a is equivalent to c = c // a
Sr.No. Operator & Description
1 ** Exponentiation (raise to the power)
Operator Precedence
2 ~ + - Complement, unary plus and minus
3 * / % // Arithmetic Operator
4 + - Arithmetic Operator
5 >> << Bitwise Shift
6 & Bitwise 'AND'
7 ^ | Bitwise exclusive `OR' and regular `OR'
8 <= < > >= Comparison operators
9 <> == != Equality operators
10 = %= /= //= -= += *= **= Assignment operators
11 is , is not Identity Operator
12 in , not in Membership Operator
13 not , or , and Logical operators
Turtle
Graphics
Turtle Graphics
• Is a module to draw graphic primitives (Line, Circle, Rectangle etc. )
• Import turtle module (Import Turtle )
• Useful Functions
• turtle.showturtle()
• turtle.backward(50)
• turtle.right(70)
• turtle.forward(50)
• turtle.goto(50,50)
• turtle.penup()
• turtle.pendown()
• turtle. circle(45)
• turtle.color(“blue”)
• turtle.pensize(3)
Example (Line Drawing)
• import turtle
• x1, y1=eval(input("Enter x1,y1:"))
• x2, y2=eval(input("Enter x2,y2:"))
• distance=((x1-x2)**2+(y1-y2)**2)**0.5
• #distance=format(distance,'10.2f')
• turtle.penup()
• turtle.goto(x1,y1)
• turtle.write("P1")
• turtle.pendown()
• turtle.goto(x2,y2)
• turtle.write("P2")
• turtle.penup()
• turtle.goto((x1+x2)/2, (y1+y2)/2)
• turtle.write(distance)
• turtle.hideturtle()
• turtle.done()
import turtle Example
turtle.pensize(3)
turtle.color("red")
turtle.penup()
# Triangle
turtle.goto(-200,-50)
turtle.pendown()
turtle.circle(40, steps=3)
# Rectangle
turtle.penup()
turtle.goto(-100,-50)
turtle.pendown()
turtle.circle(40, steps=4)
# Pentagon
turtle.penup()
turtle.goto(0,-50)
turtle.pendown()
turtle.circle(40, steps=5)
Example (filled region)
• # Octagon
• turtle.penup()
• turtle.goto(200,-50)
• turtle.begin_fill()
• turtle.color(“purple")
• turtle.pendown()
• turtle.circle(40, steps=8)
• turtle.end_fill()
SELECTIVE
Statements
SELECTIVE STATEMENTS
• def display(k):
• if(k>0): #Base Case
• display(k-1)
• print(k)
• #Driver Code
• a=eval(input("\n\nEnter a Number:"))
• display(a)