Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
42 views

Python For Beginners

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

Python For Beginners

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

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

Unit-1 Getting Started (4-7 pages)


Introduction; What is Python?: features; Installation and Set-up;
Writing your first Python program; Know your Understanding.
Unit-2 Python Basics (8-19 pages)
Introduction; Writing a comment for Program code; Variables: Rules for
Declaring a Variable; Displaying Output on the screen; Reading Input from
the User; Data types; Arithmetic Operations, Comparison Operations, Logical
Operations, Bitwise Operations, Assignment Operations; String Manipulation
Techniques.

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!”)

Save the file with a `.py` extension, for example, `first_program.py`.


This extension tells the system that the file contains Python code.
Run Your Program: Open a command prompt or terminal, navigate to the
directory where you saved your Python file, and type the following command:
Python first_program.py

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-

Know your Understanding

Multiple Choice questions


1. Who is the creator of Python?
a) Guido van Rossum
b) Larry Page
c) Mark Zuckerberg
d) Bill Gates
2. When was Python first released?
a) 1989
b) 1991
c) 2000
d) 2010

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:

1.a 2. b 3.c 4.b 5.a. 6.a 7.False 8.False

Note: Each question carries 1 point.


SCORE INTERPRETER
8 points – Excellent
7-5 points – Good
4 points – Average
1-3 points – Try again (please go through the text again).

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

Make sure to use comments judiciously to improve the readability and


maintainability of your Python code.
Variables
Variables are containers for storing data values in a program. They have
a name and a value. Variables in Python do not need explicit declaration to
reserve memory space. The declaration happens automatically when a value
is assigned to a variable.
Since Python is dynamically typed, that means you don’t need to declare
the data type of a variable. The interpreter automatically determines the type
based on the value assigned to it.

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

Examples of invalid variable declarations:


#invalid variables names
If = 10 # Invalid, ‘if’ is a keyword
My$var = 20 # Invalid, contains special character ‘$’
My-variable = 5 # Invalid, contains hyphen
My variable = “Hello” # Invalid, contains space
1variable = 10 # Invalid, starts with a digit
_1st_place = “Gold” # Invalid, starts with underscore
followed by digit
Str = “Hello” # Invalid variable name, ‘str’ is a built-
in function

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:

Print(“Hello, world!”) #this will print “Hello, Champ!” to the Screen.


X=5
Print(“The value of x is:”, x) #This will print “The value of x is: 5”.

Reading Input from the User


To read input from the user in Python, you can use the input() function.
Here’s how you can do it:
Name = input(“Enter your name: “)
Print(“Hello, “ + name + “!”) #This will prompt the user to
enter their name, and then it will print “Hello, “ followed by
the name they entered.

Age = int(input(“Enter your age: “))


Print(“You are”, age, “years old.”) #This will prompt the
user to enter their age, convert the input to an integer, and
then print their age.

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

# Greater than or equal to


Print(“x >= y:”, x >= y) # Output: x >= y: False

# Less than or equal to


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

These logical operations evaluate expressions and return Boolean


values (True or False) based on the truthiness of the operands.
Bitwise Operations
Bitwise operations are operations that directly manipulate bits, which
are the smallest units of data in a computer. In Python, bitwise operations work
on integers at the binary level. Here are the common bitwise operations:
• Bitwise AND (&): Sets each bit to 1 if both bits are 1.
• Bitwise OR (|): Sets each bit to 1 if either of the corresponding bits is
1.
• Bitwise XOR (^): Sets each bit to 1 if only one of the corresponding bits
is 1.
• Bitwise NOT (~): Inverts all the bits.
• Left Shift (<<): Shifts the bits to the left by a certain number of
positions, filling the empty bits with zeros.
• Right Shift (>>): Shifts the bits to the right by a certain number of
positions, discarding the bits shifted off.
# Bitwise AND
A = 0b1010 # Binary representation of 10
B = 0b1100 # Binary representation of 12
result_and = a & b
Print(“Bitwise AND:”, bin(result_and)) # Output: 0b1000
# Bitwise OR
result_or = a | b
Print(“Bitwise OR:”, bin(result_or)) # Output: 0b1110
# Bitwise XOR
result_xor = a ^ b
Print(“Bitwise XOR:”, bin(result_xor)) # Output: 0b0110

# 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

# Add and Assign


x += 5
Print(“x (Add and Assign):”, x) # Output: 15

# Subtract and Assign


x -= 3
Print(“x (Subtract and Assign):”, x) # Output: 12

# Multiply and Assign


x *= 2
Print(“x (Multiply and Assign):”, x) # Output: 24

# Divide and Assign


x /= 4
Print(“x (Divide and Assign):”, x) # Output: 6.0

# Modulo and Assign


x %= 5
Print(“x (Modulo and Assign):”, x) # Output: 1.0

# Floor Divide and Assign


x //= 3
Print(“x (Floor Divide and Assign):”, x) # Output: 0.0

# Exponentiate and Assign


x **= 3
Print(“x (Exponentiate and Assign):”, x) # Output: 0.0

These all are the basic operations in Python Programming.


String Manipulations
String manipulation in Python involves various operations to modify,
concatenate, format, and extract information from strings. Here are some
common string manipulation operations:
1. Concatenation: Combining two or more strings together using the `+`
operator.
Ex:
Str1 = “Hello”
Str2 = “Champ”
Result = str1 + “ “ + str2
Print(result) # Output: Hello Champ

16
2. Substring: Extracting part of a string.
Ex:
text = “Hello World”
sub = text[6:]
print(sub) # Output: World

3. Splitting: Breaking a string into a list of substrings based on a specified


delimiter using the split() method.
Ex:
sentence = “This is a sentence.”
words = sentence.split()
print(words) # Output: [‘This’, ‘is’, ‘a’, ‘sentence.’]

4. Joining: Combining a list of strings into a single string using a specified


delimiter with the join() method.
Ex:
words = [‘This’, ‘is’, ‘a’, ‘sentence.’]
sentence = ‘ ‘.join(words)
print(sentence) # Output: This is a sentence.

5. Replacing: Substituting occurrences of a substring within a string using


the replace() method.
Ex:
text = “I like apples.”
new_text = text.replace(“apples”, “bananas”)
print(new_text) # Output: I like bananas.

6. Formatting: Creating formatted strings using placeholders {} or format


specifiers within strings and using the format() method.
Ex:
name = “Alice”
age = 30
message = “My name is {} and I am {} years old.”.format(name, age)
print(message) # Output: My name is Alice and I am 30 years old.

7. Stripping: Removing leading and trailing whitespace characters from


a string using the strip() method.
Ex:
text = “ Some text with spaces “
stripped_text = text.strip()
Print(stripped_text) # Output: Some text with spaces

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-

Know your Understanding

Multiple Choice Questions


1. What is the purpose of writing comments in Python code?
a) To execute code
b) To make the code run faster
c) To document and explain code
d) To declare variables
2. Which of the following is NOT a valid variable name in Python?
a) My_variable
b) 123variable
c) variable123
d) _variable
3. How do you read input from the user in Python?
a) Input()
b) get_input()
c) read_input()
d) print()
4. What function is used to display output on the screen in Python?
a) print_output()
b) show()
c) display()
d) print()
5. Which of the following is not a data type in Python?
a) integer
b) string
c) float
d) character
6. Which Operator is used for exponentiation in Python?
a) **
b) ^
c) %
d) //
7. What operation is performed by the + operator when used with strings
in Python?
a) Concatenation
b) Subtraction

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

Note: Each question carries 1 point.

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

You might also like