0% found this document useful (0 votes)
3 views23 pages

Python Unit - I

Python is a high-level, general-purpose programming language created by Guido van Rossum in 1991, known for its readability and efficiency. It supports multiple programming paradigms and is widely used in various applications including web development and machine learning. The document covers Python's features, variable handling, reserved keywords, and best practices for coding.

Uploaded by

Aathi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views23 pages

Python Unit - I

Python is a high-level, general-purpose programming language created by Guido van Rossum in 1991, known for its readability and efficiency. It supports multiple programming paradigms and is widely used in various applications including web development and machine learning. The document covers Python's features, variable handling, reserved keywords, and best practices for coding.

Uploaded by

Aathi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Python: Unit - I

UNIT - I
Python
Python is a high-level, general-purpose and a very popular programming language. It
was created by Guido van Rossum in 1991 and further developed by the Python Software
Foundation. It was designed with an emphasis on code readability, and its syntax allows
programmers to express their concepts in fewer lines of code. Python is a programming
language that lets you work quickly and integrate systems more efficiently.
Python programming language is being used in web development, Machine Learning
applications, along with all cutting-edge technology in Software Industry. Python Programming
Language is very well suited for Beginners, also for experienced programmers with other
programming languages like C++ and Java.
 Python is currently the most widely used multi-purpose, high-level programming
language.
 Python allows programming in Object-Oriented and Procedural paradigms.
 Python programs generally are smaller than other programming languages like Java.
Programmers have to type relatively less and indentation requirement of the language,
makes them readable all the time.
 Python language is being used by almost all tech-giant companies like – Google,
Amazon, Facebook, Instagram, Dropbox, Uber… etc.
 The biggest strength of Python is huge collection of standard libraries which can be
used for the following:
 Machine Learning
 GUI Applications (like Kivy, Tkinter, PyQt etc. )
 Web frameworks like Django (used by YouTube, Instagram, Dropbox)
 Image processing (like OpenCV, Pillow)
 Web scraping (like Scrapy, BeautifulSoup, Selenium)
 Test frameworks
 Multimedia
 Scientific computing
 Text processing

Department of CS&IT, S.S.D.M College. 1


Python: Unit - I

What can Python do?


 Python can be used on a server to create web applications.
 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping, or for production-ready software
development.

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.

Variables
Variables provide a way to associate names with objects.
Variables are containers for storing data values.
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)
Variables do not need to be declared with any particular type, and can even change
type after they have been set.
Example:

Department of CS&IT, S.S.D.M College. 2


Python: Unit - I

x = 4 # x is of type int
x = "Kane" # 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:

x = str(3) # x will be '3'


y = int(3) # y will be 3
z = float(3) # z will be 3.0

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)

Valid Variable Names:

myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

Invalid Variable Names:

2myvar = "John"
my-var = "John"

Department of CS&IT, S.S.D.M College. 3


Python: Unit - I

my var = "John"

Multi Words Variable Names


Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable

Camel Case
Each word, except the first, starts with a capital letter

Example: myVariableName = "John"

Pascal Case
Each word starts with a capital letter

Example: MyVariableName = "John"

Snake Case
Each word is separated by an underscore character

Example: my_variable_name = "John"

Assign Multiple Values


Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line:
Example:

x, y, z = "Orange", "Banana", "Cherry"


print(x)
print(y)
print(z)

One Value to Multiple Variables


And you can assign the same value to multiple variables in one line:
Example:

Department of CS&IT, S.S.D.M College. 4


Python: Unit - I

x = y = z = "Orange"
print(x)
print(y)
print(z)
Global Variables
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 = "awesome"
def myfunc():
print("Python is " + x)
myfunc()

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.

Example:

x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)

The global Keyword


Normally, when you create a variable inside a function, that variable is local, and can
only be used inside that function.
To create a global variable inside a function, you can use the global keyword.
Example:

Department of CS&IT, S.S.D.M College. 5


Python: Unit - I

def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)

Also, use the global keyword if you want to change a global variable inside a function.
Example:

x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)

Python Files
A Python program, sometimes called a script, is a sequence of definitions and
commands. These definitions are evaluated and the commands are executed by the Python
interpreter in something called the shell. Whenever a program execution begins a new shell is
created.
A command, often called a statement, instructs the interpreter to do something.
Python syntax can be executed by writing directly in the Command Line:
Example:

>>> print("Hello, World!")

Hello, World!

Execute a Python program by creating a Python file using the .py extension and
running it in command line in the shell.
Example:

C:\Users\CSIT>python myfile.py

Department of CS&IT, S.S.D.M College. 6


Python: Unit - I

Python Reserved Words (Identifiers and Keywords)


Identifiers
In Python, identifiers are used to name variables, functions, classes, and other objects.
They are used to refer to the objects in the program. An identifier starts with a letter A to Z or
a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers.
Identifiers are created by the programmer, and they must follow certain rules:
Case sensitivity: Python identifiers are case-sensitive, meaning that myVariable and
myvariable are considered two different identifiers.
Allowed characters: Python identifiers can contain letters, numbers, and underscores,
but they cannot start with a number. For example, my_variable_1 is a valid identifier, while
1_my_variable is not.
Reserved words: Python has a set of reserved keywords that cannot be used as
identifiers. For example, you cannot use if as an identifier because it is a reserved keyword.
Naming conventions: Python has a set of naming conventions for identifiers. It is a
common practice to use lowercase letters for variable and function names and to use
CamelCase for class names.
Here are naming conventions for Python identifiers −
 Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.
 Starting an identifier with a single leading underscore indicates that the
identifier is private.
 Starting an identifier with two leading underscores indicates a strongly private
identifier.
If the identifier also ends with two trailing underscores, the identifier is a language-
defined special name.
Standard library: Python has a vast set of standard libraries that provides a wide
variety of modules, classes, and functions. These are pre-defined identifiers that have special
meanings and should not be overridden.
Overall, Python identifiers are used to name the variables, functions, classes and other
objects in a program. It's important to follow the rules for naming conventions and to avoid
using reserved keywords. This will make the code more readable and maintainable.

Department of CS&IT, S.S.D.M College. 7


Python: Unit - I

Example:

// Identifier for Variable Name


my_variable = 5
// Identifier for function
def my_function(x):
return x*x
// Identifier for Class Name
class MyClass:
def print_message(self):
print("Hello, World!")

Keywords
keywords are special words that are reserved by the language and have specific
meanings. They cannot be used as variable names or function names because they are used to
indicate specific language constructs.
Here are a few key points about Python keywords:
List of keywords: Python has a predefined list of keywords that cannot be used as
variable or function names. These include words like if, else, for, while, def, class, try,
except, True, False, and None.
Specific meanings: Each keyword has a specific meaning in Python and is used to
indicate a particular language construct. For example, the if keyword is used to create
conditional statements, the def keyword is used to define functions, and the class keyword is
used to define classes.
Case-sensitive: Python keywords are case-sensitive, meaning that if and If are
considered two different keywords.
Cannot be overridden: Keywords cannot be overridden, meaning that you cannot
redefine the meaning of a keyword. This ensures that keywords always have the same
meaning in Python and makes the language more predictable.
Example:

// Keyword – if statement
x=6

Department of CS&IT, S.S.D.M College. 8


Python: Unit - I

if x > 5:
print("x is greater than 5")
// Keyword – for loop
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
// Keyword – function
def add(a, b):
return a + b
result = add(3, 4)
print(result) # output: 7

Keywords Scope
Some keywords are used to indicate the scope of variables and objects.
The global keyword in Python is used to indicate that a variable is a global variable,
rather than a local variable.
When a variable is defined inside a function or a class, it is considered a local variable
and can only be accessed within that function or class. If a variable is defined outside of any
function or class, it is considered a global variable and can be accessed from anywhere in the
code.
The global keyword is used to specify that a variable is a global variable, even if it is
defined inside a function or class. This allows you to change the value of a global variable
from within a function or class.
Example:

x=5 # global variable


def my_function():
global x
x=x+1
print(x)
my_function() # Output: 6
print(x) # Output: 6

Department of CS&IT, S.S.D.M College. 9


Python: Unit - I

