0% found this document useful (0 votes)
11 views30 pages

Python_minor_mod1

The document provides a comprehensive introduction to Python programming, covering its features, environment setup, and methods to run Python code. It details the installation process for various platforms, the use of Python's built-in IDE (IDLE), and modern IDEs like Visual Studio Code and PyCharm. Additionally, it explains Python's syntax, including comments, indentation, character sets, and tokens.

Uploaded by

sharanyavp
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)
11 views30 pages

Python_minor_mod1

The document provides a comprehensive introduction to Python programming, covering its features, environment setup, and methods to run Python code. It details the installation process for various platforms, the use of Python's built-in IDE (IDLE), and modern IDEs like Visual Studio Code and PyCharm. Additionally, it explains Python's syntax, including comments, indentation, character sets, and tokens.

Uploaded by

sharanyavp
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/ 30

CSC1MN102-PYTHON PROGRAMMING

Introduction to Python, Features of Python, Different methods to run Python,Python IDE, Comments,
Indentation, Identifiers,Keywords, Variables, Standard Data Types, Input Output Functions, Import functions,
range function, Operators and Operands, Precedence of Operators, Associativity, Type Conversion, Multiple
Assignment, Expressions and Statements, Evaluation of Expressions, Boolean Expressions.

Python is a high-level, general-purpose, open-source programming language that supports multiple


programming paradigms, including object-oriented, procedural, and functional programming. It was
developed by Guido van Rossum in 1991 at the Centrum Wiskunde & Informatica (CWI), the National
Research Institute for Mathematics and Computer Science in the Netherlands. Python is currently
maintained by the Python Software Foundation (PSF), a non-profit organization that promotes the
development and use of the language. The name "Python" was inspired by the British comedy group
Monty Python, reflecting the developer’s intent to make programming more enjoyable. Designed for
readability and ease of use, Python is platform-independent and operates on a wide range of systems,
including Unix/Linux, macOS, and Windows. As of April 8, 2025, the most recent stable release is
Python 3.13.3, accompanied by updated official documentation.

FEATURES
 Easy to Learn and Use:
Python has a simple and clean syntax, making it easy for beginners to learn and use.
 High-Level Language:
Python allows programmers to write instructions using human-friendly syntax and hides low-
level machine details.
 Interpreted Language:
Python code is not compiled into machine code directly. It is executed line-by-line by the
Python interpreter, which makes debugging and testing easier.
 Interactive:
Users can interact directly with the Python interpreter using the interactive shell (REPL) to
write and test code.
 Dynamically Typed:
You don’t need to declare variable types. Python automatically detects the type at runtime.
 Free and Open Source:
Python is free to download and use. It is also open source, with a large community contributing
to its development.

1
 Portable Language:
Python runs on almost all major platforms. As long as a compatible interpreter is installed,
Python code runs the same across different systems.
 Extendable:
You can add low-level modules (written in C, C++, etc.) to the Python interpreter to optimize
performance or customize functionality.
 Database Support:
Python provides built-in and third-party libraries to connect and interact with major
commercial databases.
 GUI Programming:
Python supports GUI development through libraries like Tkinter, PyQt, and others. These can
be used across platforms like Windows, macOS, and Unix.
 Scalable:
Python supports clean code structure and modular programming, making it suitable for
developing large-scale applications.
 Supports Multiple Programming Paradigms:
Python supports functional, structured, and object-oriented programming (OOP).
 Scripting and Application Development:
Python can be used both as a scripting language and for developing complex applications,
using bytecode compilation.
 Automatic Garbage Collection:
Python automatically manages memory and reclaims unused memory using its built-in garbage
collector.
 Integratable:
Python can easily integrate with other languages like C, C++, and Java.
 Powerful:
Python offers features like dynamic typing, built-in data types and tools, an extensive standard
library, third-party modules (e.g., NumPy, SciPy), and automatic memory management.

PYTHON - ENVIRONMENT SETUP


Python is available on a wide variety of platforms including Linux and Mac OS X.
Getting Python
The most up-to-date source code, binaries, documentation, and news are available on the official
Python website:
🔗 https://www.python.org/

2
You can also download Python documentation in HTML, PDF, and PostScript formats from:
🔗 https://www.python.org/doc/
python distributions are available for various platforms. You simply need to download the
appropriate binary file for your system and install it.
If a binary version is not available for your platform, you will need a C compiler to compile the
source code manually. This approach allows for greater flexibility in choosing features during
installation.
Installing Python on various platforms −
Unix and Linux Installation
 Open a web browser and go to:
