Python Programming Language
Introduction to python
• Python is a high-level, general-purpose and a very popular programming language.
• Python programming language is used in
• web development,
• software development,
• mathematics
• Machine Learning applications, along with all cutting edge technology in
Software Industry.
• It was created by Guido van Rossum, and released in 1991.
30/03/2024 Problem Solving Using Python 1
Python Programming Language
Why Python?
• Python works on different platforms
• 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
30/03/2024 Problem Solving Using Python 2
Variables
Variables are containers for storing data values.
Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Example
x=5
y = "John"
print(x)
print(y)
Output:
5
John
30/03/2024 Problem Solving Using Python 3
Python Variables
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 = “peter" # x is now of type str
print(x)
Output:
peter
30/03/2024 Problem Solving Using Python 4
Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
print(x)
print(y)
print(z)
Output:
3
3
3.0
30/03/2024 Problem Solving Using Python 5
Get the Type
You can get the data type of a variable with the type() function.
Example
x=5
y = "John"
print(type(x))
print(type(y))
Output:
<class 'int'>
<class 'str'>
Note:
• String variables can be declared either by using single or double quotes:
30/03/2024 Problem Solving Using Python 6
Variable
Variable names are case-sensitive.
a=4
A = “Joy“ #A will not overwrite a
print(a)
print(A)
Output:
4
Joy
30/03/2024 Problem Solving Using Python 7
Rules for Python variables
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
Rules for Python variables:
A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores
(A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
30/03/2024 Problem Solving Using Python 8
Example
Example
Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John“
print(myvar)
print(my_var)
print(_my_var)
print(myVar)
print(MYVAR)
print(myvar2)
30/03/2024 Problem Solving Using Python 9
Example
llegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"
Remember that variable names are case-sensitive
30/03/2024 Problem Solving Using Python 10
Python Variables - Assign Multiple Values
23 12.5 PYTHON
23 12.5 PYTHON
23 12.5 PYTHON
23 12.5 PYTHON
23 12.5 PYTHON
Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line:
Make sure the number of variables matches the number of values, or else you will get an error.
Example
x, y, z = 23,12.5,”PYTHON”
print(x)
print(y)
print(z)
OUTPUT :
23
12.5
PYTHON
30/03/2024 Problem Solving Using Python 11
One Value to Multiple Variables
• And you can assign the same value to multiple variables in one line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
OUTPUT:
Orange
Orange
Orange
30/03/2024 Problem Solving Using Python 12
Unpack a list
456 78.678 apple
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the values into variables. This is
called unpacking.
Example
Unpack a list:
list1 = [456,78.678,"apple"]
x, y, z = list1
print(x)
print(y)
print(z)
Output:
456
78.678
apple
30/03/2024 Problem Solving Using Python 13
Print function
Print function is often used to output the value of a variable. In print function you output
multiple variables separated by comma.
Example 1
x = "Python is awesome"
print(x)
Output
Python is awesome
Example 2
x = "Python"
y = 68
z = 34.5
print(x, y, z)
Output: Python 68 34.5
30/03/2024 Problem Solving Using Python 14
Print function
You can write an expression also inside print
x=5
y = 10
print(x + y)
Output
15
30/03/2024 Problem Solving Using Python 15
Python Data Types
Built-in Data Types
Variables can store data of different types. Python has the following built-in data types :
Text Type: str
Numeric int, float, complex
Types:
Sequence list, tuple, range
Types:
Mapping dict
Type:
Set Types: set,
Boolean Type: bool
Binary Types: bytes,
None Type: NoneType
30/03/2024 Problem Solving Using Python 16
Getting the Data Type
You can get the data type of any object by using the type function
Example : Print the data type of the variable x:
x=5
print(type(x))
Output:
<class 'int'>
30/03/2024 Problem Solving Using Python 17
Setting the Data Type
In python the data type is set when you assign a value to a variable:
30/03/2024 Problem Solving Using Python 18
Data type- Numeric
There are three numeric types in Python:
1. int
2. float
3. 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
30/03/2024 Problem Solving Using Python 19
1.Integers
Int
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
Example
x=1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'int'>
<class 'int'>
<class 'int'>
30/03/2024 Problem Solving Using Python 20
2.Float
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.
Example
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Output
<class 'float'>
<class 'float'>
<class 'float'>
30/03/2024 Problem Solving Using Python 21
Float
Float can also be scientific numbers with an "e" to indicate the power of 10.
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Output
<class 'float'>
<class 'float'>
<class 'float'>
30/03/2024 Problem Solving Using Python 22
3.Complex numbers
Complex numbers are written with a "j" as the imaginary part:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Output
<class 'complex'>
<class 'complex'>
<class 'complex'>
30/03/2024 Problem Solving Using Python 23
Type Conversion
You can convert from one type to another with the int(), float(),
and complex() methods:
x=1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
Note : You cannot convert complex numbers into another number type.
30/03/2024 Problem Solving Using Python 24
Type Conversion
Example 1
x = int(1)
y = int(2.8)
z = int("3")
print(x)
print(y)
print(z)
Output:
1
2
3
30/03/2024 Problem Solving Using Python 25
Type Conversion
Example 2
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
print(x)
print(y)
print(z)
print(w)
Output:
1.0
2.8
3.0
4.2
30/03/2024 Problem Solving Using Python 26
Type Conversion
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0‘
print(x)
print(y)
print(z)
Output:
s1
2
3.0
30/03/2024 Problem Solving Using Python 27
Strings
• Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters.
• However, Python does not have a character data type, a single character is simply a string
with a length of 1.
• Square brackets can be used to access elements of the string.
Example
Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1])
Output:
e
30/03/2024 Problem Solving Using Python 28
String Length
String Length
To get the length of a string, use the len() function.
Example
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
Output
13
30/03/2024 Problem Solving Using Python 29
Check a string
To check if a certain phrase or character is present in a string, we can use
the keyword in.
Example
Check if "free" is present in the following text:
txt = "The best things in life are free!"
print("free" in txt)
Output:
True
30/03/2024 Problem Solving Using Python 30
Check a string
Example
Check if "expensive" is NOT present in the following text:
txt = "The best things in life are free!"
print("expensive" not in txt)
Output:
True
30/03/2024 Problem Solving Using Python 31
Slicing Strings
Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the string.
The first character has index 0.
Example
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
Output:
llo
30/03/2024 Problem Solving Using Python 32
Slice From the Start
• By leaving out the start index, the range will start at the first character:
Example
Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])
OUTPUT:
Hello
30/03/2024 Problem Solving Using Python 33
Slice To the End
Slice To the End
By leaving out the end index, the range will go to the end:
Example
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
OUTPUT:
llo, World!
30/03/2024 Problem Solving Using Python 34
Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example
Get the characters:
From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -2):
b = "Hello, World!"
print(b[-5:-2])
OUTPUT:
orl
30/03/2024 Problem Solving Using Python 35
Modify Strings
• Python has a set of built-in methods that you can use on strings.
Upper Case
Upper() method returns the string in upper case.
Example
a = "Hello, World!"
print(a.upper())
OUTPUT:
HELLO, WORLD!
30/03/2024 Problem Solving Using Python 36
Modify Strings
• Python has a set of built-in methods that you can use on strings.
Lower Case
lower() method returns the string in lower case.
Example
a = "Hello, World!"
print(a.lower())
OUTPUT:
hello, world!
30/03/2024 Problem Solving Using Python 37
Remove Whitespace
Whitespace is the space before and/or after the actual text, and
very often you want to remove this space.
Example
The strip() method removes any whitespace from the
beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
OUTPUT:
Hello, World!
30/03/2024 Problem Solving Using Python 38
Booleans
Booleans represent one of two values: True or False.
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:
print(10 > 9)
print(10 == 9)
print(10 < 9)
OUTPUT:
True
False
False
30/03/2024 Problem Solving Using Python 39
Booleans
Replace String
Example
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
30/03/2024 Problem Solving Using Python 40
Boolean Values
Most Values are True
Almost any value is evaluated to True if it has some sort of content.
Any string is True, except empty strings.
Any number is True, except 0.
Any list, tuple, set, and dictionary are True, except empty ones.
Example
The following will return True:
bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])
OUTPUT
True
True
True
30/03/2024 Problem Solving Using Python 41
Boolean Values
In fact, there values that evaluate to False, such as empty values, ex- (), [], {}, "", the
number 0, and the value None. And of course the value False evaluates to False
Some Values are False
The following will return False:
print(bool(False))
print(bool(None))
print(bool(0))
print(bool(""))
print(bool(()))
print(bool([]))
print(bool({}))
Output
False
False
False
False
False
False
False
30/03/2024 Problem Solving Using Python 42
operators
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
30/03/2024 Problem Solving Using Python 43
Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical
operations:
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
30/03/2024 Problem Solving Using Python 44
Arithmetic Operators
• EX
x = 15
y=2
print(x // y)
OUTPUT
7
#the floor division // rounds the result down to the nearest whole number
30/03/2024 Problem Solving Using Python 45
Assignment Operators
Python Assignment Operators Assignment operators are used to assign values to variables:
Operator Example Same As
= 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
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
30/03/2024 <<= x <<= 3 Solving Using Python x = x << 3
Problem 46
Python Comparison Operators
Comparison operators are used to compare two values:
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <=
30/03/2024 Problem Solving Using Python 47
Python Logical Operators
Logical operators are used to combine conditional statements:
Operator Description Example
and Returns True if both x < 5 and x < 10
statements are true
or Returns True if one of the x < 5 or x < 4
statements is true
not Reverse the result, not(x < 5 and x < 10)
returns False if the result
is true
30/03/2024 Problem Solving Using Python 48
Python Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:
Operator Description Example
is Returns True if both x is y
variables are the same
object
is not Returns True if both x is not y
variables are not the
same object
30/03/2024 Problem Solving Using Python 49
Python Identity Operators
x = [23, 45.6, "Python"]
y = [23, 45.6, "Python"]
z=x
print(x is z)
# returns True because z is the same object as x
print(x is y)
#returns False because x is not the same object as y, even if they have the same content
print(x == y)
# to demonstrate the difference betweeen "is" and "==": this comparison returns True because x is equal
to y
Output:
True
False
True
30/03/2024 Problem Solving Using Python 50
Python Membership Operators
Operator Description Example
in Returns True if a sequence x in y
with the specified value is
present in the object
not in Returns True if a sequence x not in y
with the specified value is
not present in the object
Ex
x = ["apple", 45, 56.5]
print(45 in x)
Output:
True
30/03/2024 Problem Solving Using Python 51
Python Bitwise Operators
Bitwise operators are used to compare (binary) numbers:
Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill Shift left by pushing zeros in from the right and let the leftmost
left shift bits fall off
>> Signed Shift right by pushing copies of the leftmost bit in from the left,
right and let the rightmost bits fall off
shift
30/03/2024 Problem Solving Using Python 52