PYTHON
PYTHON
GOVERNMENT COLLEGE
WOMEN
UNIVERSITY FASILABAD
SUBMITTED BY:
NAME JUWAIRIA
KHALID
SEMESTER 3rd MA
DEP. MATH
SUBJECT: PROGRAMING
WITH PYTHON
SUBMITTED TO:
MAM MERISH
DATE OF SUBMISSION:
24 OCT. 2024
NAME: JUWAIRIA KHALID
ROLL NO: 39
COURSE: PROGRAMING
WITH PYTHON
What is Python?
Python is a popular programming language.
It is often applied in scripting roles.
It was created by Guido van Rossum, and released in 1991
.It is scripting language.
Is is also called interpreted language.
Why Python?
High demand in indrustry.
Easy to learn
Versatile applications
Large community support
Cross platfoam compatibility
Example: 1
Num 1 = 6.5
Num 2 = .37
Sum = num1+num2
Print (‘The sum of {0} and {1} is {12}. format)
(*args num1,num2,sum))
Example:2
Num1=input(‘Enter 1 number:’)
Num2=input(‘Enter 2 number:’)
Sum=float(num1)+(num2)
Print(‘The sum of {0}and{1}is{2} ‘.
format(*args num1,num2,sum))
Python Syntax
Execute Python Syntax
As we learned in the previous page, Python syntax can be executed by
writing directly in the Command Line:
Or by creating a python file on the server, using the .py file extension, and
running it in the Command Line:
Python Indentation
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.
Example
Python Comments
Comments can be used to explain Python code.
Creating a Comment
Comments starts with a #, and Python will ignore them:
Example
#This is a comment
print("Hello, World!")
Comments can be placed at the end of a line, and Python will ignore the
rest of the line:
Example
A comment does not have to be text that explains the code, it can also be
used to prevent Python from executing code:
Example
#print("Hello, World!")
print("Cheers, Mate!")
Multiline Comments
Python does not really have a syntax for multiline comments.
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Since Python will ignore string literals that are not assigned to a variable,
you can add a multiline string (triple quotes) in your code, and place your
comment inside it:
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Python Variables
Variables
Variables are containers for storing data values.
Creating Variables
Python has no command for declaring a variable.
Example
x = 5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type, and can
even change type after they have been set.
Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Casting
If you want to specify the data type of a variable, this can be done with
casting.
Example
Example
x = 5
y = "John"
print(type(x))
print(type(y))
Example
x = "John"
# is the same as
x = 'John'
Case-Sensitive
Variable names are case-sensitive.
Example
a = 4
A = "Sally"
#A will not overwrite a
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:
Example
x = 5
print(type(x))
Example Data
Type
x = 20 int
x = 20.5 float
x = 1j complex
x = range(6) range
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryv
iew
x = None NoneTyp
e
Example Data
Type
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = range(6) range
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryv
iew
Python Numbers
Python Numbers
There are three numeric types in Python:
int
float
complex
Variables of numeric types are created when you assign a value to them:
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
To verify the type of any object in Python, use the type() function:
Example
print(type(x))
print(type(y))
print(type(z))
Int
Int, or integer, is a whole number, positive or negative, without decimals,
of unlimited length.
Example
Integers:
x = 1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Float
Float, or "floating point number" is a number, positive or negative,
containing one or more decimals.
Example
Floats:
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Float can also be scientific numbers with an "e" to indicate the power of
10.
Example
Floats:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Complex
Complex numbers are written with a "j" as the imaginary part:
Example
Complex:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Type Conversion
You can convert from one type to another with the int(), float(),
and complex() methods:
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
Random Number
Python does not have a random() function to make a random number, but
Python has a built-in module called random that can be used to make
random numbers:
Example
Import the random module, and display a random number between 1 and 9:
import random
print(random.randrange(1, 10))
In our Random Module Reference you will learn more about the Random
module.
Python Casting
Specify a Variable Type
There may be times when you want to specify a type on to a variable. This
can be done with casting. Python is an object-orientated language, and as
such it uses classes to define data types, including its primitive types.
Example
Integers:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Example
Floats:
Example
Strings:
Python Strings
Strings
Strings in python are surrounded by either single quotation marks, or
double quotation marks.
Example
print("Hello")
print('Hello')
Example
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')
Example
a = "Hello"
print(a)
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
Example
However, Python does not have a character data type, a single character
is simply a string with a length of 1.
Example
Get the character at position 1 (remember that the first character has the
position 0):
a = "Hello, World!"
print(a[1])
Example
for x in "banana":
print(x)
String Length
To get the length of a string, use the len() function.
Example
a = "Hello, World!"
print(len(a))
Check String
To check if a certain phrase or character is present in a string, we can use
the keyword in.
Example
Example
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can
use the keyword not in.
Example
Use it in an if statement:
Example
Python Booleans
Booleans represent one of two values: True or False.
Boolean Values
In programming you often need to know if an expression is True or False.
You can evaluate any expression in Python, and get one of two
answers, True or False.
When you compare two values, the expression is evaluated and Python
returns the Boolean answer:
Example
print(10 > 9)
print(10 == 9)
print(10 < 9)
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Example
print(bool("Hello"))
print(bool(15))
Example
x = "Hello"
y = 15
print(bool(x))
print(bool(y))
Any list, tuple, set, and dictionary are True, except empty ones.
Example
bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])
Example
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
One more value, or object in this case, evaluates to False, and that is if
you have an object that is made from a class with a __len__ function that
returns 0 or False:
Example
class myclass():
def __len__(self):
return 0
myobj = myclass()
print(bool(myobj))
Example
def myFunction() :
return True
print(myFunction())
Example
def myFunction() :
return True
if myFunction():
print("YES!")
else:
print("NO!")
Python also has many built-in functions that return a boolean value, like
the isinstance() function, which can be used to determine if an object is
of a certain data type:
Example
x = 200
print(isinstance(x, int))
Python Operators
Python Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example
print(10 + 5)
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiatio x ** y
n
// Floor division x // y
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
:= print(x := 3) x=3
print(x)
== Equal x == y
!= Not equal x != y
and Returns True if both statements are true x < 5 and x < 10
not Reverse the result, returns False if the not(x < 5 and x <
result is true 10)
is not Returns True if both variables are not the same x is not y
object
<< Zero fill Shift left by pushing zeros in from the x << 2
left shift right and let the leftmost bits fall off
Operator Precedence
Operator precedence describes the order in which operations are
performed.
Example
print((6 + 3) - (6 + 3))
Example
print(100 + 5 * 3)
The precedence order is described in the table below, starting with the highest
precedence at the top:
Operator Description
() Parentheses
** Exponentiation
^ Bitwise XOR
| Bitwise OR
and AND
or OR
Example
print(5 + 4 - 7 + 3)
Python Lists
mylist = ["apple", "banana", "cherry"]
List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of
data, the other 3 are Tuple, Set, and Dictionary, all with different qualities
and usage.
Example
Create a List:
List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has
index [1] etc.
Ordered
When we say that lists are ordered, it means that the items have a defined
order, and that order will not change.
If you add new items to a list, the new items will be placed at the end of
the list.
Note: There are some list methods that will change the order, but in general: the
order of the items will not change.
Changeable
The list is changeable, meaning that we can change, add, and remove
items in a list after it has been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
List Length
To determine how many items a list has, use the len() function:
Example
Example
Example
type()
From Python's perspective, lists are defined as objects with the data type
'list':
<class 'list'>
Example
Example
Python Tuples
mytuple = ("apple", "banana", "cherry")
Tuple
Tuples are used to store multiple items in a single variable.
Example
Create a Tuple:
Tuple items are indexed, the first item has index [0], the second item has
index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a
defined order, and that order will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove
items after the tuple has been created.
Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Example
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
Print the number of items in the tuple:
Example
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Example
Example
type()
From Python's perspective, tuples are defined as objects with the data
type 'tuple':
<class 'tuple'>
Example
Example