0% found this document useful (0 votes)
42 views88 pages

Python Fundamentals-1

The document discusses the Python programming language. It provides an introduction to Python including its creator, uses, features, and syntax. It also covers installing Python and running Python programs. The document contains information about Python's history, characteristics, structures, and more.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views88 pages

Python Fundamentals-1

The document discusses the Python programming language. It provides an introduction to Python including its creator, uses, features, and syntax. It also covers installing Python and running Python programs. The document contains information about Python's history, characteristics, structures, and more.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 88

PYTHON

BY AMIT PATEL
INTRODUCTION

▪ Created by Guido van Rossum, and released in 1991.

▪ It is used for:
▪ Data Analysis
▪ Machine Learning
▪ Artificial Intelligence
▪ Web Development Guido van Rossum
▪ Desktop Application
▪ System Programming
INTRODUCTION

▪ General purpose, Dynamic, high-level, and interpreted programming language.

▪ Simple and easy to learn and provides lots of high-level data structures.

▪ Python's syntax and dynamic typing make it an ideal language for scripting and rapid application
development.

▪ Syntax is the rules of how code is constructed

while Semantics are the overall effect the code has.


INTRODUCTION

▪ Python is not intended to work in a particular area, such as web programming.

▪ That is why it is known as multipurpose programming language because it can be used with web,
enterprise, 3D CAD, etc.

▪ We don't need to use data types to declare variable

because it is dynamically typed. so we can write a=10 to assign an integer value in an integer
variable.
Why 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-oriented way or a functional way.


First Python Program : Print “Hello World”

print("Hello World")

It takes only one statement without using a semicolon or curly braces in Python
Where Python is used?

• Desktop Applications
• Console-based Applications
• Mobile Applications
• Software Development
• Artificial Intelligence
• Web Applications
• Data Science and Machine Learning
• Computer Vision or Image Processing Applications.
• Speech Recognitions
Characteristics of Python

High Level Language

• It is very close to human language like English language so it is called high level language. So
we don’t need to remember syntax in Python.

Easy To Code

• Due to high level language it is very easy to write program in python than other language like c,
c++, c# etc. It is developer friendly language so anybody can easily learn and code in python.

Dynamic Typed Language

• It means data type is decided at run time not in advance. So no need to declare variable.
Characteristics of Python

Interpreted Language

• Code is executed line by line at a time when we code. There is no need to compile python code.
It makes easy to debug and run. Source code is converted into “Bytecode”.

Portable Language

• It can be run on any platform it means python program written in windows can easily run on Mac
or Linux platform.

Integrated Language

• We can integrate it with any programming language like c, c++, c#


Characteristics of Python

Large Standard Library

• It has large standard library which provide rich set of functionality so you don’t need to write
separate code.

Object Oriented Language

• It support features like class, object, encapsulation, inheritance etc.

Open Source

• It is freely available at its official websites : www.python.org/downloads/ . It is freely available for


public. So anybody can download as well as share it with others.
Structure of Python Programming Language

▪ Python programs are typically organized with one statement per line.

▪ The end of the statement delimited by the newline character that marks the end of the line.

▪ Extension of python program is “.py”

▪ There are so many IDE to run python program like Jupiter, PyCharm, VS Code
Structure of Python Programming Language

▪ Python Statements : In general, the interpreter reads and executes the statements line by line
i.e sequentially. Though, there are some statements that can alter this behavior like conditional
statements.

print('Welcome to Geeks for Geeks')


Structure of Python Programming Language

Multiple Statements per Line :

▪ We can also write multiple statements per line, but it is not a good practice as it reduces the
readability of the code.

▪ Try to avoid writing multiple statements in a single line.

▪ But, still you can write multiple lines by terminating one statement with the help of ‘;’.
▪ ‘;’ is used as the terminator of one statement in this case.

▪ For Example, consider the following code.


Structure of Python Programming Language

a = 10; b = 20; c = b + a
print(a); print(b); print(c)
Structure of Python Programming Language

▪ Python provides us the two ways to run a program:

1. Using Interactive interpreter prompt


2. Using a script file
Structure of Python Programming Language

Interactive interpreter prompt

▪ It provides us the feature to execute the Python statement one by one at the interactive prompt.