🔗 https://www.python.org/downloads/
 Download the zipped source code for Unix/Linux.
 Extract the downloaded files.
 (Optional) Edit the Modules/Setup file to customize features.
 Run the following commands in your terminal:
./configure
make
make install
Python will be installed at the default location:
/usr/local/bin for executables and
/usr/local/lib/python312/ for libraries, where 312 refers to Python version 3.12.

Windows Installation
Installing the Latest Version of Python on Windows (Python 3.13.x)
1. Download the Installer
o Open a web browser and go to the official Python download page:
🔗 https://www.python.org/downloads/
o Click on the latest Python version for Windows (e.g., Python 3.13.3) and download
the Windows installer (e.g., python-3.13.3-amd64.exe for 64-bit systems).
2. Run the Installer
o Locate the downloaded .exe file and double-click to run it.
o On the first screen of the installer:
 ✅ Check the box that says “Add Python to PATH” (very important).
 Click on “Install Now” to begin installation using default settings.
3. Wait for Installation to Complete

3
o The installer will set up Python, pip (Python package manager), and the standard
library.
o Once done, you will see the “Setup was successful” screen.
4. Verify the Installation
o Open the Command Prompt (press Win + R, type cmd, and hit Enter).
o Type:
python --version
This should display the installed version, e.g., Python 3.13.3.
o Also try:
pip --version
to confirm pip was installed.

Running Python (Updated for Python 3.13.x)


Python programs can be run in several ways depending on your platform and development
preference. The most common methods are:
1. Interactive Mode (Python Shell)
Python includes an interactive shell (also known as the REPL – Read-Eval-Print Loop), where you
can type and execute Python commands one line at a time.
To start the interactive shell:
 On Windows (Command Prompt or PowerShell):
C:\> python
 On Linux/macOS (Terminal):
$ python3
You’ll see the Python prompt (>>>) where you can start typing and testing Python code
interactively.
2.Running Python Scripts from the Command Line

You can execute complete Python programs (saved with .py extension) via the command line:
Command format:
 Windows:
C:\> python script.py
 Linux/macOS:
$ python3 script.py
o The script file is saved with a .py extension.
o On Unix/Linux, the script has execution permissions (chmod +x script.py) if using a shebang line
(#!/usr/bin/env python3).

4
3.Using IDLE (Python’s Built-in IDE)

IDLE (Integrated Development and Learning Environment)


IDLE is bundled with the standard Python installer and offers a user-friendly interface to:
 Write Python code in a code editor.
 Run and test code in the Python Shell.
 Debug using a built-in debugger.
 Highlight syntax and check errors.
How to open IDLE:
 On Windows:
Open the Start Menu → Python 3.13 → IDLE (Python 3.13 GUI).
 On macOS/Linux:
Type idle3 in the terminal, or launch it from the applications menu (if installed).

Python Shell and Script Mode in IDLE (Python 3.13)


When you start Python IDLE (Integrated Development and Learning Environment) — either by
clicking its icon on the desktop or from the Start Menu → Apps by name → IDLE (Python 3.13)
— it opens in the Python Shell by default.
Python Shell (Interactive Mode)
 The Python Shell is an interactive window where you can type Python code and immediately
see the output.
 It acts as an interface between Python commands and the operating system.
 When IDLE starts, you will see the Python command prompt:
>>>
 The >>> symbols (called the Python prompt) indicate that the interpreter is ready to accept
commands.
 When commands are typed directly into the Shell and executed line by line, Python is said to
be operating in interactive mode.
Python IDLE Components
Python IDLE has two key modes:
1. Python Shell (Interactive Mode) – For testing and running commands line by line.
2. Python Editor (Script Mode) – For writing, editing, and running Python programs saved as
.py files.
Script Mode
In Script Mode, Python source code is written in a text editor and saved in a file with a .py extension.
The script is then run using the interpreter.

5
Steps to Run a Python Script using IDLE:
1. Open a text editor (e.g., Notepad or directly within IDLE).
2. Write the Python code and save the file with a .py extension.
(Example: demo.py — default directory might be C:\Users\<YourName>\)
3. Open IDLE (Python GUI).
4. From the File menu, choose Open and select your saved .py file.
5. The code will open in the Python Editor window.
6. Go to the Run menu and click Run Module (or simply press F5).
7. The output of the script will be displayed in the Python Shell window.
Example:
If you saved a file named demo.py with the following content:
print("Hello, Python!")
Running it through the steps above will display in the Python Shell:
Hello, Python!

Modern IDEs for Python Development


While IDLE is a basic environment useful for beginners, modern Integrated Development
Environments (IDEs) offer more advanced features that enhance productivity, code quality, and
debugging.
Popular Modern Python IDEs
1.Visual Studio Code (VS Code)
 Lightweight, fast, and highly customizable.
 Free and open source.
 Offers Python support via the Python extension.
 Features:
o IntelliSense (smart code suggestions and autocompletion)
o Integrated terminal
o Built-in Git support
o Debugger and linting tools
o Jupyter Notebook integration
 Platform: Windows, macOS, Linux

2.PyCharm
 Powerful Python IDE developed by JetBrains.
 Available in two versions:
o Community Edition (free)

6
o Professional Edition (paid, includes web development and database tools)
 Features:
o Smart code navigation and refactoring
o Integrated debugger and test runner
o Virtual environment and package management
o Django support (Professional version)
 Platform: Windows, macOS, Linux
3.Jupyter Notebook / JupyterLab
 Ideal for data science, machine learning, and research.
 Allows code, output, markdown, and visualizations in the same document.
 Often used with Anaconda distribution.
 Features:
o Interactive coding with live output
o Integration with NumPy, pandas, matplotlib, etc.
o Supports multiple programming languages via kernels
4.Thonny
 Beginner-friendly IDE designed for learning Python.
 Simple interface with features like variable explorer and step-by-step debugger.
 Good for schools and students.
 Pre-installed with Python and easy to set up.
5.Spyder
 Scientific Python IDE for data analysis and research.
 Often used by scientists and engineers.
 Built-in IPython console, variable explorer, and plotting support.

Python Interpreter
 Python is an interpreted language – it runs code line by line, not all at once like compiled
languages.
 Python does not convert code directly into machine code. Instead, it first converts the code
into bytecode.
 The Python interpreter handles two main steps when running a program:
1. Compilation:
 Python source code (.py file) is compiled into bytecode (.pyc file) which is a
more efficient, intermediate format..
 Bytecode is saved in a folder called __pycache directory and help speed up
future execution.

7
2. Interpretation:
 The Python Virtual Machine (PVM) reads and executes the bytecode.
 It converts bytecode into machine-level instructions that the computer
understands.
 The interpreter acts as both:
o A translator (from Python code to bytecode),
o And a runtime environment (executing the program).
 Example of Interpreted Languages: Python, JavaScript, Ruby, PHP, Perl
 Example of Compiled Languages: C, C++, C#, COBOL
Key Features of the Python Interpreter
 The interpreter includes the Python Virtual Machine (PVM), which abstracts the underlying
hardware and ensures portability.
 The most widely used implementation of the Python interpreter is CPython, written in C.
 Python interpreters often include a REPL (Read-Eval-Print Loop), allowing developers to
interactively execute and test Python code snippets.

PYTHON COMMENTS
 Comments in Python are lines of text that the interpreter ignores during execution.
 They are used to explain the code, making it more readable and maintainable.
Single-line Comments
 A comment starts with a # symbol. Everything after # on that line is ignored by Python.
# This is a comment
print("Hello, World!")
 Comments can also appear at the end of a code line:
print("Hello, World!") # This is a comment
Multi-line Comments
Option 1: Multiple # symbols for each line
# This is a comment
# written in
# more than just one line
Option 2: Triple-quoted strings (''' or """)
 You can use triple quotes for multiline comments.
 These are ignored if not assigned to a variable.
"""
This is a comment
written in

8
more than just one line
"""
print("Hello, World!")
Note: Technically, triple-quoted strings are not true comments but multi-line string literals.
However, when unassigned, they are treated like comments.

Indentation in Python
In Python, indentation is used to define blocks of code. It tells the Python interpreter that a group of
statements belongs to a specific block. All statements with the same level of indentation are
considered part of the same block. Indentation is achieved using whitespace (spaces or tabs) at the
beginning of each line.
Example:
if 10 > 5:
print("This is true!")
print("I am tab indentation")
print("I have no indentation")
o The first two print statements are indented by 4 spaces, so they belong to the if block.
o The third print statement is not indented, so it is outside the if block.

Common Places Where Indentation is Used:


 Conditional statements (if, else, elif)
 Loops (for, while)
 Functions (def)
 Classes (class)
 Exception handling (try, except, finally)

PYTHON CHARACTER SET


A character set is a collection of valid characters that a programming language can recognize and
use. Each character represents a letter, digit, symbol, or whitespace.
Python supports the following character sets:

9
 Letters:
Uppercase and lowercase alphabets A–Z, a–z
 Digits:
Numeric characters 0–9
 Special Symbols:
Symbols used in expressions and syntax +, -, *, /, (, ), {}, [], =, <, >, etc.
 Whitespaces:
Non-printing characters used for spacing
o Space
o Tab (\t)
o Newline (\n)
o Carriage return (\r)
o Form feed (\f)
 Other Characters:
Python supports all ASCII characters and Unicode characters. These can be used in strings,
identifiers, or other data elements.

TOKENS
A token is the smallest individual unit in a python program. All statements and instructions in a
program are built with tokens. Python breaks each logical line into a sequence of elementary lexical
components Known as Tokens.
Python has the following tokens:
(i) Keyword
(ii) Identifiers
(iii) Literals
(iv) Operators
(v) Punctuator

KEYWORDS
Keywords are special words used by Python interpreter to recognize the structure of program.
As these words have specific meaning for interpreter, they cannot be used for any other purpose.
E.g. int, float,True,elif,else,break,as etc
For checking/displaying the list of keywords available in python use
>>>import keyword
>>>print(keyword.kwlist)

10
IDENTIFIERS
An Identifier is a name used to identify a variable, function, class, module or object.
E.g.: Sum, total_marks, regno, num1, Column31, _Total
Rules for Identifier:
 It consist of letters and digits in any order except that the first character must be a letter letter
or an underscore (_) but no a digit.
 The underscore (_) counts as a character.
 Spaces are not allowed.
 Special Characters are not allowed. Such as @,$ etc.
 An identifier must not be a keyword of Python.
 Variable names should be meaningful which easily depicts the logic.
 Uppercase and lowercase are treated differently.

PYTHON LITERALS
Literals are fixed values or data items used directly in a program’s source code.
They are also known as constants because their value does not change during program execution.
Python supports several types of literals:
1. String Literals
 Represent sequences of characters enclosed in single (') or double (") quotes.
 Example:
 a = "hello"
2. Numeric Literals
 Integer Literals: Whole numbers without a decimal point.
Example:
 p=2
 a = 100
 Floating Point Literals: Numbers with decimal points.
Example:
 salary = 15000.00
3. Boolean Literals
 Represent truth values: True and False (case-sensitive).
 Used to represent logical values.
Example:
bool_1 = (6 > 10)
print(bool_1) # Output: False

11
4. Special Literal – None
 Represents the absence of a value or a null value.
 Often used to indicate that a variable has not been assigned a value yet.
Example:
value1 = 20
value2 = None
print(value1) # Output: 20
print(value2) # Output: None (no visible result in some contexts)

PUNCTUATORS/DELIMITERS
Punctuators (or delimiters) are symbols used in Python to organize the structure of programs. They
define the boundaries of statements, expressions, function calls, indexing, code blocks, and more
example

Symbol Name Example Description


() Parentheses print("Hello") Used for function calls, grouping
[] Square Brackets list1 = [1, 2, 3] Used for list, indexing
{} Curly Braces my_dict = {'a': 1, 'b': 2} Used for dictionaries and sets
: Colon if a > b: Used in defining blocks (if, for, def, etc.)
, Comma a, b = 10, 20 Used to separate items

OPERATORS
Operators are special symbols in Python used to perform operations on variables and values.
 The variables on which operations are performed are called operands.
 Operators can be unary (work on one operand) or binary (work on two operands).

TYPES OF OPERATORS IN PYTHON


1. Arithmetic Operators
Used for mathematical operations.

Operator Description Example


+ Add two operands a + b → 30
- Subtract right operand from the left a - b → -10
* Multiply two operands a * b → 200
/ Divide left operand by the right one (always results into float) b / a → 2.0
% Modulus - remainder of the division of left operand by the right b%a→0
** Exponent - left operand raised to the power of right a ** b → 10^20
Floor division - division that results into whole number adjusted to 9//2 → 4, -11//3
//
the left in the number line → -4

12
2. Comparison (Relational) Operators
Compare two values and return True or False.

Operator Description Example


a == b →
== Equal to- True if both operands are equal.
False
!= Not equal to- True if operands are not equal. a != b → True
> Greater than- True if left operand is greater than or equal to the right a > b → False
< Less than- Less that - True if left operand is less than the right a < b → True
Greater than or equal to- True if left operand is greater than or equal to a >= b →
>=
the right False
<= Less than or equal to- True if left operand is less than or equal to the right a <= b → True
3. Assignment Operators
Used to assign values to variables.

Operator Description Example

= Assign c=a+b

+= Add and assign c += a (same as c = c + a)

-= Subtract and assign c -= a

*= Multiply and assign c *= a

/= Divide and assign c /= a

%= Modulus and assign c %= a

**= Exponent and assign c **= a

//= Floor divide and assign c //= a

4. Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation.
Let a = 60 (0011 1100) and b = 13 (0000 1101)
Operator Description Example
& returns 1 if both the bits are 1, otherwise 0. (a & b)=12
(Binary AND) (means 0000 1100)
| eturns 1 if any of the bits is 1. If both the bits are 0, (a | b) = 61
(Binary OR) then it returns 0. (means 0011 1101)
^ returns 1 if one of the bits is 0 and the other bit is 1. (a ^ b) = 49
Binary XOR If both the bits are 0 or 1, then it returns 0. (means 0011 0001)
~ bitwise NOT operator (~), which expects just one (~a ) = -61
argument, making it the only unary bitwise

13
Binary Ones operator. It performs logical negation on a given (means 1100 0011 in 2's
Complement number by flipping all of its bits: complement form due to a
signed binary number.
<< The left operands value is moved left by the number a << 2 = 240
Binary Left of bits specified by the right operand. (means 1111 0000)
Shift
>> The left operands value is moved right by the a >> 2 = 15
Binary Right number of bits specified by the right operand. (means 0000 1111)
Shift

5. Logical Operators
Used to combine conditional statements.

Operator Description Example


and True if both are True a and b
or True if at least one is True a or b
not Reverses the condition not(a and b)

6. Membership Operators
Check membership in a sequence like string, list, or tuple.

Operator Description Example


in True if value is found 5 in [1, 2, 5] → True
not in True if value is not found 3 not in [1, 2, 5] → True

7. Identity Operators
Check if two variables refer to the same object.

Operator Description Example


is True if same object x is y
is not True if different objects x is not y

OPERATOR PRECEDENCE IN PYTHON


The combination of values, variables, operators, and function calls is termed as an expression. The
Python interpreter can evaluate a valid expression.
For example:
>>> 5 - 7
-2

14
Here 5 - 7 is an expression.There can be more than one operator in an expression.To evaluate these
types of expressions there is a rule of precedence in Python. It guides the order in which these
operations are carried out.

Precedence Operators
Highest () Parentheses
** Exponentiation
+x, -x, ~x Unary operations
*, /, //, %
+, -
<<, >>
&
^
`
Comparisons: ==, !=, >, <, >=, <=, is, is not, in, not in
not
and
Lowest or

ASSOCIATIVITY OF OPERATORS
Associativity is the order in which an expression is evaluated that has multiple operators of the same
precedence. Left to Right: Most operators follow this.
Right to Left: Only ** (exponentiation).
Example:
12 + 3 * 4 - 6 / 2
= 12 + 12 - 3.0
= 21.0
Note:
 Comparisons like x < y < z mean: x < y and y < z, not nested comparisons.
 Assignment and comparison operators are non-associative.

PYTHON DATA TYPES


Python data types are used to define the type of a variable. They specify the kind of value a variable
can hold. For example, a person’s age is stored as a numeric value, while their address is stored as a
string of alphanumeric characters.
type() Function
The type() function is a built-in function in Python that allows the programmer to check the data type
of any variable.

15
Example:
a = 10
b = 10.5
c = True
d = 1 + 5j
print(type(a)) # <class 'int'>
print(type(b)) # <class 'float'>
print(type(c)) # <class 'bool'>
print(type(d)) # <class 'complex'>

Built-in Data Types in Python

Data Type Class Description


Numeric int, float, complex Holds numeric values
String str Holds sequence of characters
Sequence list, tuple, range Holds collection of ordered items
Mapping dict Holds data in key-value pair format
Boolean bool Holds either True or False
Set set, frozenset Holds a collection of unique items
Numeric Data Types in Python
Numeric values in Python are classified into:
 Integers
 Floating-point numbers
 Complex numbers
1. Integer (int)
 Whole numbers (positive or negative) without a fractional part.
 In Python, there is no limit to how long an integer can be.
 Can be represented in different number systems: binary, octal, and hexadecimal.
Examples:
b = 0b11011000 # binary
print(b) # 216

o = 0o12 # octal
print(o) # 10

h = 0x12 # hexadecimal
print(h) # 18

16
x = int('100') # converting string to int
print(x) # 100
2. Float (float)
 Represents real numbers with a fractional part.
 Can also use scientific notation using e or E.
Examples:
f = 1.2
print(f) # 1.2
print(type(f)) # <class 'float'>

f = 1e3
print(f) # 1000.0

f = float('5.5')
print(f) # 5.5
3. Complex (complex)
 Represents a complex number in the form (real part) + (imaginary part)j
 Use j or J to denote the imaginary part.
Examples:
a=5
print(type(a)) # <class 'int'>
b = 5.0
print(type(b)) # <class 'float'>
c = 2 + 4j
print(type(c)) # <class 'complex'>
Sequence Data Types
A sequence is an ordered collection of elements. It allows multiple values to be stored efficiently.
Main sequence types:
 String
 List
 Tuple
1. String (str)
 A string is a sequence of characters enclosed in single, double, or triple quotes.
 Python has no char type; a single character is a string of length one.

17
Examples:
String1 = 'Welcome to the Geeks World'
print("Single Quotes:", String1)

String2 = "I'm a Geek"


print("Double Quotes:", String2)

String3 = '''I'm a Geek and I live in a world of "Geeks"'''


print("Triple Quotes:", String3)

Escape Sequences in Strings


Escape sequences are used to represent non-printable or special characters in strings. Each begins
with a backslash (\).
Escape Sequence Description
\" Double quote
\' Single quote
\\ Backslash
\a Bell
\b Backspace
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
PYTHON STATEMENTS, EXPRESSIONS & INPUT/OUTPUT FUNCTIONS
Python Statements
 A statement is an instruction that the Python interpreter can execute.
 Examples of common Python statements:
o Assignment statement: x = 5
o Print statement: print("Hello")
o Control statements: if, else, for, while, break, etc.
o Import statements: import math
 When run, Python executes the statement and, if applicable, displays the result.
 Assignment statements do not display a result unless used with print().

Python Expressions
 An expression is a combination of values, variables, operators, and function calls that
produces a result.
 Expressions are evaluated to a single value.

18
Example:
x=5
y=3
z = x + y # This is an expression. z will be 8.
Evaluation of an expression
Evaluation means computing the result of the expression.
x=5
y=3
z = x + y # z = 8 after evaluation

USER INPUT IN PYTHON


Python provides the following ways to accept user input:
1. input() function
Reads a line from input and returns it as a string. The Python interpreter automatically identifies the
whether a user input a string, a number, or a list.
Syntax: input(prompt)
Example:
name = input("Enter your name: ")
print("Hello", name)
You can typecast the input for numbers:
age = int(input("Enter your age: "))
marks = float(input("Enter your marks: "))
2. raw_input() function
 The raw_input function is used in Python's older version like Python 2.x. It takes the input from
the keyboard and return as a string. The Python 2.x doesn't use much in the industry.
 Not used in Python 3.x or later.
 name = raw_input("Enter your name: ") # Python 2.x
eval() FUNCTION
 eval() is a built-in- function used in python, eval() function parses the expression argument and
evaluates it as a python expression. The eval() function evaluates the “String” like a python
expression and returns the result as an integer.
Syntax: eval(expression, globals=None, locals=None)
 The eval() function takes three parameters:
 expression - the string parsed and evaluated as a Python expression
 globals (optional) - a dictionary

19
 locals (optional)- a mapping object. Dictionary is the standard and commonly used mapping
type in Python.
 Example:
 x=1
 print(eval('x + 1')) # Output: 2
print() FUNCTION
 The print() function prints the specified message to the screen, or other standard output device.
 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), sep=' ', end='\n', file=sys.stdout, flush=False)

