Unit 1 Python
Unit 1 Python
Introduction to python
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:
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
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'>
print(type(x))
print(type(y))
print(type(z))
Output
<class 'float'>
<class 'float'>
<class 'float'>
print(type(x))
print(type(y))
print(type(z))
Output
<class 'complex'>
<class 'complex'>
<class 'complex'>
print(type(a))
print(type(b))
print(type(c))
Note : You cannot convert complex numbers into another number type.
Example
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
Output
13
Example
Check if "free" is present in the following text:
Output:
True
Output:
True
b = "Hello, World!"
print(b[-5:-2])
OUTPUT:
orl
OUTPUT:
HELLO, WORLD!
OUTPUT:
hello, world!
Example
The strip() method removes any whitespace from the
beginning or the end:
OUTPUT:
Hello, World!
30/03/2024 Problem Solving Using Python 38
Booleans
Booleans represent one of two values: True or False.
print(10 > 9)
print(10 == 9)
print(10 < 9)
OUTPUT:
True
False
False
Replace String
Example
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
Example
bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])
OUTPUT
True
True
True
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.
== Equal x == y
!= Not equal x != y
Ex
x = ["apple", 45, 56.5]
print(45 in x)
Output:
True