▪ It is preferable in the case where we are concerned about the output of each line of our Python
program.

▪ To open the interactive mode, open the terminal (or command prompt) and type “python”

▪ It will open the following prompt where we can execute the Python statement and check their
impact on the console.
Structure of Python Programming Language

This is python IDLE


Structure of Python Programming Language

▪ After writing the print statement, press the Enter key.

Here, we get the message "Hello World !" printed on the console.
PYTHON INSTALLATION

▪ Download from: https://www.python.org/downloads/


▪ Install into PC
▪ Open command prompt and type command
python –version
OR
py –version
Print the version of python, so it means python is install
▪ You can run command from cmd prompt directly.
▪ Other way is to open python IDLE
PYTHON ONLINE INTERPRETERS

Below, you’ll find links to some of the most popular online interpreters.

▪ https://www.python.org/shell/

▪ https://www.onlinegdb.com/online_python_interpreter

▪ https://repl.it/languages/python3

▪ https://www.tutorialspoint.com/execute_python3_online.php

▪ https://rextester.com/l/python3_online_compiler

▪ https://trinket.io/python3
Additional Python resources

Addition Resources

▪ Python 3.10.2 documentation : https://docs.python.org/3

▪ Subscribe to the Python tutor mailing list, where you can ask questions and collaborate with
other Python learners. : https://mail.python.org/mailman/listinfo/tutor

▪ Subscribe to the Python-announce mailing list to read about the latest updates in the
language.: https://mail.python.org/mailman3/lists/python-announce-list.python.org/

▪ https://dabeaz-course.github.io/practical-python/Notes/Contents.html
PYTHON IDLE

▪ Full Form : Integrated Development and Learning Environment

▪ Coded in 100% pure Python, using the tkinter GUI toolkit

▪ Cross-platform: works mostly the same on Windows, Unix, and macOS

▪ Python shell window (interactive interpreter) with colorizing of code input, output, and error messages

▪ Multi-window text editor with multiple undo, Python colorizing, smart indent, call tips, auto completion,
and other features

▪ Search within any window, replace within editor windows, and search through multiple files (grep)

▪ Debugger with persistent breakpoints, stepping, and viewing of global and local namespaces
Structure of Python Programming Language

Using Script File

▪ Using the script mode, we can write multiple lines code into a file which can be executed later.

▪ For this purpose, we need to open an editor like notepad, create a file named and save it

with .py extension, which stands for "Python".

print ("hello world"); #here, we have used print() function to print the message on the console.

▪ To run this file named as first.py, we need to run the following command on the terminal.
Structure of Python Programming Language
Structure of Python Programming Language
Python Code Indention

▪ Indentation is nothing but adding whitespaces before the statement when it is needed.

▪ Python uses indentation to indicate a block of code.

▪ All statements with the same distance to the right belong to the same block of code.

▪ Without indentation Python doesn't know which statement to be executed to next. Indentation
also defines which statements belong to which block.

▪ Example
if 5 > 2:
print("Five is greater than two!")
Python Code Indention

▪ Python will give you an error if you skip the indentation:


if 5 > 2:
print("Five is greater than two!")

File "demo_indentation_test.py", line 2

print("Five is greater than two!")


^
IndentationError: expected an indented block
Python Code Indention

j=1
while(j<= 5):
print(j)
j=j+1
Print(“Successful…”)

In above example : print (j ) and j=j+1 are block of code of while loop. So both statement must be
with same indention space

Python uses 4 spaces as indentation by default. However, the number of spaces is up to you,
but a minimum of 1 space has to be used.
Line Continuation

▪ Some statements may become very long and may force you to scroll the screen left and right
frequently.

▪ You can fit your code in such a way that you do not have to scroll here and there.

▪ Python allows you to write a single statement in multiple lines, is known as line continuation.

▪ Line continuation enhances readability as well.

▪ 2 type of line continuation


1. Implicit line continuation
2. Explicit line continuation
Line Continuation

Implicit Line Continuation

▪ This is the most straightforward technique in writing a statement that spans multiple lines.

