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

Python Programming

The document provides an introduction to Python programming, covering its basics including data types, expressions, statements, and the differences between scripting and programming languages. It explains the installation process, the execution of Python code in both interactive and script modes, and the characteristics that make Python popular such as its object-oriented nature and ease of use. Additionally, it details variable assignment, operator precedence, and examples of various data types like integers, floats, booleans, strings, and lists.

Uploaded by

jijithabiju2244
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 views28 pages

Python Programming

The document provides an introduction to Python programming, covering its basics including data types, expressions, statements, and the differences between scripting and programming languages. It explains the installation process, the execution of Python code in both interactive and script modes, and the characteristics that make Python popular such as its object-oriented nature and ease of use. Additionally, it details variable assignment, operator precedence, and examples of various data types like integers, floats, booleans, strings, and lists.

Uploaded by

jijithabiju2244
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

PYTHON PROGRAMMING

UNIT I BASICS
Python-Variables-Executing Python from the Command Line-Editing Python Files-Python Reserved
Words- Basic Syntax-Comments-Standard Data Types–Relational Operators-Logical Operators-
Bit Wise Operators-Simple Input and Output.

INTRODUCTION DATA, EXPRESSIONS, STATEMENTS


Introduction to Python and installation, data types: Int, float, Boolean, string, and list;
variables, expressions, statements, precedence of operators, comments; modules, functions--
- function and its use, flow of execution, parameters and arguments.

Introduction to Python and installation:

Python is a widely used general-purpose, high level programming language. It was initially
designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It
was mainly developed for emphasis on code readability, and its syntax allows programmers
to express concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate systems more
efficiently.
There are two major Python versions- Python 2 and Python 3.
• On 16 October 2000, Python 2.0 was released with many new features.
• On 3rd December 2008, Python 3.0 was released with more testing and includes new
features.

Beginning with Python programming:


1) Finding an Interpreter:
Before we start Python programming, we need to have an interpreter to interpret and run our
programs. There are certain online interpreters like [Link]
[Link] or [Link] that can be used to start Python without installing an
interpreter.
Windows: There are many interpreters available freely to run Python scripts like IDLE
(Integrated Development Environment) which is installed when you install the python
software from [Link]
2) Writing first program:

# Script Begins

Statement1
Statement2

Statement3

# Script Ends

Differences between scripting language and programming language:

Why to use Python:

The following are the primary factors to use python in day-to-day life:

1. Python is object-oriented
Structure supports such concepts as polymorphism, operation overloading and
multiple inheritance.
2. Indentation
Indentation is one of the greatest feature in python
3. It’s free (open source)
Downloading python and installing python is free and easy
4. It’s Powerful
 Dynamic typing
 Built-in types and tools
 Library utilities
 Third party utilities (e.g. Numeric, NumPy, sciPy)
 Automatic memory management
5. It’s Portable
 Python runs virtually every major platform used today
 As long as you have a compaitable python interpreter installed, python
programs will run in exactly the same manner, irrespective of platform.
6. It’s easy to use and learn
 No intermediate compile
 Python Programs are compiled automatically to an intermediate form called
byte code, which the interpreter then reads.
 This gives python the development speed of an interpreter without the
performance loss inherent in purely interpreted languages.
 Structure and syntax are pretty intuitive and easy to grasp.
7. Interpreted Language
Python is processed at runtime by python Interpreter
8. Interactive Programming Language
Users can interact with the python interpreter directly for writing the programs
9. Straight forward syntax
The formation of python syntax is simple and straight forward which also makes it
popular.

Installation:

There are many interpreters available freely to run Python scripts like IDLE (Integrated
Development Environment) which is installed when you install the python software
from [Link]
Steps to be followed and remembered:
Step 1: Select Version of Python to Install.
Step 2: Download Python Executable Installer.
Step 3: Run Executable Installer.
Step 4: Verify Python Was Installed On Windows.

Step 5: Verify Pip Was Installed.


Step 6: Add Python Path to Environment Variables (Optional)

Working with Python