Parameter Description
object(s) One or more objects to be printed
sep Optional. Separator between objects. Default: space
end Optional. What to print at the end. Default: newline \n
file Optional. Where to print. Default: screen
flush Optional. True to flush the output buffer
Examples:
print("Hello", "World") # Output: Hello World
print("Hello", "World", sep="---") # Output: Hello---World
print("Hello", end=" ") # Output: Hello (without newline)
print("How are you?") # Output: How are you?

Variables
In Python, variables are used to store data values. Python is a dynamically-typed language, meaning
you don't need to declare the type of a variable explicitly—it is determined automatically based on
the value assigned.
Key Features of Python Variables:
Dynamic Typing: A variable can hold different types of values during execution.
a= 10 # Integer
x = "Hello" # String
No Declaration Needed: Variables are created when you assign a value to them.
name= "Alice"
age = 25
Multiple Assignments:
Python supports simultaneous assignment to multiple variables.

20
Syntax
Var1,var2,var3,……..=exp1,exp2,exp3..expn
Python simultaneously evaluates all the expressions on the right and assign them to a corresponding
variable on the left.
Assigning the same value to multiple variables:
a=b=c=5
Assigning different values to multiple variables in one line:
x, y, z = 1, 2, 3
Variable Naming Rules:
 Must start with a letter or an underscore (_).
 Cannot start with a number.
 Can only contain alphanumeric characters and underscores.
 Case-sensitive (myVar and myvar are different).
