0% found this document useful (0 votes)
2 views38 pages

Python Programming

Python is a high-level, interpreted programming language created by Guido van Rossum, known for its ease of learning and versatility in various applications such as web development, data analysis, and GUI programming. It features an open-source license, supports object-oriented programming, and allows for easy integration with other languages. The document also covers Python's comments, input-output operations, variable management, data types, type conversion, and operators.

Uploaded by

n5504130ab
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)
2 views38 pages

Python Programming

Python is a high-level, interpreted programming language created by Guido van Rossum, known for its ease of learning and versatility in various applications such as web development, data analysis, and GUI programming. It features an open-source license, supports object-oriented programming, and allows for easy integration with other languages. The document also covers Python's comments, input-output operations, variable management, data types, type conversion, and operators.

Uploaded by

n5504130ab
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

Dr.G.

Aparna
Associate Professor
Department of CSM
Python is a general purpose, high-level, interpreted programming language developed by Guido van Rossum
in the late 1980s at the National Research Institute for Mathematics and Computer Science in the Netherlands.

Python is one of the most popular and widely used programming language used for set of tasks including console
based, GUI based, web programming and data analysis.

Python is a easy to learn and simple programming language so even if you are new to programming, you can
learn python without facing any problems.

Fact: Python is named after the comedy television show Monty Python's Flying Circus.
Features of Python
Python provides lots of features that are listed below.

● Easy to Learn and Use:Python is easy to learn and use compared with other programming languages. It is
developer-friendly and high level programming language.
● Interpreted Language:Python is an interpreted language because no need of compilation. This makes
debugging easy and thus suitable for beginners.
● Cross-platform Language:Python can run equally on different platforms such as Windows, Linux, Unix and
Macintosh etc. So, we can say that Python is a portable language.
● Free and Open Source:The Python interpreter is developed under an open-source license, making it free to
install, use, and distribute.
● Object-Oriented Language:Python supports object oriented language and concepts of classes and objects
come into existence.
● GUI Programming Support:Graphical user interfaces can be developed using Python.
● Integrated:It can be easily integrated with languages like C, C++, and JAVA etc.
Python Applications
Python is a general purpose programming language that makes it applicable in almost all domains of

Software development. Python as a whole can be used to develop any type of application.

Here, we are providing some specific application areas where Python can be applied.

● Web Applications
● Desktop GUI Applications
● Software
● Development
● Scientific and Numeric
● Business Applications
● Console Based Application
● Audio or Video based Applications

Comments in Python

In general, Comments are used in a programming language to describe the program


or to hide the some part of code from the interpreter.
Comments in Python can be used to explain any program code. It can also be used
to hide the code as well.

Comment is not a part of the program, but it enhances the interactivity of the program
and makes the program readable.

Python supports two types of comments:

● Single Line Comments


● Multi Line Comments
1. Single Line Comments in Python:

In case user wants to specify a single line comment, then comment must start with ‘#’

format:

# This is single line comment

Example: "[Link]"

# This is single line comment.

print("Hello Python")

Output: $python3 [Link]

Hello Python

2. Multi Line Comments in Python


2. Multi Line Comments in Python
Multi lined comment can be given inside triple [Link] must start at begining of the line.

format:
''' This
Is
Multiline comment'''

Example: "[Link]"

'''This
is
Multi line comment'''
print("Hello Python")

Output: $python3 [Link]

Hello Python
Python Example Program: Demonstrates usage of Comments in Python

Example: "[Link]"

# This example demonstrates usage of Comments

''' print() used to


print/display
text on screen '''

print("Welcome to Python")

#Assign value to variables


a=20
b=30

#print sum of two numbers


print("Sum is")
print(a+b)
Input-Output Operations in Python
Input and Output operations are performed using two built-in functions

● print( ) - Used for output operation.


● input( ) - Used for input operations.

1. print()
The print() function prints the specified message to the screen, or other standard output devi
The message can be a string, or any other object, the object will be converted into a string before written to the screen.