Python Code Execution:

Python’s traditional runtime execution model: Source code you type is translated to byte
code, which is then run by the Python Virtual Machine (PVM). Your code is automatically
compiled, but then it is interpreted.
Source Byte code Runtime

PVM
[Link] [Link]

Source code extension is .py


Byte code extension is .pyc (Compiled python code)

There are two modes for using the Python interpreter:


• Interactive Mode
• Script Mode
Running Python in interactive mode:

Without passing python script file to the interpreter, directly execute code to Python prompt.
Once you’re inside the python interpreter, then you can start.

>>> print("hello world")

hello world

# Relevant output is displayed on subsequent lines without the >>> symbol

>>> x=[0,1,2]

# Quantities stored in memory are not displayed by default.

>>> x

#If a quantity is stored in memory, typing its name will display it.

[0, 1, 2]

>>> 2+3

The chevron at the beginning of the 1st line, i.e., the symbol >>> is a prompt the python
interpreter uses to indicate that it is ready. If the programmer types 2+6, the interpreter replies
8.

Running Python in script mode:


Alternatively, programmers can store Python script source code in a file with
the .py extension, and use the interpreter to execute the contents of the file. To execute the
script by the interpreter, you have to tell the interpreter the name of the file. For example, if
you have a script name [Link] and you're working on Unix, to run the script you have to
type:

python [Link]
Working with the interactive mode is better when Python programmers deal with small pieces
of code as you can type and execute them immediately, but when the code is more than 2-4
lines, using the script for coding can help to modify and use the code in future.

Example:

Data types:

The data stored in memory can be of many types. For example, a student roll number is stored
as a numeric value and his or her address is stored as alphanumeric characters. Python has
various standard data types that are used to define the operations possible on them and the
storage method for each of them.

Int:

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


length.

>>> print(24656354687654+2)
24656354687656
>>> print(20)
20
>>> print(0b10)
2
>>> print(0B10)
2
>>> print(0X20)
32
>>> 20
20
>>> 0b10
2
>>> a=10
>>> print(a)
10
# To verify the type of any object in Python, use the type() function:
>>> type(10)
<class 'int'>
>>> a=11
>>> print(type(a))
<class 'int'>
Float:

Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.

Float can also be scientific numbers with an "e" to indicate the power of 10.

>>> y=2.8
>>> y
2.8
>>> y=2.8
>>> print(type(y))
<class 'float'>
>>> type(.4)
<class 'float'>
>>> 2.
2.0
Example:
x = 35e3
y = 12E4
z = -87.7e100

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

Output:
<class 'float'>
<class 'float'>
<class 'float'>

Boolean:

Objects of Boolean type may have one of two values, True or False:

>>> type(True)

<class 'bool'>

>>> type(False)

<class 'bool'>

String:

1. Strings in Python are identified as a contiguous set of characters represented in the


quotation marks. Python allows for either pairs of single or double quotes.
• 'hello' is the same as "hello".

• Strings can be output to screen using the print function. For example: print("hello").

>>> print("JCT college")JCT college

>>> type("JCT college")