Variable Types: Python supports various data types, such as:
 Integer: x = 10
 Float: y = 3.14
 String: name = "Alice"
 Boolean: is_active = True
 List: fruits = ["apple", "banana"]
 Tuple: coordinates = (10, 20)
 Dictionary: person = {"name": "Alice", "age": 25}
Type Checking: Use the type() function to check the type of a variable.
x = 10
print(type(x)) # Output: <class 'int'>

range() Function
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1
(by default), and stops before a specified number.
Syntax
range(start, stop, step)

Parameter Description
start Optional. An integer number specifying at which position to start. Default is 0
stop Required. An integer number specifying at which position to stop (not included).
step Optional. An integer number specifying the incrementation. Default is 1

21
Example
for i in range(5):
print(i, end=" ")
print()
Output:
01234
range() allows the user to generate a series of numbers within a given range. Depending on how
many arguments the user is passing to the function, the user can decide where that series of numbers
will begin and end, as well as how big the difference will be between one number and the next.

Python range() function takes can be initialized in 3 ways.


range (stop) takes one argument.
Generates numbers from 0 up to (but not including) stop.
Example: range(5) generates 0, 1, 2, 3, 4.
range (start, stop) takes two arguments.
Generates numbers from start up to (but not including) stop.
Example: range(2, 7) generates 2, 3, 4, 5, 6.
range (start, stop, step) takes three arguments.
Generates numbers from start up to (but not including) stop, with an increment of step.
Example: range(1, 10, 2) generates 1, 3, 5, 7, 9.
A negative step can be used to count backward.
Example: range(10, 0, -1) generates 10, 9, 8, ..., 1.
Note:
The primary purpose of the range() function in Python is to generate a sequence of numbers. This
function is particularly useful when iterating a specific number of times, especially within for loops.