From the above example, x is a global variable, and the value of x is 5 before the
function my_function is called. Inside the function, the global keyword is used to specify
that the x inside the function is the global x. Then the function increases the value of x by 1
and prints it. After the function call, the value of x is 6, which can be accessed outside of the
function as well.
It's important to be careful when using the global keyword, as it can lead to naming conflicts
and make code harder to understand and maintain. As a general rule, it is recommended to
avoid using global variables whenever possible and use function arguments and return values
to pass data between different parts of the code.

Structure of Python
Python Statements In general, the interpreter reads and executes the statements line by
line sequentially. Though, there are some statements that can alter this behavior like
conditional statements.
Mostly, python statements are written in such a format that one statement is only
written in a single line. The interpreter considers the ‘new line character’ as the terminator
of one instruction. But, writing multiple statements per line is also possible.

print(“Welcome to Python Program”)

Multiple Statements per Line


Can able to 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, terminate the multiple lines by one statement with the help of semicolon (;).
Semicolon (;) is used as the terminator of one statement in this case.
For Example, consider the following code.

a = 10; b = 20; c = b + a

print(a); print(b); print(c)

Line Continuation
Some statements may become very long and may force you to scroll the screen left
and right frequently. It is possible to fit the code in such a way that no need to scroll here

Department of CS&IT, S.S.D.M College. 10


Python: Unit - I

and there. Python allows to write a single statement in multiple lines, also known as line
continuation. Line continuation enhances readability as well.

x = 10
y = 20
z = 30
no_of_teachers = x
no_of_male_students = y
no_of_female_students = z

# Bad Practice as width of this code is too much.


if (no_of_teachers == 10 and no_of_female_students == 30 and
no_of_male_students == 20 and (x + y) == 30):
print(“The course is valid”)

# This could be done instead:


if (no_of_teachers == 10 and no_of_female_students == 30
and no_of_male_students == 20 and x + y == 30):
print(“The course is valid”)

Types of Line Continuation


In general, there are two types of 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.
Example:

Department of CS&IT, S.S.D.M College. 11


Python: Unit - I

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

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

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.
Example:

x= \
1+2\
+5+6\
+ 10
print(x)
Output:

24

