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

Type Conversion in Python

Uploaded by

rajeshgoud0310
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Type Conversion in Python

Uploaded by

rajeshgoud0310
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Type Conversion in Python Repetition structures :

The act of changing an object’s data type is known as type While Loop in Python
conversion. The Python interpreter automatically performs
In Python, a while loop is used to execute a block of
Implicit Type Conversion. Python prevents Implicit Type
statements repeatedly until a given condition is satisfied.
Conversion from losing data.
When the condition becomes false, the line immediately
Implicit Type Conversion in Python after the loop in the program is executed.
In Implicit type conversion of data types in Python, the
count = 0
Python interpreter automatically converts one data type to
while (count < 3):
another without any user involvement. To get a more clear
count = count + 1
view of the topic see the below examples.
print("Hello Geek") o/p : Hello Geek
x = 10
Hello Geek
print("x is of type:",type(x))
Hello Geek
y = 10.6
For Loop in Python :
print("y is of type:",type(y))
For loops are used for sequential traversal. For example:
z=x+y traversing a list or string or array etc.
n=4
print(z)
for i in range(0, n):
print("z is of type:",type(z)) print(i) o/p : 0
1 2 3
o/p : x is of type: <class 'int'> Nested Loops in Python
y is of type: <class 'float'>
20.6 Python programming language allows to use one loop inside
z is of type: <class 'float'> another loop which is called nested loop. Following section
shows few examples to illustratconconcept. from
Explicit Type Conversion in Python __future__ import print_function
In Explicit Type Conversion in Python, the data type is for i in range(1, 5):
manually changed by the user as per their requirement. With
explicit type conversion, there is a risk of data loss since we for j in range(i):
are forcing an expression to be changed in some specific data
print(i, end=' ')
type.
print() o/p: 1
# initializing string
22
s = "10010"
333
# printing string converting to int base 2
4444
c = int(s,2)
Loop Control Statements
print ("After converting to integer base 2 : ", end="")
Continue Statement
print (c)
The continue statement in Python returns the control to the
# printing string converting to float
beginning of the loop.
e = float(s)
for letter in 'geeksforgeeks':
print ("After converting to float : ", end="")
if letter == 'e' or letter == 's':
print (e) o/p: After converting character to integer : 52
continue
After converting 56 to hexadecimal string : 0x38
After converting 56 to octal string : 0o70 print('Current Letter :', letter) o/p: Current Letter : g

Current Letter : k
Current Letter : f print("\nType of c: ", type(c)) 2.
2..Sequence Data Types in Python
Current Letter : o
The sequence Data Type in Python is the ordered collection
Current Letter : r
of similar or different Python data types.
Current Letter : g
Strings in Python are arrays of bytes representing Unicode
Current Letter : k characters. A string is a collection of one or more characters
put in a single quote, double-quote, or triple-quote.
Break Statement
List Data Type
The break statement in Python brings control out of the loop.
Lists are just like arrays, declared in other languages which is
for letter in 'geeksforgeeks':
an ordered collection of data. It is very flexible as the items
if letter == 'e' or letter == 's': in a list do not need to be of the same type.

break Creating a List in Python

print('Current Letter :', letter) Lists in Python can be created by just placing the sequence
inside the square brackets[].
o/p: Current Letter : e
# Empty list
Pass Statement
a = []
We use pass statement in Python to write empty loops. Pass
is also used for empty control statements, functions and # list with int values
classes.
a = [1, 2, 3]
for letter in 'geeksforgeeks':
print(a)
pass
# list with mixed int and string
print('Last Letter :', letter) o/p: Last Letter : s b = ["Geeks", "For", "Geeks", 4, 5]
data types print(b) o/p: [1, 2, 3]
1. Numeric Data Types in Python
['Geeks', 'For', 'Geeks', 4, 5]
The numeric data type in Python represents the data that
has a numeric value. A numeric value can be an integer, a Tuple Data Type
floating number, or even a complex number.
Just like a list, a tuple is also an ordered collection of Python
 Integers – This value is represented by int class. It objects. The only difference between a tuple and a list is that
contains positive or negative whole numbers tuples are immutable i.e. tuples cannot be modified after it is
(without fractions or decimals). created. It is represented by a tuple class.
 Float – This value is represented by the float class. It # initiate empty tuple