Import in Python
In Python, modules help organize code into reusable files. They allow you to import and use
functions, classes and variables from other scripts. The import statement is the most common way to
bring external functionality into your Python program.

Importing a Module
The most common way to use a module is by importing it with the import statement. This allows
access to all the functions and variables defined in the module.
Example:

22
import math
pie = math.pi
print("Value of pi:", pie)
Output
Value of pi: 3.141592653589793

Importing Specific Functions


Instead of importing the entire module, we can import only the functions or variables we need using
the from keyword. This makes the code cleaner and avoids unnecessary imports.
Example:
from math import pi
print(pi)

Output
3.141592653589793

Importing Built-in Modules


Python provides many built-in modules that can be imported directly without installation. These
modules offer ready-to-use functions for various tasks, such as random number generation, math
operations and file handling.
Example:
import random
res = random.randint(1, 10)
print("Random Number:", res)
Output
Random Number: 3

Importing Modules with Aliases


To make code more readable and concise, we can assign an alias to a module using as keyword. This
is especially useful when working with long module names.
Example:
import math as m
result = m.sqrt(25)
pr
int("Square root of 25:", result)

23
Output
Square root of 25: 5.0

Importing Everything from a Module (*)


Instead of importing specific functions, we can import all functions and variables from a module
using the * symbol. This allows direct access to all module contents without prefixing them with the
module name.
Example:
from math import *
print(pi) # Accessing the constant 'pi'
print(factorial(6)) # Using the factorial function
Output
3.141592653589793