Comments in Python
Writing comments in the code are very important and they help in code readability
and also tells more about the code. It helps you to write details against a statement or a
chunk of code. Interpreter ignores the comments and does not count them in commands.
Symbols used for writing comments include Hash (#) or Triple Double Quotation
marks (“““). Hash is used in writing single line comments that do not span multiple lines.

Department of CS&IT, S.S.D.M College. 12


Python: Unit - I

Triple Quotation Marks are used to write multiple line comments. Three triple quotation
marks to start the comment and again three quotation marks to end the comment.
Example:

# This example will show single line comment

""" This example will demonstrate


that this statement is in
multiple line comments """

Invalid comment statement


That Hash (#) inside a string does not make it a comment.
Example:

""" The following statement prints the string stored


in the variable """
a = “This is # not a comment #”
print(a)

Datatypes
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:
 Text Type : str
 Numeric Types : int, float, complex
 Sequence Types : list, tuple, range
 Mapping Types : dict
 Set Types : set, frozenset
 Boolean Type : bool
 Binary Types : bytes, bytearray, memoryview
Python provides the type () function to know the data-type of the variable

Text Type
The string can be defined as the sequence of characters represented in the quotation
marks. In Python, we can use single, double, or triple quotes to define a string.

Department of CS&IT, S.S.D.M College. 13


Python: Unit - I

Example:
x = "Hello World"

Numeric Types
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. Its value belongs to int
 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.
Example:
int : x = 20
float : x = 20.5
complex : x = 1j

Sequence Type
List
Python Lists are similar to arrays in C. However, the list can contain data of different
types. The items stored in the list are separated with a comma (,) and enclosed within square
brackets [].
Example:
x = ["apple", 1, "cherry"]
Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection
of the items of different data types. The items of the tuple are separated with a comma (,) and
enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items
of a tuple.
Example:
x = ("apple", 1, "cherry")

Department of CS&IT, S.S.D.M College. 14


Python: Unit - I

Range
Create a sequence of numbers.
Example:
x = range(6)
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.
The items in the dictionary are separated with the comma (,) and enclosed in the curly braces
{}.
Example:
x = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}

Boolean
Boolean type provides two built-in values, True and False. These values are used to
determine the given statement true or false. True can be represented by any non-zero value or
'T' whereas false can be represented by the 0 or 'F'.
Example:
x = bool(5) or x = bool(0) or x = True

Set
Sets are used to store multiple items in a single variable.
A set is a collection which is both unordered and unindexed.
Sets are written with curly brackets.
Set items are unordered, unchangeable, and do not allow duplicate values.
Example:
x = set(("apple", 1, "cherry", 2))

Frozenset
Freeze the list, and make it unchangeable.
Example:
x = frozenset(("apple", "banana", "cherry"))

Department of CS&IT, S.S.D.M College. 15


Python: Unit - I

ByteArray
The bytearray() function returns a bytearray object.
It can convert objects into bytearray objects, or create empty bytearray object of the
specified size.
Example:
x = bytearray(5)

Bytes
The bytes() function returns a bytes object.
It can convert objects into bytes objects, or create empty bytes object of the specified
size.
The difference between bytes() and bytearray() is that bytes() returns an object that
cannot be modified, and bytearray() returns an object that can be modified.
Example:
x = bytes(5)

Memoryview
The memoryview() function returns a memory view object from a specified object.
Example:
x = memoryview(bytes(5))

Type Conversion
Python defines type conversion functions to directly convert one data type to another
which is useful in day-to-day and competitive programming.
 Implicit Type Conversion
 Explicit Type Conversion
The act of changing an object’s data type is known as type conversion. The Python
interpreter automatically performs Implicit Type Conversion. Python prevents Implicit Type
Conversion from losing data.
The user converts the data types of objects using specified functions in explicit type
conversion, sometimes referred to as type casting. When type casting, data loss could happen
if the object is forced to conform to a particular data type.

Department of CS&IT, S.S.D.M College. 16


Python: Unit - I

Implicit Type Conversion


In Implicit type conversion of data types in Python, the Python interpreter
automatically converts one data type to another without any user involvement.
Example:
x = 10
print("x is of type:",type(x))
y = 10.6
print("y is of type:",type(y))
z=x+y
print(z)
print("z is of type:",type(z))
Output:
x is of type: <class 'int'>
y is of type: <class 'float'>
20.6
z is of type: <class 'float'>

Explicit Type Conversion


In Explicit Type Conversion in Python, the data type is manually changed by the user
as per their requirement. With explicit type conversion, there is a risk of data loss since we
are forcing an expression to be changed in some specific data type.
Example:
# initializing string
s = "10010"

# printing string converting to int base 2


c = int(s,2)
print ("After converting to integer base 2 : ")
print (c)

# printing string converting to float


e = float(s)
print ("After converting to float : ")

Department of CS&IT, S.S.D.M College. 17


Python: Unit - I

print (e)
Output:
After converting to integer base 2 :
18
After converting to float :
10010.0

Operators
Operators are special symbols in Python that perform specific operations on one or
more operands (values or variables).
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called
operator.
Types of Operator
Python language supports the following types of operators.
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators

Python Arithmetic Operator


Arithmetic operators are used with numeric values to perform common mathematical
operations.
Example
Operator Name Description Syntax
(a=10, b=20)
Adds values on either side of
+ Addition a+b a + b = 30
the operator
Subtracts right hand operand
- Subtraction a–b a – b = -10
from left hand operand
Multiplies values on either side
* Multiplication a*b a * b =200
of the operator

Department of CS&IT, S.S.D.M College. 18


Python: Unit - I

Divides left hand operand value


/ Division a/b b/a=2
by right hand operand
Divides left hand operand value
% Modulus by right hand operand and a%b b%a=0
returns remainder
Performs exponential (power) a ** b 10 to the
** Exponentiation a ** b
calculation of operators power 20
The Division of operands where
the result is the quotient in
// Floor Division a // b 15 // 2 = 7
which the digits after the
decimal points are removed

Python Assignment Operator


Assignment operators are used to assign values to variables.
Operator Syntax Same As Example

= x = value x=5 x=5

+= x += value x=x+3 x += 3

-= x -= value x=x-3 x -= 3

*= x *= value x=x*3 x *= 3

/= x /= value x=x/3 x /= 3

%= x %= value x=x%3 x %= 3

//= x //= value x = x // 3 x //= 3

**= x **= value x = x ** 3 x **= 3

&= x &= value x=x&3 x &= 3

|= x |= value x=x|3 x |= 3

^= x ^= value x=x^3 x ^= 3

>>= x >>= value x = x >> 3 x >>= 3

<<= x <<= value x = x << 3 x <<= 3

Department of CS&IT, S.S.D.M College. 19


Python: Unit - I

Python Comparison Operators


Comparison operators are used to compare two values
Example
Operator Name Syntax
(x=5, y=3)
== Equal x == y x == y

!= Not equal x != y x != y

> Greater than x>y x>y

< Less than x<y x<y

>= Greater than or equal to x >= y x >= y

<= Less than or equal to x <= y x <= y

Python Logical Operators


Logical operators are used to combine conditional statements
Operator Description Example

and Returns True if both statements are true x < 5 and x < 10

or Returns True if one of the statements is true x < 5 or x < 4

not Reverse the result, returns False if the result is true not(x < 5 and x < 10)

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
Returns True if both variables are the same
is x is y
object
Returns True if both variables are not the
is not x is not y
same object

Example:
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x

Department of CS&IT, S.S.D.M College. 20


Python: Unit - I

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

Python Membership Operators


Membership operators are used to test if a sequence is presented in an object
Operator Description Example
Returns True if a sequence with the
in x in y
specified value is present in the object
Returns True if a sequence with the
not in x not in y
specified value is not present in the object

Example:
x = ["apple", "banana"]
print("banana" in x) #Returns True
x = ["apple", "banana"]
print("pineapple" not in x) #Returns True

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


Shift left by pushing zeros in from the right and
<< Zero fill left shift
let the leftmost bits fall off
Shift right by pushing copies of the leftmost bit
>> Signed right shift in from the left, and let the rightmost bits fall
off

Department of CS&IT, S.S.D.M College. 21


Python: Unit - I

Input and Output Statements


Input Statement
The input() function in Python is used to read input from the user. The input is
returned as a string, so if you need to use the input as a number, you will need to convert it
using the appropriate data type method such as int() or float().
Example:

name = input("What is your name? ")


print("Hello, " + name)

From the example, the input() function is used to prompt the user to enter their
name. The input is assigned to the variable name, and then the print() function is used to
display "Hello, [name]".
To get a numerical input from the user convert the input string to a number using the
appropriate data type function such as int() or float().
Example:

x = int(input("Enter an integer: "))


print(x)

It is possible to provide a default value or a prompt message as an optional parameter


to input function. It will be displayed as prompt message to user before taking input.
Example:

age = input("What is your age? (default 20) ") or 20


print(f"Your age is {age}")

Here the prompt message is "What is your age? (default 20)" and if user does not
provide the input, it will take the default value 20.
The f before the string in the print(f"Your age is {age}") statement is
called an f-string, also known as a "formatted string literal".
The expressions inside the curly braces {} are evaluated at runtime and their values
are included in the resulting string. The expressions can be variables, function calls or any
other valid Python expressions.
It is also more efficient than using the format() method or string concatenation,
since it is evaluated at runtime rather than at compile time.

Department of CS&IT, S.S.D.M College. 22


Python: Unit - I

raw_input()
raw_input() is a legacy function that is present in Python. It reads input from the
user as a string, without evaluating it.
Example:
>>> x = raw_input("Enter a number: ")
Enter a number: 5
>>> print(x)
'5'
The raw_input() function is used to prompt the user to enter a number. The input
is returned as a string, so the variable x is assigned the value '5' (as a string).

Output Statement
The print() function is the most commonly used function for displaying output to
the user. The print() function can take one or more arguments, which are the values to be
printed. The values are separated by spaces and a newline is added at the end of the print
statement by default.
Example:

x=5
y = 10
print("The value of x is", x)
print("The sum of x and y is", x + y)
From above example, the print() function is used to display "The value of x is 5"
and "The sum of x and y is 15"
The print() function allows to print multiple values on the same line by using the
sep parameter:
Example:
print(1, 2, 3, 4, 5, sep=" | ")
Also use the print() function to print values without a newline at the end, by using
the end parameter:
Example:
print("Hello", end=", ")
print("world!")
This will print "Hello, world!" on the same line

Department of CS&IT, S.S.D.M College. 23

You might also like