is a real number with a floating-point representation.
It is specified by a decimal point. t1 = ()

 Complex Numbers – A complex number is t2 = ('Geeks', 'For')


represented by a complex class. It is specified print("\nTuple with the use of String: ", t2)
as (real part) + (imaginary part)j . For example – 2+3j o/p : Tuple with the use of String: ('Geeks', 'For')
a=5 3. Boolean Data Type in Python
Python Data type with one of the two built-in values, T rue or
print("Type of a: ", type(a)) False. Boolean objects that are equal to True are truthy
(true), and those equal to False are falsy (false).
b = 5.0
print(type(True))
print("\nType of b: ", type(b))
print(type(False))
c = 2 + 4j
print(type(true))
4. Set Data Type in Python

In Python Data Types, a Set is an unordered collection of data


types that is iterable, mutable, and has no duplicate
elements.

# initializing empty set

s1 = set()

s1 = set("GeeksForGeeks")

print("Set with the use of String: ", s1)

s2 = set(["Geeks", "For", "Geeks"])

print("Set with the use of List: ", s2)

o/p: Set with the use of String: {'e', 'G', 's', 'F', 'o', 'r', 'k'}

Set with the use of List: {'For', 'Geeks'}

5. Dictionary Data Type in Python

A dictionary in Python is an unordered collection of data


values, used to store data values like a map, unlike other
Python Data Types that hold only a single value as an
element, a Dictionary holds a key: value pair. Key-value is
provided in the dictionary to make it more optimized.

# initialize empty dictionary

d = {}

d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}

print(d)

# creating dictionary using dict() constructor

d1 = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})

print(d1) o/p: {1: 'Geeks', 2: 'For', 3: 'Geeks'}

{1: 'Geeks', 2: 'For', 3: 'Geeks'}

String Manipulation in Python

some cool operations to manipulate the string. We will see


how we can manipulate the string in a Pythonic way. Strings
are fundamental and essential data structures that every
Python programmer works with.
frames 13.

14. btn1 = Button(frame, text="Submit", fg="red",activeb


ackground = "red")
 bg: This option used to represent the normal
background color displayed behind the label and 15. btn1.pack(side = LEFT)
indicator. 16.
 bd: This option used to represent the size of the 17. btn2 = Button(frame, text="Remove", fg="brown", ac
border around the indicator and the default tivebackground = "brown")
value is 2 pixels.
18. btn2.pack(side = RIGHT)
 cursor: By using this option, the mouse cursor
19.
will change to that pattern when it is over the
frame. 20. btn3 = Button(rightframe, text="Add", fg="blue", acti
vebackground = "blue")
 height: The vertical dimension of the new frame.
21. btn3.pack(side = LEFT)
 highlightcolor: This option used to represent the
22.
color of the focus highlight when the frame has
the focus. 23. btn4 = Button(leftframe, text="Modify", fg="black", a
ctivebackground = "white")
 highlightthickness: This option used to represent
the color of the focus highlight when the frame 24. btn4.pack(side = RIGHT)
does not have focus. 25.
 highlightbackground: This option used to 26. top.mainloop()
represent the thickness of the focus highlight..
Tkinter Button Options
 relief: The type of the border of the frame. It’s
 activebackground: Background color when the
default value is set to FLAT.
button is under the cursor.
 width: This option used to represents the width
 activeforeground: Foreground color when the
of the frame. button is under the cursor.
Frames  anchor: Width of the border around the outside of
1. from tkinter import * the button

2.  bd or borderwidth: Width of the border around the


outside of the button
3. top = Tk()
 bg or background: Normal background color.
4. top.geometry("140x100")
 command: Function or method to be called when
5. frame = Frame(top) the button is clicked.
6. frame.pack()  cursor: Selects the cursor to be shown when the
mouse is over the button.
7.
 text: Text displayed on the button.
8. leftframe = Frame(top)
 disabledforeground: Foreground color is used when
9. leftframe.pack(side = LEFT)
the button is disabled.
10.
 fg or foreground: Normal foreground (text) color.
11. rightframe = Frame(top)
 font: Text font to be used for the button’s label.