▪ Any statement containing opening parentheses (‘(‘), brackets (‘[‘), or curly braces (‘{‘) is
presumed to be incomplete until all matching parentheses, square brackets, and curly braces
have been encountered.

▪ Until then, the statement can be implicitly continued across lines without raising an error.
Line Continuation

# The following code is valid


a=[
[1, 2, 3],
[3, 4, 5],
[5, 6, 7]
]

print(a)
Output:
[[1, 2, 3], [3, 4, 5], [5, 6, 7]]
Line Continuation

Explicit Line Continuation

▪ Explicit Line joining is used mostly when implicit line joining is not applicable.

▪ In this method, you have to use a character that helps the interpreter to understand that the
particular statement is spanning more than one lines.

▪ Backslash (\) is used to indicate that a statement spans more than one line.

▪ The point is to be noted that ” must be the last character in that line, even white-space is not
allowed.
Line Continuation

x=\
1+2\
+5+6\
+ 10

print(x)

Output:
24
Comment

▪ Python has commenting capability for the purpose of in-code documentation.

▪ Comments start with a #, and Python will render the rest of the line as a comment.

▪ The Python interpreter entirely ignores the lines followed by a hash ( # )character.

▪ Doesn’t support multiline comments.

▪ A good programmer always uses the comments to make code under stable. Let's see the
following example of a comment.

name = "Thomas" # Assigning string value to the name variable


Comment

Importance of Comment

▪ Comments are essential for defining the code and help us and other to understand the code.

▪ By looking the comment, we can easily understand the intention of every line that we have
written in code.

▪ We can also find the error very easily, fix them, and use in other applications.
Triple Quote

▪ 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:
"""
This is a comment
As long as the string is not assigned to a variable,
written in Python will read the code, but then ignore it, and you
more than just one line have made a multiline comment.
"""
print("Hello, World!")
Triple Quote

▪ 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:
"""
This is a comment
As long as the string is not assigned to a variable,
written in Python will read the code, but then ignore it, and you
more than just one line have made a multiline comment.
"""
print("Hello, World!")
Python Identifier

▪ Python identifiers refer to a name used to identify a variable, function, module, class, module or
other objects.

▪ Rules:
▪ A identifier name must start with either an English letter or underscore (_).
▪ A identifier name cannot start with the number.
▪ Special characters are not allowed in the variable name.
▪ The identifier's name is case sensitive.
Python Variable

▪ Variable is a only name in python that is used to refer to memory location.

▪ Python variable is also known as an identifier and used to hold value.

▪ In Python, we don't need to specify the type of variable because Python is a infer language and
smart enough to get variable type.

▪ Variable names can be a group of both the letters and digits, but they have to begin with a letter
or an underscore.

▪ Python is a dynamically typed language. So, Python doesn't need an explicit variable
declaration to reserve memory. The variable declaration will happen automatically when we
assign value to it.
Python Variable

Rules To Declare Variable

▪ 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)
Python Variable

Creating Variables

▪ Python has no command for declaring a variable.

▪ A variable is created the moment you first assign a value to it.

▪ Variables do not need to be declared with any particular type, and can even change type after
they have been set.

▪ The equal (=) operator is used to assign value to a variable.

Example : x = 5
y = "John"
Python Variable

Multiple Assignment

▪ Python allows us to assign a value to multiple variables in a single statement, which is also
known as multiple assignments.

▪ We can apply multiple assignments in two ways, either by assigning a single value to multiple
variables or assigning multiple values to multiple variables. Consider the following example.
Python Variable

Assigning single value to multiple variables

X = y = z = 50

print(x)

print(y)

print(z)

Output: 50

50
Python Variable

Assigning multiple values to multiple variables:

a,b,c=5,10,15
print a
print b
print c
Output: 5
10
15
▪ The values will be assigned in the order in which variables appear.
Python Variable

Output Variable

▪ The Python print statement is often used to output variables.

▪ To combine both text and a variable, Python uses the , character:

Example
x = "awesome"
print("Python is “ , x)

Output
Python is awesome
Python Variable

Output Variable

▪ You can also use the + character to add a variable to another variable:

Example
x = "Python is "
y = "awesome" Output

z= x+y Python is awesome

print(z)
Python Variable

Output Variable

▪ If you try to combine a string and a number, Python will give you an error:

Example
x=5
Output
y = "John"
TypeError: unsupported operand type(s) for +: 'int' and 'str'
print(x + y)
Python Global Variable

▪ Variables that are created outside of a function (as in all of the examples above) are known as
global variables.

▪ Global variables can be used by everyone, both inside of functions and outside.

Example
x = “VTCBB"
def myfunc():
print("Python is " , x) Output
myfunc() //function call VTCBB
Python Global Variable

▪ If you create a variable with the same name inside a function, this variable will be local, and can
only be used inside the function.

▪ The global variable with the same name will remain as it was, global and with the original value.
x = “vtcbb"
def myfunc() :
x = "fantastic"
print("Python is " + x) Output

myfunc() Python is fantastic

print("Python is " + x) Python is vtcbb


Python Variable

Delete Variable

▪ We can delete the variable using the del keyword.

del <variable_name>

▪ In the following example, we create a variable x and assign value to it. We deleted variable x,
and print it, we get the error "variable x is not defined". The variable x will no longer use in future.
Python Variable

▪ Example -
# Assigning a value to x
x=6
print(x)
# deleting a variable.
del x
print(x)
Python Variable

Output:
6
Traceback (most recent call last):
File "C:/Users/DEVANSH SHARMA/PycharmProjects/Hello/multiprocessing.py", line 389, in
print(x)
NameError: name 'x' is not defined
print ( )

▪ Prints the message to the screen or any other standard output device.

▪ Syntax: print ( value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush )

Parameters:

value(s) : Any value, and as many as you like. Will be converted to string before printed

sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than one. Default :’ ‘

end= (Optional) Specify what to print at the end. Default : ‘\n’

file : (Optional) An object with a write method. Default :sys.stdout


Print ( )

▪ Returns: It returns output to the screen.

▪ For Example:
print("Python is fun.")
a=5
# Two objects are passed
print("a =", a)
Output:
b=a
Python is fun.
# Three objects are passed
a=5
print('a =', a, '= b') a=5=b
print ( )

▪ For Example:
print('Printing in a Nutshell', end='\n * ')
print('hello', 'world', sep='\n')
print('Calling Print', end='\n * ')
Output:
print('Separating Multiple Arguments', end='\n * ')
hello print('Preventing Line Breaks')
world
Output:

Printing in a Nutshell
* Calling Print
* Separating Multiple Arguments
* Preventing Line Breaks
Python Data Type

▪ Python has five standard data types

1. Numbers
2. String
3. List
4. Tuple
5. Dictionary
Python Data Type : Number

▪ Number data types store numeric values.

▪ They are immutable data types, means that changing the value of a number data type
results in a newly allocated object.

▪ Number objects are created when you assign a value to them.

▪ For example :

var1 = 1

var2 = 10
Python Data Type : Number

▪ Python supports three types of numeric data.

▪ Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has
no restriction on the length of an integer.

▪ Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is accurate
upto 15 decimal points.

▪ complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote the
real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j, etc.
Python Data Type : Number

▪ Python provides the type() function to know the data-type of the variable.

▪ Similarly, the isinstance() function is used to check an object belongs to a particular class.

▪ Python creates Number objects when a number is assigned to a variable.

For example:

a=5

print("The type of a", type(a)) Output : The type of a <class 'int'>


Python Data Type : String

▪ We can create string simply by enclosing characters in quotes.

▪ Python treats single quotes the same as double quotes.

For example :

var1 = 'Hello World!'

var2 = "Python Programming"


Python Data Type : String

▪ Python does not support a character type; these are treated as strings of length one, thus
also considered a substring.

▪ To access substrings, use the square brackets for slicing along with the index or indices to
obtain your substring.

For example :

var1 = 'Hello World!'

var2 = "Python Programming"


Python Data Type : String

var1 = 'Hello World!'

var2 = "Python Programming“

print "var1[0]: ", var1[0]

print "var2[1:5]: ", var2[1:5]

Output:

var1[0]: H

var2[1:5]: ytho
Python Data Type : String

str1 = 'hello Python' #string str1

str2 = ' how are you' #string str2

print (str1[0:2]) #printing first two character using slice operator 🡪 he

print (str1[4]) #printing 4th character of the string 🡪o

print (str1*2) #printing the string twice 🡪 hello Pythonhello Python

print (str1 + str2) #printing the concatenation of str1 and str2 🡪hello Python how are you
Python Data Type : String

str = ‘VTCBCSR'

print(str[-1])

print(str[-3])

print(str[-2:])
Output:
print(str[-4:-1]) R
C
print(str[::-1]) SR
BCS
print(str[-12]) RSCBCTV
IndexError: string index out of range
Python Data Type : String

▪ You can "update" an existing string by (re)assigning a variable to another string.

▪ The new value can be related to its previous value or to a completely different string
altogether.

For example:

var1 = 'Hello World!'

print "Updated String :- ", var1[:6] + 'Python

Updated String :- Hello Python


Python Data Type : String

Operator Description Example

+ Concatenation - Adds values on either side of the operator a + b will give HelloPython

* Repetition - Creates new strings, concatenating multiple copies a*2 will give -HelloHello
of the same string

[] Slice - Gives the character from the given index a[1] will give e

[:] Range Slice - Gives the characters from the given range a[1:4] will give ell

in Membership - Returns true if a character exists in the given H in a will give 1


string

not in Membership - Returns true if a character does not exist in the M not in a will give 1
given string
Python Data Type : String

Triple-Quoted Strings

▪ Triple-quoted strings are delimited by matching groups of three single quotes or three
double quotes.

▪ Escape sequences work in triple-quoted strings.

▪ Single quotes, double quotes, and newlines can be included without escaping them.

▪ This provides a convenient way to create a string with both single and double quotes in it.
Python Data Type : String

Triple-Quoted Strings example:

print('''This string has a single (') and a double (") quote.'‘’)

Output: This string has a single (') and a double (") quote.

\
Python Data Type : String

Triple-Quoted Strings

▪ Because newlines can be included without escaping them, this also allows for multiline
strings:

▪ For example:

print("""This is a Output:

string that spans This is a


string that spans
across several lines""")
across several lines
Python Data Type : List

▪ List is an ordered sequence of different type of items.

▪ The index starts from 0 in Python.

▪ The items stored in the list are separated with a comma (,) and enclosed within square
brackets [ ].

▪ For Example:

a = [1, 2.2, 'python']


Python Data Type : List

▪ Slicing Operator ( [ : ] ) : Used to extract an item or a range of items from a list.

▪ For Example:
a = [1,”om”, “sai”,80 ]

▪ print("a[2] = ", a[2]) 🡪 a[2] = sai


▪ print("a[0:2] = ", a[0:2]) 🡪 a[0:2] = [0,”om”]
▪ print("a[2:] = ", a[2:]) 🡪 a[2:] = [“sai”,80]
▪ print(a) 🡪 [1,”om”,”sai”,80]
Python Data Type : List [ LBM ]

▪ Lists are mutable, meaning, the value of elements of a list can be altered.

▪ For Example:
a = [1,”om”, “sai”,80 ]
a[2]=“ram”
print (a) 🡪 [1,”om”,”ram”,80]
Python Data Type : List [ LBM ]

▪ Lists are mutable, meaning, the value of elements of a list can be altered.

▪ For Example:
a = [1,”om”, “sai”,80 ]
a[2]=“ram”
print (a) 🡪 [1,”om”,”ram”,80]
Python Data Type : Tuple [TPIm]

▪ Tuple is an ordered sequence of items same as a list.

▪ A tuple is a read-only data structure as we can't modify the size and value of the items of a
tuple.

▪ Difference Between List & Tuple:


▪ Tuples are immutable. Tuples once created cannot be modified.
▪ The items of the tuple are separated with a comma (,) and enclosed in parentheses ().

▪ Tuples are used to write-protect data and are usually faster than lists as they cannot change
dynamically.
Python Data Type : Tuple

▪ For Example

tup = ("hi", "Python", 2)

t[2] = "hi“ # Try to modify 3rd element. It display following error

Traceback (most recent call last):


File "main.py", line 14, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment
Python Data Type : Dictionary

▪ Dictionary is an unordered set of a key-value pair of items.

▪ It is like an associative array or a hash table where each key stores a specific value.

▪ Key can hold any primitive data type, whereas value is an arbitrary Python object.

▪ When to used? When we have a huge amount of data. Dictionaries are optimized for
retrieving data. We must know the key to retrieve the value.

▪ Dictionaries are defined within braces { } with each item being a pair in the form “key:value”.
Key and value can be of any type.
Python Data Type : Dictionary

▪ Dictionary is an unordered set of a key-value pair of items.

▪ It is like an associative array or a hash table where each key stores a specific value.

▪ When to used? When we have a huge amount of data. Dictionaries are a great tool for
counting elements and analyzing frequency

▪ Dictionaries are defined within braces { } with each item being a pair in the form “key:value”.
Key and value can be of any type.

▪ For example : d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}


Python Data Type : Dictionary

▪ For example : d = {1:'Jimmy', 10:'Alex', ‘b’:'john', 4:'mike’}

# Printing dictionary

print (d) {1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike’}

# Accesing value using keys

print("1st name is "+d[1]) 1st name is Jimmy

print (d.keys()) dict_keys([1, 2, 3, 4])


dict_values(['Jimmy', 'Alex', 'john', 'mike'])
print (d.values())
Type Conversion

▪ The process of converting the value of one data type (integer, string, float, etc.) to another
data type is called type conversion.

▪ Python has two types of type conversion.


▪ Implicit Type Conversion
▪ Explicit Type Conversion
Implicit Type Conversion

▪ In Implicit type conversion, Python automatically converts one data type to another data type.
This process doesn't need any user involvement.

num_int = 123
When we run the above program, the output will be:
num_flo = 1.23 datatype of num_int: <class 'int'>

print("datatype of num_int:",type(num_int)) datatype of num_flo: <class 'float‘>

print("datatype of num_flo:",type(num_flo))
Explicit Type Conversion

▪ In Explicit Type Conversion, users convert the data type of an object to required data type.

▪ We use the predefined functions like int(), float(), str(), etc to perform explicit type
conversion.

▪ This type of conversion is also called typecasting because the user casts (changes) the
data type of the objects.
▪ Syntax : <required_datatype> (expression)

▪ Typecasting can be done by assigning the required data type function to the expression.
Implicit Type Conversion

num_int = 123 When we run the above program, the output will be:

num_str = "456“ Data type of num_str after Type Casting: <class 'int'>

Sum of num_int and num_str: 579


num_str = int(num_str)
Data type of the sum: <class 'int'>

print("Data type of num_str after Type Casting:",type(num_str))

num_sum = num_int + num_str

print("Sum of num_int and num_str:",num_sum)


Key Point for Type Conversion

▪ Type Conversion is the conversion of object from one data type to another data type.

▪ Implicit Type Conversion is automatically performed by the Python interpreter.

▪ Python avoids the loss of data in Implicit Type Conversion.

▪ Explicit Type Conversion is also called Type Casting, the data types of objects are
converted using predefined functions by the user.

▪ In Type Casting, loss of data may occur as we enforce the object to a specific data type.
Input & Output

▪ The input() method reads a line from input, converts into a string and returns it.

▪ Syntax: input ( [ prompt ] )

▪ The input() method takes a single optional argument: prompt

prompt (Optional) - a string that is written to standard output (usually screen) without trailing
newline

▪ Return value: The input() method reads a line from the input (usually from the user),
converts the line into a string by removing the trailing newline, and returns it.

▪ If EOF is read, it raises an EOFError exception.


Input & Output

Example:

Name = input(“Enter your name:”)

Print(“Your name is “,name)


Input & Output : print()

▪ The print() function to output data to the standard output device (screen).

▪ Example:

print(‘VTCBB') Output:
VTCBB
a=5
The value of a is 5
print('The value of a is', a)
Input & Output : print()

▪ Syntax: print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

▪ Here, objects is the value(s) to be printed.

▪ The sep separator is used between the values. It defaults into a space character.

▪ After all values are printed, end is printed. It defaults into a new line.

▪ The file is the object where the values are printed and its default value
is sys.stdout (screen).
Input & Output : print()

▪ Example: Output:
print(1, 2, 3, 4) 1234

print(1, 2, 3, 4, sep='*') 1*2*3*4


1#2#3#4&
print(1, 2, 3, 4, sep='#', end='&')

You might also like