Type Conversion
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
1. Implicit Type Conversion (Coercion)
2. Explicit Type Conversion( Type Casting )
Implicit Type Conversion :
In Implicit type conversion, Python interpreter automatically converts one data type to another data
type.In this Type Conversion the python interpreter converts lower datatype to higher datatype to
avoid data loss.
num1 = 15 #int
num2 = 4.5 #float
num3 = num1 + num2
print("Value of num3:",num3)
print("Datatype of num3:",type(num3))
output
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.

24
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 converts higher datatype to lower datatype or lower datatype to higher datatype.
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. An Explicit type conversion is also called as 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.
bool(x): Converts x to a boolean (0, None, and empty sequences are False, others are True).
list(x): Converts x to a list (e.g., from a tuple or string).
tuple(x): Converts x to a tuple (e.g., from a list or string).
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)
output
2
3
6
26

Example2
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)

25
print(b)
print(c)
print(d)
output
2.0
3.2
6.0
6.2

Expressions in Python
An expression is a combination of operators and operands that is interpreted to produce some other
value. In any programming language, an expression is evaluated as per the precedence of its
operators. So that if there is more than one operator in an expression, their precedence decides which
operation will be performed first. We have many different types of expressions in Python.
1. Constant Expressions: These are the expressions that have constant values only.
Example:
# Constant Expressions
x = 15 + 1.3
print(x)
Output
16.3