12. rightframe.pack(side = RIGHT)
 height: Height of the button in text lines
 highlightbackground: Color of the focus highlight  font=("Arial", 12),
when the widget does not have focus.
 height=2,
 highlightcolor: The color of the focus highlight when
 highlightbackground="black",
the widget has focus.
 highlightcolor="green",
 highlightthickness: Thickness of the focus highlight.
 highlightthickness=2,
 image: Image to be displayed on the button (instead
of text).  justify="center",
 justify: tk.LEFT to left-justify each line; tk.CENTER to  overrelief="raised",
center them; or tk.RIGHT to right-justify.
 padx=10,
 overrelief: The relief style to be used while the
mouse is on the button; default relief is tk.RAISED.  pady=5,

 padx, pady: padding left and right of the text. /  width=15,


padding above and below the text.  wraplength=100)
 width: Width of the button in letters (if displaying  button.pack(padx=20, pady=20)
text) or pixels (if displaying an image).
 root.mainloop()
 underline: Default is -1, underline=1 would underline
the second character of the button’s text. o/p :click me

 width: Width of the button in letters Python provides various options for developing graphical
user interfaces (GUIs). The most important features are
 wraplength: If this value is set to a positive number, listed below.
the text lines will be wrapped to fit within this
length.  Tkinter − Tkinter is the Python interface to the Tk
GUI toolkit shipped with Python. We would look at
 import tkinter as tk this option in this chapter.
 def button_clicked():  wxPython − This is an open-source Python interface
 print("Button clicked!") for wxWidgets GUI toolkit. You can find a complete
tutorial on WxPython here.
 root = tk.Tk()
 PyQt − This is also a Python interface for a popular
 # Creating a button with specified options cross-platform Qt GUI library. TutorialsPoint has a
