Python For Beginners
Python For Beginners
By
Arun Kumar Pasunoori
1
©All Rights Reserved.
No part of this publication may be reproduced, distributed, or transmitted in
any form or by any means, including photocopying, recording, or other
electronic or mechanical methods without the prior written permission of the
publisher.
ACKNOWLEDGEMENT
I would like to acknowledge the unknown photographer(s) whose work
contributed to this project. I ‘am grateful for their creative contribution and
apologize for any oversight in not being able to credit them individually.
22nd March, 2024 Arun Kumar. P
2
CONTENTS
3
Unit -1 Getting Started
Introduction
In this course, I will explain how Python was evolved and its
significance in the present-day world. Apart from many other programming
languages, Python stands out due to its simplicity in writing program codes.
Syntaxes are simple and easy to use when required.
Python is used for wide range of applications that include Web
Development, Machine learning and Artificial Intelligence, Software
Development, Audio or Video Based Applications etc.
It’s advantages include reduction of maintenance cost, avoids the harm
of software bugs, easy memory management, large community, asynchronous
coding, wide applicability.
What is Python?
Python is an Object Oriented, High Level,
Interpreted, Scripting Language.
It was developed by Guido Van Rossum, a Dutch
programmer in the late 1980’s at Centrum Wiskunde &
Informatica (CWI) in the Netherlands as a successor to
ABC programming language and first released in 1991 for
public distribution.
Features
• Simple and Readable Syntax: Python emphasizes readability and
simplicity, making it easy to learn and understand.
• High-level Language: Python abstracts many complex programming
tasks, allowing developers to focus on solving problems rather than
dealing with low-level details.
• Interpreted and Interactive: Python code is executed line by line,
making it suitable for rapid prototyping and debugging. It also supports
an interactive mode where code can be executed and tested
interactively.
4
• Multiparadigm: Python supports multiple programming paradigms,
including procedural, object-oriented, and functional programming,
allowing developers to choose the most suitable approach for their
projects.
• Dynamic Typing: Python uses dynamic typing, meaning variable types
are inferred at runtime, providing flexibility and reducing the need for
explicit type declarations.
• Extensive Standard Library: Python comes with a large standard
library that provides modules and functions for various tasks, such as
file I/O, networking, database access, and more, facilitating rapid
development without the need for external dependencies.
• Cross-platform Compatibility: Python code can run on various
platforms, including Windows, macOS, Linux, and more, ensuring
portability and interoperability.
• Community and Ecosystem: Python has a vibrant and active
community that contributes to its ecosystem by developing libraries,
frameworks, and tools for different domains, enhancing its functionality
and versatility.
These features collectively make Python a powerful and flexible
programming language suitable for a wide range of applications and
industries.
Installation and Set-up
Download Python: Visit the official Python website at
https://www.python.org/downloads/ and download the latest version of
Python for your operating system (Windows, macOS, or Linux).
Run the Installer: Once the installer is downloaded, run it and
follow the installation wizard’s instructions. Make sure to check the box
that says “Add Python to PATH” during the installation process. This will
allow you to run Python from any command prompt or terminal window.
Verify Installation: After installation, open a command prompt or
terminal and type `python –version` to verify that Python has been installed
correctly. You should see the version number of Python printed to the
screen.
That’s it! Python should now be installed on your system and ready
to use. You can start writing and running Python code in your favourite text
editor or integrated development environment (IDE).
5
Writing your first Python program
Now you are going to write your first Python program. Open your
chosen text editor and create a new file. In the text editor, write your Python
code. For your first program, let’s keep it simple. Here’s an example of a basic
“Hello, Champ!” program:
print(“Hello, Champ!”)
This command tells the Python interpreter to execute the code in your
`first_program.py` file.
See the Output: After running the command, you should see the output
“Hello, Champ!” printed to the console.
Congratulations! You’ve written and executed your first Python program.
From here, you can continue learning Python by exploring different concepts,
writing more complex programs, and working on projects that interest you.
-o-
6
3. Name one key feature of Python.
a) Static typing
b) Low-level language
c) Dynamic typing
d) Limited standard library
4. Which website is the official source for downloading Python?
a) python.com
b) python.org
c) python.net
d) python.io
5. What is the command to check the installed Python version in the
command prompt or terminal?
a) python –version
b) version python
c) python -v
d) python –info
6. What is the output of the following Python code?
Print(“Hello, Programmer!”)
a) Hello, Programmer!
b) “Hello, Programmer!”
c) Hello Programmer
d) Syntax error
7. Python is a statically typed language. (True/ False)
8. Python has a limited standard library. (True/ False)
Key:
7
Unit – 2 Python Basics
Introduction
In this unit I’m going to cover Basics of Python that includes Writing
Comments, Variables, Data types such as Integers, Floats, Booleans and
Strings etc. Reading input from the user and displaying output on the screen.
Basic Arithmetic operations and String manipulation techniques. And also
have handful work on these topics.
Writing a Comment for Program Code
Comments are written in Python for explaining the program code.
Comments helps us to understand the program code better. Comments are
ignored by the Python interpreter while debugging the program code.
Here’s how you write comments in Python:
# This is a single-line comment
X = 10 # This is also a single-line comment
“““
This is a multi-line comment.
You can write multiple lines of comments within triple
quotes.
”””
X = 20 # This line of code is not part of the comment
block
8
Rules for declaring a variable
• Variable names can contain letters (a-z, A-Z), digits (0-9), and
underscores (_).
• They cannot start with a digit.
• Variable names are case-sensitive,
For example `myVar` and `myvar` are considered as different
variables, because the ASCII values of V and v are different.
• It’s recommended to use descriptive names to make your code
more readable.
• Variable names cannot be the same as Python keywords or
reserved words like `if`, `else`, `for`, `while`,
`import`, `def`, etc.
• Special characters such as !, @, #, $, %, etc., cannot be used in
variable names.
• Python conventionally uses snake_case for variable names,
where words are separated by underscores.
For example:`my_variable`, `user_age`, `total_amount`.
Examples of valid variable declarations:
#valid variable names
Age = 25 #integer
Name = “Shiva” #string
User_age = 30 #integer
_my_variable = “Hello”
Salary = 2500.50 # Float
Myvar = True #boolean
9
Displaying Output on the Screen
In Python, We use the ‘print()’ function to display output on the
Screen.
Here’s how you can do it:
Data Types
In Python, there are several
built-in data types that are commonly
used to represent different types of
data that a variable can hold.
Understanding data types is essential
for effectively storing, manipulating,
and working with data in Python
programs.
We need to keep in mind that
Python is a dynamically typed
language in which we no need to
specify the type of the data that a
variable can hold.
Here is a rough outline of different types of data that we come across in
Python programming.
10
• Integer (int): Represents whole numbers, both positive and negative,
without any decimal point.
Examples: 10, -5, 1000, 0.
Python automatically assigns the data type int to whole numbers.
• Float (float): Represents floating-point numbers, which are numbers
that have a decimal point or use exponential notation.
Examples: 3.14, -0.001, 2.5e-3.
Python automatically assigns the data type float to numbers with
decimal points or in exponential notation.
• Boolean (bool): Represents a Boolean value, which can be either True
or False.
Examples: True, False.
Booleans are commonly used for logical operations, comparisons, and
control flow in Python.
• String (str): Represents a sequence of characters enclosed within single
quotes (‘’), double quotes (“”), or triple quotes (‘‘‘ ’’’ or “““ ”””).
Examples: ‘Hello’, “Python”, ‘‘‘Multi-line string’’’.
Strings can contain letters, digits, special characters, and whitespace.
Python treats single quotes and double quotes interchangeably for
defining strings.
• List (list): Represents an ordered collection of items, which can be of
different data types.
Enclosed within square brackets [] and items are separated by commas.
Lists are mutable, meaning they can be modified after creation.
Example: [1, 2, ‘apple’, True].
• Tuple (tuple): Similar to lists, tuples represent an ordered collection of
items. However, tuples are immutable, meaning they cannot be
modified after creation.
Enclosed within parentheses () and items are separated by commas.
Example: (10, ‘banana’, 3.14).
• Dictionary (dict): Represents a collection of key-value pairs, where
each key is associated with a value.
Enclosed within curly braces {} and key-value pairs are separated by
commas, with keys and values separated by colons :.
Dictionaries are unordered and mutable.
Example: {‘name’: ‘Alice’, ‘age’: 30, ‘city’: ‘New York’}.
• Set (set): Represents an unordered collection of unique items.
Enclosed within curly braces {} and items are separated by commas.
Sets automatically remove duplicate elements.
Example: {1, 2, 3, ‘apple’}.
We will study all these data types in detail in the upcoming chapters.
11
How to know the different Data Types in Python?
In Python programming we have an inbuilt function ‘type()’ to find
the data type of a Variable declared.
Here are some of the examples demonstrating the same.
X = 5
Print(type(x)) # Output: <class ‘int’>
Y = “Hello”
Print(type(y)) # Output: <class ‘str’>
Z = [1, 2, 3]
Print(type(z)) # Output: <class ‘list’>
X = True
Print(type(x)) # Output: <class ‘bool’>
This will print the data type of the variable x, y, and z respectively.
Arithmetic Operations
In Python, you can perform various arithmetic operations using opera-
tors like `+`, `-`, `*`, `/`, `%`, and `**`. Here are some examples:
# Addition
Result = 5 + 3
Print(“5 + 3 =”, result) # Output: 5 + 3 = 8
# Subtraction
Result = 7 – 2
Print(“7 – 2 =”, result) # Output: 7 – 2 = 5
# Multiplication
Result = 4 * 6
Print(“4 * 6 =”, result) # Output: 4 * 6 = 24
# Division
Result = 10 / 2
Print(“10 / 2 =”, result) # Output: 10 / 2 = 5.0
# Modulus (Remainder)
Result = 17 % 5
Print(“17 % 5 =”, result) # Output: 17 % 5 = 2
# Exponentiation
Result = 2 ** 3
Print(“2 ** 3 =”, result) # Output: 2 ** 3 = 8
12
Comparison Operations
In Python, comparison operations are used to compare values and
determine the relationship between them. Here are the comparison operators
in Python:
Equal to: ==
Not equal to: !=
Greater than: >
Less than: <
Greater than or equal to: >=
Less than or equal to: <=
Here are examples for each:
X = 5
Y = 10
# Equal to
Print(“x == y:”, x == y) # Output: x == y: False
# Not equal to
Print(“x != y:”, x != y) # Output: x != y: True
# Greater than
Print(“x > y:”, x > y) # Output: x > y: False
# Less than
Print(“x < y:”, x < y) # Output: x < y: True
# Less than
Print(“x < y:", x < y) # Output: x < y: True
These comparison operators return boolean values (True or False) based on
the result of the than
# Greater comparison.
or equal to
print("x >= y:", x >= y) # Output: x >= y: False
Logical Operations
# Less than or equal to
In Python, logical operations are used to perform operations on boolean
print("x <= y:", x <= y) # Output: x <= y: True
values. Here are the logical operators in Python:
Logical AND: and
Logical OR: or
Logical NOT: not
Here are examples for each of them:
13
# AND
result_and = True and False
Print(“AND result:”, result_and) # Output: False
# OR
result_or = True or False
Print(“OR result:”, result_or) # Output: True
# NOT
result_not = not True
Print(“NOT result:”, result_not) # Output: False
# Bitwise NOT
Result_not_a = ~a
14
Print(“Bitwise NOT of a:”, bin(result_not_a)) # Output: -
0b1011 (two’s complement)
# Bitwise NOT
result_not_a = ~a
Print(“Bitwise NOT of a:”, bin(result_not_a)) # Output: -0b1011
(two’s complement)
# Left Shift
shifted_left = a << 2
Print(“Left Shift:”, bin(shifted_left)) # Output: 0b101000
(shifts 2 bits to the left)
# Right Shift
shifted_right = b >> 1
Print(“Right Shift:”, bin(shifted_right)) # Output: 0b110
(shifts 1 bit to the right)
These operations can be useful for various tasks such as optimizing
code, manipulating binary data, and implementing algorithms that work at the
bit level.
Assignment Operations
Assignment operations in Python are used to assign values to variables
while performing an operation simultaneously. They are shorthand notations
to make code more concise. Here are the common assignment operations:
• Assign (=): Assigns the value on the right to the variable on the left.
• Add and Assign (+=): Adds the value on the right to the variable’s
current value.
• Subtract and Assign (-=): Subtracts the value on the right from the
variable’s current value.
• Multiply and Assign (*=): Multiplies the variable’s current value by the
value on the right.
• Divide and Assign (/=): Divides the variable’s current value by the value
on the right.
• Modulo and Assign (%=): Computes the remainder of dividing the
variable’s current value by the value on the right and assigns the result.
• Floor Divide and Assign (//=): Performs floor division on the variable’s
current value by the value on the right and assigns the result.
• Exponentiate and Assign (**=): Raises the variable’s current value to
the power of the value on the right and assigns the result.
These assignment operations can help in writing concise and readable code
while performing arithmetic operations on variables.
Here’s the examples for each of the operator
15
# Assign
X = 10
Print(“x (Assign):”, x) # Output: 10
16
2. Substring: Extracting part of a string.
Ex:
text = “Hello World”
sub = text[6:]
print(sub) # Output: World
17
These operations are fundamental for text processing, data cleaning, and
many other tasks in Python programming. Python’s string manipulation
capabilities make it a versatile language for working with textual data.
-o-
18
c) Multiplication
d) Division
8. How do you split a string into a list of substrings in Python?
a) split()
b) split_string()
c) break_string()
d) spring_split
9. Which method is used to convert a string to uppercase in Python?
a) to_upper()
b) uppercase()
c) upper()
d) convert_to_upper()
10. What method is used to replace occurrences of a substring within
a string in Python?
a) replace()
b) substitute()
c) swap()
d) update()
Key
1.c 2.b 3.a 4.d 5.d 6.a 7.a 8.a 9.c 10.a
SCORE INTERPRETER
10 points – Excellent
9-7 points – Good
6-5 points – Average
1-4 points – Try again (please go through the text again).
19