Syntax:
print(object(s), separator=separator, end=end, file=file, flush=flush)
When we use the print( ) function to display a message, the string can be enclosed either in the single quotation or dou
quotation.

format:
print('how are you?')
print("have fun with python")

function is also used to display variables value.


The following example shows that how to display the combination of message and variable value
x = 10
print('The value of variable num1 is ' + x)
In Python, we can use the formatted string that is prefixed with character "f". In the formatted string, the variable values a
included using curly braces ({ }). Return value of print( ) function is default None.
format:
x = 10
print(f"The value of variable num1 is {x}")

However, it turns out that this function can accept any number of positional arguments, including zero, one, or mo
arguments. That’s very handy in a common case of message formatting, where you’d want to join a few elements together.
format:
a =10
b=20
print("a= ",a,"b= ",b)
integer and String objects have a built-in operation using the % operator, which you can use to format strings.
format:
a=10
b='python'
print("a= %d b= %s" %(a,b))
By default, python's print() function ends with a newline. This function comes with a parameter called 'end.' The default va
2. input()
The Python provides a built-in function input( ) to perform input operations.

Syntax:
input(prompt)
Use the prompt parameter to write a message before the input.

format:
x = input('Enter your name:')

print('Hello, ' + x)
The Python does not provide any direct function to read a single character as input. But we can use the index value to
extract a single character from the user entered input value. Let's look at the following Python code.

format:
x = input('Enter your name:')[0]
print('Hello, ' + x)
Always the input( ) function reads input value as string value only. To read the value of any other data type, there is no
input function in Python. Explicitly we need to convert to the required data type using type casing.

format:
x = int(input('Enter a value:'))
print('The value is : ', x)
Variables in Python
A variable is a named memory location in which we can store values for the particular program. In other words, a variable
name that is used to refer to a memory location. A variable, also known as an identifier, is used to hold a value.

Creating Variables in Python


In Python, we don't need to declare variables explicitly. When we assign any value to the variable, that variable is decl
automatically.
In Python, we don't need to specify the type of variable because Python is a loosely typed language. I.e., in loosely t
language, there is no need to specify the type of variable because the variable automatically changes its datatype based on
assigned va
For Exam
a=10 Where variable a is an integer datat
b="HITAM" Where variable b is string datat
Rules for naming variable:

● Variable names can be a group of both letters and digits, but they have to begin with a letter or an underscore.
● It is recommended to use lowercase letters for variable name. ‘SUM’ and ‘sum’ both are two different variables.
Python Example Program - Variables in Python

Example: "[Link]"

a=10 #integer
b="HITAM" #string
c=12.5 #float
print(a)
print(b)
print(c)

Output: $python3 [Link]

10
HITAM
12.5
Assign Value to Multiple Variables
Python allows us to assign a value to multiple variables and multiple values to multiple variables in a single statement
which is also known as multiple assignment.

Assign single value to multiple variables :

Example: "[Link]"

x=y=z=50
print x
print y
print z

Output: $python3 [Link]

50
50
50
Assign multiple values to multiple variables :

Example: "[Link]"

a,b,c=5,10,15
print a
print b
print c

Output: $python3 [Link]

5
10
15
Data Types in Python
In general, Data Types specifies what type of data will be stored in variables. Variables can hold values of different data
types. Python is a dynamically typed or loosely typed language, hence we need not define the type of the variable while
declaring it. The interpreter implicitly binds the value with its type.

I.e. In loosely typed language no need to specify the type of variable because the variable automatically changes it's
datatype based on assigned value.
Python provides the type() function which enables us to check the type of the variable.

Python provides following standard data types, those are

1. Numbers
2. String

1. Numbers
Number stores numeric values. Python creates Number type variable when a number is assigned to a variable.
There are three numeric types in Python:

1. int
2. float
a. int

Int, or integer, is a whole number, positive or negative, without decimals, of


unlimited length.

format:
a = 10
b = -12
c = 123456789

b. float

Float or "floating point number" is a number, positive or negative,


containing one or more decimals.

format:
X = 1.0
Y = 12.3
Z = -13.4

c. complex