very good tutorial on PyQt5 here.
 button = tk.Button(root,
 PyGTK − PyGTK is a set of wrappers written in Python
 text="Click Me",
and C for GTK + GUI library. The complete PyGTK
 command=button_clicked, tutorial is available here.

 activebackground="blue",  PySimpleGUI − PySimpleGui is an open source, cross-


platform GUI library for Python. It aims to provide a
 activeforeground="white",
uniform API for creating desktop GUIs based on
 anchor="center", Python's Tkinter, PySide and WxPython toolkits. For
a detaile PySimpleGUI tutorial, click here.
 bd=3,
 Pygame − Pygame is a popular Python library used
 bg="lightgray", for developing video games. It is free, open source
 cursor="hand2", and cross-platform wrapper around Simple
DirectMedia Library (SDL). For a comprehensive
 disabledforeground="gray", tutorial on Pygame, visit this link.
 fg="black",
 Jython − Jython is a Python port for Java, which gives
C++, C#, Java, Python, etc. are the examples of
Python scripts seamless access to the Java class Examples
OOP languages.
libraries on the local machinehttp
Procedural Programming
Parameter Object Oriented Programming
Procedural Programming is a programming language that
follows a step-by-step approach to break down a task into a
collection of variables and routines (or subroutines) through
a sequence of instructions.
Object-oriented Programming is a programming
language that uses classes and objects to create models Each step is carried out in order in a systematic manner so
based on the real world environment. that a computer can understand what to do.

In OOPs, it makes it easy to maintain and modify < In procedural programming, the main program is divided
existing code as new objects are created inheriting into small parts based on the functions and is treated as
characteristics from existing ones. separate program for individual smaller program.

< No such modifiers are introduced in procedural


programming.

< Procedural programming is less secure as compare to


OOPs.
In OOPs concept of objects and classes is
< There is no simple process to add data in procedural
introduced and hence the program is divided
Approach programming, at least not without revising the whole
into small chunks called objects which are
program.
instances of classes.
< Procedural programming divides a program into small
programs and each small program is referred to as a
function.
Access In OOPs access modifiers are introduced namely
modifiers as Private, Public, and Protected. < Procedural programming does not give importance to data.
In POP, functions along with sequence of actions are
Due to abstraction in OOPs data hiding is followed.
Security
possible and hence it is more secure than POP. < Procedural programming does not provide any inheritance.

<
OOPs due to modularity in its programs is less
complex and hence new data objects can be
Complexity C, BASIC, COBOL, Pascal, etc. are the examples POP languages.
created easily from existing objects making
object-oriented programs easy to modify

Program OOP divides a program into small parts and


division these parts are referred to as objects.

Importanc OOP gives importance to data rather than


e functions or procedures.

OOP provides inheritance in three modes i.e.


Inheritance
protected, private, and public
When designing classes in Python, consider the  Dependency Inversion Principle (DIP): High-level
following techniques: modules should not depend on low-level modules,
both should depend on abstractions.
1. Encapsulation:
6. Design Patterns:
 Bundle data and the methods that operate on that
data within a class.  Utilize design patterns to solve common design
problems.
 Use underscores (_) to denote private attributes and
methods, indicating they shouldn't be accessed  Examples include the Singleton pattern, Factory
directly from outside the class. pattern, and Decorator pattern.

 Provide getter and setter methods to control access 7. Docstrings:


to attributes if necessary.  Document your classes, methods, and attributes
2. Inheritance: using docstrings.

 Create a hierarchy of classes where subclasses  Explain the purpose, parameters, return values, and
inherit attributes and methods from parent classes. any exceptions raised.

 Use super() to access methods from the parent class 8. Testing:


within the subclass.  Write unit tests to ensure your classes behave as
 Avoid deep inheritance hierarchies to maintain code expected.
readability and maintainability.  Use a testing framework like unittest or pytest.
3. Polymorphism:

 Allow objects of different classes to be treated as if  Example:


 Python
they are of the same type.  class Animal:
def __init__(self, name):
 Use common interfaces (methods with the same self._name = name
name) across classes.
def make_sound(self):
 Make use of Python's duck typing, where the type of pass # Abstract method
an object is determined by its behavior rather than
its explicit type. class Dog(Animal):
def make_sound(self):
4. Composition: return "Woof!"

 Build classes by combining simpler objects. class Cat(Animal):


def make_sound(self):
 Use has-a relationships instead of is-a relationships return "Meow!"
(inheritance) when appropriate.

 This can lead to more flexible and maintainable code.

5. SOLID Principles:

 Single Responsibility Principle (SRP): A class should


have only one reason to change.

 Open-Closed Principle (OCP): Classes should be


open for extension but closed for modification.

 Liskov Substitution Principle (LSP): Subclasses


should be substitutable for their base classes
without affecting program correctness.

 Interface Segregation Principle (ISP): Interfaces


should be small and focused.
List Methods into words based on spaces. So, the resulting substrings list
contains each word as an element
Let’s look at different list methods in Python:
# code
 append(): Adds an element to the end of the list.
str=&quot;Geeks For Geeks&quot;
 copy(): Returns a shallow copy of the list.
substrings=str.split()
 clear(): Removes all elements from the list.
print(substrings) o/p : ['Geeks', 'For', 'Geeks']
 count(): Returns the number of times a specified
element appears in the list. Using Regular Expressions
 extend(): Adds elements from another list to the end We can use re.findall() method to find all the substrings with
of the current list. the regular expressions.we have used the regular expression
'w+' which matches one or more word characters. We then
 index(): Returns the index of the first occurrence of a
used re.findall() function to get all the strings based on the
specified element.
regular expression specified.
 insert(): Inserts an element at a specified position.
import re
 pop(): Removes and returns the element at the
str = &quot;GeeksforGeeks is best!&quot;
specified position (or the last element if no index is
specified). pattern = r'\w+'
 remove(): Removes the first occurrence of a substrings = re.findall(pattern, str)
specified element.
print(substrings) o/p : ['GeeksforGeeks', 'is', 'best']
 reverse(): Reverses the order of the elements in the
list.

 sort(): Sorts the list in ascending order (by default).

A String is a collection of characters arranged in a particular


order. A portion of a string is known as a substring.

Substring a string in Python

 Using String Slicing

 Using str.split() function

 Using Regular Expressions

 Using String Slicing to get the


Substring
 Consider the string " GeeksForGeeks is
best! ". Let's perform various string-
slicing operations to extract various
substrings
# code

str = &quot;GeeksForGeeks is best!&quot;

substring_start = str[:5]

print(substring_start) o/p: best!

Using str.split() function

We can use the split() function to get the substrings.The


split() method effectively splits the string "Geeks For Geeks"

You might also like