<class 'str'>
>>> print('JCT

college')JCT college

>>> " "

''

If you want to include either type of quote character within the string, the simplest way is to
delimit the string with the other type. If a string is to contain a single quote, delimit it with
double quotes and vice versa:

>>> print("JCT is an autonomous (') college")JCT is

an autonomous (') college

>>> print('JCT is an autonomous (") college')JCT is

an autonomous (") college Suppressing Special

Character:

Specifying a backslash (\) in front of the quote character in a string “escapes” it and causes
Python to suppress its usual special meaning. It is then interpreted simply as a literal single
quote character:

>>> print("JCT is an autonomous (\') college")JCT is

an autonomous (') college

>>> print('JCT is an autonomous (\") college')JCT is

an autonomous (") college

The following is a table of escape sequences which cause Python to suppress the usual
special interpretation of a character in a string:

>>> print('a\
....b')
a. ..b
>>> print('a\
b\
c')
abc
>>> print('a \n b')
a
b
>>> print("JCT \n
college")JCT college

Escape Usual Interpretation of


Sequence Character(s) After Backslash “Escaped” Interpretation
\' Terminates string with single quote opening delimiter Literal single quote (') character
\" Terminates string with double quote opening delimiter Literal double quote (") character
\newline Terminates input line Newline is ignored
\\ Introduces escape sequence Literal backslash (\) character

In Python (and almost all other common computer languages), a tab character can be
specified by the escape sequence \t:

>>> print("a\tb")
a b
List:

 It is a general purpose most widely used in data structures


 List is a collection which is ordered and changeable and allows duplicate members.
(Grow and shrink as needed, sequence type, sortable).
 To use a list, you must declare it first. Do this using square brackets and separate
values with commas.
 We can construct / create list in many ways.
Ex:
>>> list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]
>>> x=list()
>>> x
[]

>>> tuple1=(1,2,3,4)
>>> x=list(tuple1)
>>> x
[1, 2, 3, 4]
Variables:

Variables are nothing but reserved memory locations to store values. This means that when
you create a variable you reserve some space in memory.

Based on the data type of a variable, the interpreter allocates memory and decides what can
be stored in the reserved memory. Therefore, by assigning different data types to variables,
you can store integers, decimals or characters in these variables.

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)

Assigning Values to Variables:


Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to
assign values to variables.

The operand to the left of the = operator is the name of the variable and the operand to the
right of the = operator is the value stored in the variable.
For example −

a= 100 # An integer assignment

b = 1000.0 # A floating point

c = "John" # A string

print (a)

print (b)

print (c)

This produces the following result −

100

1000.0

John

Multiple Assignment:
Python allows you to assign a single value to several variables simultaneously.

For example :

a=b=c=1

Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables.

For example −

a,b,c = 1,2,"JCT“

Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively,
and one string object with the value "john" is assigned to the variable c.

Output Variables:

The Python print statement is often used to output variables.

Variables do not need to be declared with any particular type and can even change type after
they have been set.
x=5 # x is of type int
x = "JCT " # x is now of type str
print(x)

Output: JCT

To combine both text and a variable, Python uses the “+” character:

Example
x = "awesome"
print("Python is " + x)

Output
Python is awesome

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

Example
x = "Python is "
y = "awesome"
z=x+y
print(z)

Output:
Python is awesome

Expressions:

An expression is a combination of values, variables, and operators. An expression is


evaluated using assignment operator.

Examples: Y=x + 17

>>> x=10

>>> z=x+20

>>> z

30
>>> x=10

>>> y=20

>>> c=x+y

>>> c

30

A value all by itself is a simple expression, and so is a variable.

>>> y=20

>>> y

20

Python also defines expressions only contain identifiers, literals, and operators. So,

Identifiers: Any name that is used to define a class, function, variable module, or object is an
identifier.

Literals: These are language-independent terms in Python and should exist independently in
any programming language. In Python, there are the string literals, byte literals, integer literals,
floating point literals, and imaginary literals.

Operators: In Python you can implement the following operations using the corresponding
tokens.
Operator Token

add +

subtract -

multiply *

Integer Division /

remainder %

Binary left shift <<

Binary right shift >>

and &

or \

Less than <

Greater than >

Less than or equal to <=

Greater than or equal to >=

Check equality ==

Check not equal !=


Some of the python expressions are:

Generator expression:

Syntax: ( compute(var) for var in iterable )

>>> x = (i for i in 'abc') #tuple comprehension


>>> x
<generator object <genexpr> at 0x033EEC30>

>>> print(x)
<generator object <genexpr> at 0x033EEC30>

You might expect this to print as ('a', 'b', 'c') but it prints as <generator object <genexpr>
at 0x02AAD710> The result of a tuple comprehension is not a tuple: it is actually a
generator. The only thing that you need to know now about a generator now is that you
can iterate over it, but ONLY ONCE.

Conditional expression:
Syntax: true_value if Condition else false_value

>>> x = "1" if True else "2"

>>> x

'1'

Statements:

A statement is an instruction that the Python interpreter can execute. We have normally two
basic statements, the assignment statement and the print statement. Some other kinds of
statements that are if statements, while statements, and for statements generally called as
control flows.

Examples:

An assignment statement creates new variables and gives them values:

>>> x=10
>>> college="JCT"

An print statement is something which is an input from the user, to be printed / displayed on
to the screen (or ) monitor.

>>> print("JCT colege")JCT college

Precedence of Operators:

Operator precedence affects how an expression is evaluated.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first multiplies 3*2 and then adds into 7.

Example 1:

>>> 3+4*2

11

Multiplication gets evaluated before the addition operation

>>> (10+10)*2

40

Parentheses () overriding the precedence of the arithmetic operators

Example 2:
a = 20
b = 10
c = 15
d=5
e=0

e = (a + b) * c / d #( 30 * 15 ) / 5
print("Value of (a + b) * c / d is ", e)

e = ((a + b) * c) / d # (30 * 15 ) / 5
print("Value of ((a + b) * c) / d is ", e)

e = (a + b) * (c / d); # (30) * (15/5)


print("Value of (a + b) * (c / d) is ", e)

e = a + (b * c) / d; # 20 +
(150/5) print("Value of a + (b *
c) / d is ", e)

Output:
C:/Users/JCT/AppData/Local/Programs/Python/Python38-
32/pyyy/[Link] Value of (a + b) * c / d is 90.0
Value of ((a + b) * c) / d is
90.0 Value of (a + b) * (c /
d) is 90.0 Value of a + (b *
c) / d is 50.0

Comments:
Single-line comments begins with a hash(#) symbol and is useful in mentioning that
the whole line should be considered as a comment until the end of line.

A Multi line comment is useful when we need to comment on many lines. In python, triple
double quote(“ “ “) and single quote(‘ ‘ ‘)are used for multi-line commenting.

Example:

Output:

C:/Users/JCT/AppData/Local/Programs/Python/Python38-32/pyyy/[Link] 30
Basic Python Syntax
1. Print Output
print("Hello, World!")

2. Variables
name = "Alice"
age = 25
height = 5.6

3. Data Types
x = 10 # Integer
y = 3.14 # Float
name = "John" # String
is_student = True # Boolean

4. Taking Input
name = input("Enter your name: ")
print("Hello", name)

5. If-Else Statements
age = 18

if age >= 18:


print("Adult")
else:
print("Minor")

6. Loops

For Loop

for i in range(5):
print(i)

While Loop

count = 0

while count < 5:


print(count)
count += 1
7. Functions
def greet(name):
return "Hello " + name

print(greet("Alice"))

8. Lists
fruits = ["apple", "banana", "mango"]

print(fruits[0]) # apple
[Link]("grape")

9. Dictionaries
student = {
"name": "John",
"age": 20
}

print(student["name"])

10. Classes and Objects


class Person:
def __init__(self, name):
[Link] = name

def introduce(self):
print("My name is", [Link])

p = Person("Alice")
[Link]()
Important Python Rules

 No semicolon (;) required at the end of statements.


 Indentation (usually 4 spaces) defines code blocks.
 Comments start with #.

# This is a comment

if True:
print("Indentation matters!")
Example Program
name = input("Enter your name: ")

if name:
print("Welcome,", name)
else:
print("Please enter a valid name.")

1. Arithmetic Operators

Used to perform mathematical calculations.

Operator Description Example

+ Addition 5+3→8

- Subtraction 5-3→2

* Multiplication 5 * 3 → 15

/ Division 5 / 2 → 2.5

// Floor Division 5 // 2 → 2

% Modulus (Remainder) 5 % 2 → 1

** Exponentiation 2 ** 3 → 8

Example:

a = 10
b=3

print(a + b) # 13
print(a - b) # 7
print(a * b) # 30
print(a / b) # 3.3333
print(a // b) # 3
print(a % b) # 1
print(a ** b) # 1000
2. Comparison (Relational) Operators

Used to compare two values. They return True or False.

Operator Description Example

== Equal to 5 == 5 → True

!= Not equal to 5 != 3 → True

> Greater than 5 > 3 → True

< Less than 5 < 3 → False

>= Greater than or equal to 5 >= 5 → True

<= Less than or equal to 5 <= 3 → False

Example:

x = 10
y = 20

print(x == y)
print(x != y)
print(x < y)
print(x >= y)

3. Logical Operators

Used to combine multiple conditions.

Operator Description Example

and True if both conditions are true True and False → False

or True if at least one condition is true True or False → True

not Reverses the result not True → False

Example:

a = 10
b = 20
print(a < b and b > 15)
print(a > b or b > 15)
print(not(a > b))

4. Assignment Operators

Used to assign values to variables.

Operator Example Equivalent To

= x=5 Assign value

+= x += 2 x=x+2

-= x -= 2 x=x-2

*= x *= 2 x=x*2

/= x /= 2 x=x/2

//= x //= 2 x = x // 2

%= x %= 2 x=x%2

**= x **= 2 x = x ** 2

Example:

x = 10
x += 5
print(x) # 15

x *= 2
print(x) # 30

5. Bitwise Operators

Operate on the binary representation of integers.

Operator Description

& AND
Operator Description

` `

^ XOR

~ NOT

<< Left Shift

>> Right Shift

Example:

a = 5 # 0101
b = 3 # 0011

print(a & b) # 1
print(a | b) # 7
print(a ^ b) # 6

6. Membership Operators

Check whether a value exists in a sequence.

Operator Description

in Returns True if value is present

not in Returns True if value is absent

Example:

fruits = ["apple", "banana", "mango"]

print("apple" in fruits) # True


print("grape" not in fruits) # True

7. Identity Operators

Check whether two variables refer to the same object in memory.


Operator Description

is True if both variables refer to the same object

is not True if they refer to different objects

Example:

a = [1, 2]
b=a
c = [1, 2]

print(a is b) # True
print(a is c) # False
print(a == c) # True

Note: == compares values, while is compares object identity.

Summary Table
Operator Type Operators

Arithmetic +, -, *, /, //, %, **

Comparison ==, !=, >, <, >=, <=

Logical and, or, not

Assignment =, +=, -=, *=, /=, //=, %=, **=

Bitwise &, `

Membership in, not in

Identity is, is not

Basic Input and Output in Python


Output using print()

The print() function is used to display information on the screen.

Example 1: Print a message


print("Hello, World!")

Output:

Hello, World!

Example 2: Print variables

name = "Alice"
age = 20

print(name)
print(age)

Output:

Alice
20

Input using input()

The input() function is used to get input from the user. It always returns the input as a string.

Example 1: Read a name

name = input("Enter your name: ")


print("Hello,", name)

Sample Output:

Enter your name: John


Hello, John

Reading Numbers

Since input() returns a string, convert it to a number using int() or float().

Integer Input

age = int(input("Enter your age: "))


print("Your age is", age)
Sample Output:

Enter your age: 21


Your age is 21

Float Input

price = float(input("Enter the price: "))


print("Price is", price)

Sample Output:

Enter the price: 99.5


Price is 99.5

Multiple Inputs

You can read multiple values in one line using split().

a, b = input("Enter two numbers: ").split()

print(a)
print(b)

Sample Output:

Enter two numbers: 10 20


10
20

To read them as integers:

a, b = map(int, input("Enter two numbers: ").split())

print("Sum =", a + b)

Sample Output:

Enter two numbers: 10 20


Sum = 30

Simple Example Program


name = input("Enter your name: ")
age = int(input("Enter your age: "))

print("Name:", name)
print("Age:", age)

Sample Output:

Enter your name: Alice


Enter your age: 20
Name: Alice
Age: 20
Summary

 print() → Displays output.


 input() → Reads input as a string.
 int() → Converts input to an integer.
 float() → Converts input to a decimal number.
 split() → Splits multiple inputs entered on one line.
 map() → Applies a function (such as int) to each input value.

You might also like