Complex numbers are written with a "j" as the imaginary part.

format:
2. String
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.
In the case of string handling, the operator + is used to concatenate two strings as the operation "hello"+"
python" returns "hello python".

format:
S1='Welcome'
S2="to Python"
S3='''world'''
Python Example Program - String Datatypes in Python
Example:

a = "Welcome" #using double quotes


b ='Python' #using single quotes
c = '''World''' #using triple quotes
print("Datatype of Variable a :",type(a))
print(a+b) #to concatenate two strings

Output:

Datatype of Variable a : <class ‘str’>


Welcome Python
Type Conversion & Type Casting in Python

Type Conversion & Casting


The Type Conversion is the process of converting the value of one data
type to another data type. In general, Type Conversion classified into two
types

● Implicit Type Conversion


● Explicit Type Conversion( Type Casting )

Implicit Type Conversion :


In Implicit type conversion, Python interpreter automatically converts one
data type to another data [Link] this Type Conversion the python
Python Example Program - Implicit Type Conversion in Python
num1 = 15 #int

num2 = 4.5 #float

num3 = num1 + num2

print("Value of num3:" ,num3)

print("Datatype of num3:" ,type(num3))

Output: $python3 [Link]

Value of num3 : 19.5

datatype of num3 : <class 'float'>

In the above example, we are trying to add two variable values(num1 is integer datatype & num2 is folat
datatype),but resultant variable(num3) is float datatype, because python interpreter converts lower
datatype(integer) to higher datatype(float) to avoid data loss.
Explicit Type Conversion (Type Casting):
In explicit type conversion, the user converts one data type to another data type. In this type conversion, the user convert
a higher datatype to a lower datatype or a lower datatype to a higher datatype.
An Explicit type conversion is also called "type casting" in Python
Python supports following functions to perform Type Casting in Python:
● int () : This function converts any data type to integer.
● float() : This function is used to convert any data type to a floating point number.
● str() : This function is used to convert any data type to a string.

Python Example Programs—Explicit Type Conversion in Python


Example: "[Link]"

a = int(2) # returns 2
b = int(3.2) # returns 3
c = int("6") # returns 6
d = int("11010",2) # returns base 2 value
print(a)
print(b)
print(c)
print(d)
Example: "[Link]"

a = float(2) # returns 2.0

b = float(3.2) # returns 3.2

c = float("6") # returns 6.0

d = float("6.2") # returns 6.2

print(a)

print(b)

print(c)

print(d)

Output: $python3 [Link]

2.0

3.2

6.0

6.2
Example: "[Link]"
a = str("abc") # returns 'abc'
b = str(3.2) # returns '3.2'
c = str(6) # returns '6'
print(a)
print(b)
print(c)

abc
3.2
6

Note: In Python, when an integer


value is cast to float value, then it is
appended with the fractional part
containing zeros (0) and when a float
value is cast to an integer it rounding
down to the previous whole number.
Operators in Python

The operator can be defined as a symbol which is responsible for a particular operation between two operands.
Python provides a variety of operators described as follows.

● Arithmetic operators
● Assignment Operators
● Comparison operators
● Bitwise Operators
● Identity Operators
● Logical Operators
● Membership Operators

1. Arithmetic operators
Arithmetic operators are used to perform arithmetic operations between two operands.
Operator Description

+ (addition) Add two operands

- (subtraction) Subtract right operand from the left

*(multiplication) Multiply two operands

/ (divide) Divide left operand by the right one (always results into float)

%( reminder) Modulus - remainder of the division of left operand by the right

// (floor division) Floor division - division that results into whole number adjusted to the left in the number line

** (exponent) Exponent - left operand raised to the power of right


Python Example Program - Arithmetic operators in Python

Example:

x = 20
y = 10
print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x // y =',x//y)
print('x ** y =',x**y)

Output:

x + y = 30
x - y = 10
x * y = 200
x / y = 2
x // y = 0
x ** y = 8
2. Assignment Operators Python Example Program
The assignment operators are used to
- Assignment operators in
assign the value of the right expression Python
to the left operand.
Example:

# assign a value to variable


x = 10
y = 6
# x = x + y assignment after
addition
x += y
# print result
print( "Addition = ", x)

# x = x - y assignment after
subtraction
x -= y
# print result
print( "Subtraction = ", x)

# x = x * y assignment after
Operator Description

= (Assigns to) Assigns values from right side operands to left side operand.

+= (Assignment after Addition) It adds right operand to the left operand and assign the result to left operand.

-= (Assignment after Subtraction) It subtracts right operand from the left operand and assign the result to left operand.

*= (Assignment after Multiplication) It multiplies right operand with the left operand and assign the result to left operand.

/= (Assignment after Division) It divides left operand with the right operand and assign the result to left operand.

%= (Assignment after Modulus) It takes modulus using two operands and assign the result to left operand.

**= (Assignment after Exponent) Performs exponential (power) calculation on operators and assign value to the left operand.

//= (Assignment after floor division) It performs floor division on operators and assign value to the left operand.
3. Comparison operators Operator Description

Comparison operators are used to


comparing the value of the two == (Equal to) Equal to - True if both operands are equal.

operands and returns boolean true or


false accordingly. != (Not equal to) Not equal to - True if operands are not equal.

<= (Less than or Less than or equal to - True if left operand is less than or equal to
equal) the right

>= (Greater than or Greater than or equal to - True if left operand is greater than or
equal) equal to the right

< (Less than) Less that - True if left operand is less than the right

> (Greater than) Greater that - True if left operand is greater than the right
Python Example Program
- Comparison operators
in Python

Example:

x = 20
y = 10
print('x > y is',x > y)
print('x < y is',x < y)
print('x == y is',x == y)
print('x != y is',x != y)
print('x >= y is',x >= y)
print('x <= y is',x <= y)

Output:

x > y is True
x < y is False
x == y is False
Operator Description

& (binary and) Sets each bit to 1 if both bits are 1

| (binary or) Sets each bit to 1 if one of two bits is 1

^ (binary xor) Sets each bit to 1 if only one of two bits is 1

~ (negation) Inverts all the bits

<< (left shift) Shift left by pushing zeros in from the right and let the leftmost bits fall off

>> (right shift) Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off
Python Example Program - Bitwise operators in Python

Example:

a = 9 # equal to 1001
b = 12 # equal to 1100

print ("a & b = ",a & b)


print ("a | b = ",a | b)
print("a ^ b = ",a ^ b)
print("~a = ",~a)
print("a << 2 = ",a << 2)
print("a >> 2 = ",a >> 2)

Output:

a & b = 8
a | b = 13
a ^ b = 5
~a = -10
a << 2 = 36
a >> 2 = 2
5. Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are actually the sam
object, with the same memory location.

Operator Description

is Returns true if both variables are the same object ( if id(x) equals id(y) )

is not Returns true if both variables are not the same object
Python Example Program
- Identity operators in
Python

Example:

x=10
y=10
print(x is y)
print("id(x)= %d id(y)= %d"
%(id(x),id(y)))
y=20
print(x is not y)
print("id(x)= %d id(y)= %d"
%(id(x),id(y)))

Output:

True
id(x)= 10105376 id(y)=
10105376
6. Logical Operators
The logical operators are used primarily in the expression evaluation to make a decision.
Example:

x = True
Operator Description y = False
print('x and y is',x
and y)
and (logical and) Returns True if both statements are true print('x or y is',x
or y)
print('not x
or (logical or) Returns True if one of the statements is true
is',not x)

not (logical not) Reverse the result, returns False if the result is true Output:

x and y is False
x or y is True
not x is False
7. Membership Operators
The logical operators are used primarily in the expression evaluation to make a decision.

Opera Python Example


tor Description Program—Membership opera
in Python
in it Returns True if a sequence with the specified value is present in the
object (list, tuple, or dictionary)
Example:

not it Returns True if a sequence with the specified value is not present in x = 'Hello world'
in ) the object (list, tuple, or dictionary) print('H' in x)
print('hello' not in x)

Output:

True
True

You might also like