2. Arithmetic Expressions: An arithmetic expression is a combination of numeric values, operators,


and sometimes parenthesis. The result of this type of expression is also a numeric value. The
operators used in these expressions are arithmetic operators like addition, subtraction, etc.
x = 40
y = 12
add = x + y
sub = x - y
pro = x * y
div = x / y
print(add)
print(sub)
print(pro)
print(div)

26
Output
52
28
480
3.3333333333333335
3. Integral Expressions: These are the kind of expressions that produce only integer results after all
computations and type conversions.
Example:
# Integral Expressions
a = 13
b = 12.0
c = a + int(b)
print(c)
Output
25
4. Floating Expressions: These are the kind of expressions which produce floating point numbers as
result after all computations and type conversions.
Example:
# Floating Expressions
a = 13
b=5
c=a/b
print(c)
Output
2.6

Multiple operators in expression (Operator Precedence)


Operator Precedence simply defines the priority of operators that which operator is to be executed
first.
a = 10 + 3 * 4
print(a)
b = (10 + 3) * 4
print(b)
c = 10 + (3 * 4)
print(c)

27
Output
22
52
22

Statement in Python
A Python statement is an instruction that the Python interpreter can execute. There are different types
of statements in Python language as Assignment statements, Conditional statements, Looping
statements, etc. The token character NEWLINE is used to end a statement in Python. It signifies that
each line of a Python script contains a statement. These all help the user to get the required output.

Types of statements in Python


The different types of Python statements are listed below:
Multi-Line Statements
Python Conditional and Loop Statements
 Python If-else
 Python for loop
 Python while loop
 Python try-except
 Python with statement
Python Expression statements
 Python pass statement
 Python del statement
 Python return statement
 Python import statement
 Python continue and
 Python break statement
Statement in Python can be extended to one or more lines using parentheses (), braces {}, square
brackets [], semi-colon (;), and continuation character slash (\). When the programmer needs to do
long calculations and cannot fit his statements into one line, one can make use of these characters.

Declared using Continuation Character (\):


s=1+2+3+\
4+5+6+\
7+8+9

28
Declared using parentheses () :
n = (1 * 2 * 3 + 7 + 8 + 9)

Declared using square brackets [] :


footballer = ['MESSI',
'NEYMAR',
'SUAREZ']

Declared using braces {} :


x = {1 + 2 + 3 + 4 + 5 + 6 +
7 + 8 + 9}

Declared using semicolons(;) :


flag = 2; ropes = 3; pole = 4

Boolean expressions
A boolean expression is an expression that is either true or false. The following examples use the
operator ==, which compares two operands and produces True if they are equal and False otherwise:
Example
print(5 == 6)
print("Is five equal 5 to the result of 3 + 2?")
print(5 == (3 + 2))
print("Does five equal six?")
print(5 == 6)
The == operator is one of six common comparison operators which all produce a bool result.
x == y # Produce True if ... x is equal to y
x != y # ... x is not equal to y
x>y # ... x is greater than y
x<y # ... x is less than y
x >= y # ... x is greater than or equal to y
x <= y # ... x is less than or equal to y
bool() Function: This built-in function can evaluate any value and return its Boolean equivalent.
Most values with content (non-empty strings, non-zero numbers, non-empty lists, tuples,
dictionaries, sets) evaluate to True.

29
Empty strings, the number 0, and empty collections evaluate to False.
Python
print(bool("Hello")) # True
print(bool(0)) # False
print(bool([])) # False
Usage of Boolean Expressions:
Boolean expressions are fundamental for controlling program flow, especially in:
Conditional statements (if, elif, else): To execute specific blocks of code based on whether a
condition is True or False.
Loops (while): To determine whether a loop should continue iterating.
Function returns: Functions can return True or False to indicate success, failure, or a specific state.

30

You might also like