Docsity

Python Programming handbook-Complete Beginner guide| B-tech Notes(81 pages), Study notes of Programming Languages

Toggle sidebar
bg1
Introduction to Python and
Programming
What is Programming?
Programming is the process of giving instructions to a computer to perform
specific tasks. It involves writing code in a programming language that the
computer can understand and execute.
Why Python?
Python is a high-level, interpreted programming language known for its
simplicity and readability.
It is widely used in:
Web Development (Django, Flask)
Data Science and Machine Learning (Pandas, NumPy, TensorFlow)
Automation and Scripting
Game Development (Pygame)
Python has a large community and extensive libraries, making it
beginner-friendly.
Setting Up Python and IDEs
Installing Python
Download Python:
Visit the official Python website: python.org.
1.
2.
3.
4.
5.
6.
7.
1.
1.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51

Partial preview of the text

Download Python Programming handbook-Complete Beginner guide| B-tech Notes(81 pages) and more Study notes Programming Languages in PDF only on Docsity!

Introduction to Python and

Programming

What is Programming?

Programming is the process of giving instructions to a computer to perform specific tasks. It involves writing code in a programming language that the computer can understand and execute.

Why Python?

Python is a high-level, interpreted programming language known for its simplicity and readability. It is widely used in: Web Development (Django, Flask) Data Science and Machine Learning (Pandas, NumPy, TensorFlow) Automation and Scripting Game Development (Pygame) Python has a large community and extensive libraries, making it beginner-friendly.

Setting Up Python and IDEs

Installing Python

Download Python:

Visit the official Python website: python.org.

Download the latest version for your operating system (Windows, macOS, or Linux).

Install Python:

Run the installer and ensure you check the box to Add Python to PATH (important for running Python from the command line).

Verify Installation:

Open a terminal or command prompt and type:

This should display the installed Python version (e.g., Python 3.13.5 ).

Choosing an IDE

What is an IDE? An Integrated Development Environment (IDE) is a software application that provides tools for writing, testing, and debugging code. Popular Python IDEs: VS Code: Lightweight, customizable, and supports extensions for Python. (We will use this one as our primary IDE) PyCharm: Powerful IDE with advanced features for professional developers. Jupyter Notebook: Great for data science and interactive coding. IDLE: Comes pre-installed with Python; good for beginners.

Writing Your First Python Program

The "Hello, World!" Program

Open a folder in your VS code and type the following code in a new file named hello.py :

python --version

Whitespace:

Python is sensitive to whitespace. Ensure consistent indentation to avoid errors. Ideally, use 4 spaces for indentation.

Statements:

Each line of code is a statement. You can write multiple statements on one line using a semicolon ( ; ), but this is not recommended.

Comments:

Use # for single-line comments. Use ''' or """ for multi-line comments. Example:

Notes from Instructor

Python is a versatile and beginner-friendly programming language. Setting up Python and choosing the right IDE is the first step to writing code. Python syntax is simple but requires attention to indentation and whitespace. Start with small programs like "Hello, World!" to get comfortable with the basics.

if 5 > 2: print("Five is greater than two!")

Spaces before print are called indentation

This is a single-line comment

''' This is a multi-line comment '''

Python Fundamentals

Variables and Data Types in Python

What are Variables?

Variables are used to store data that can be used and manipulated in a program.

A variable is created when you assign a value to it using the = operator.

Example:

Variable Naming Rules

Variable names can contain letters, numbers, and underscores. Variable names must start with a letter or underscore. Variable names are case-sensitive. Avoid using Python keywords as variable names (e.g., print , if , else ).

Best Practices

Use descriptive names that reflect the purpose of the variable. Use lowercase letters for variable names. Separate words using underscores for readability (e.g., first_name , total_amount ).

name = "Alice" age = 25 height = 5.

Examples:

Taking User Input in Python

Using the input() Function

The input() function allows you to take user input from the keyboard.

By default, input() returns a string. You can convert it to other data types as needed.

Example:

Convert string to integer

num_str = "10" num_int = int(num_str) print(num_int) # Output: 10

Convert integer to string

num = 25 num_str = str(num) print(num_str) # Output: "25"

Convert float to integer

pi = 3. pi_int = int(pi) print(pi_int) # Output: 3

name = input("Enter your name: ") age = int(input("Enter your age: ")) print(f"Hello {name}, you are {age} years old.")

Comments, Escape Sequences & Print Statement

Comments

Comments are used to explain code and are ignored by the Python interpreter.

Single-line comments start with #.

Multi-line comments are enclosed in ''' or """.

Escape Sequences

Escape sequences are used to include special characters in strings.

Common escape sequences:

\n : Newline \t : Tab \ : Backslash " : Double quote ' : Single quote

Example:

Print Statement

The print() function is used to display output.

This is a single-line comment

''' This is a multi-line comment '''

print("Hello\nWorld!") print("This is a tab\tcharacter.")

Assignment Operators:

= , += , -= , *= , /= , %= , **= , //=.

Example:

Membership Operators:

in , not in.

Example:

Identity Operators:

is , is not.

Example:

Summary

Variables store data, and Python supports multiple data types. Typecasting allows you to convert between data types. Use input() to take user input and print() to display output. Comments and escape sequences help make your code more readable. Python provides a variety of operators for performing operations on data.

x = 10 x += 5 # Equivalent to x = x + 5 print(x) # Output: 15

fruits = ["apple", "banana", "cherry"] print("banana" in fruits) # Output: True

x = 10 y = 10 print(x is y) # Output: True

Control Flow and Loops

If-Else Conditional Statements

What are Conditional Statements?

Conditional statements allow you to execute code based on certain conditions. Python uses if , elif , and else for decision-making.

Syntax:

Example:

if condition1:

Code to execute if condition1 is True

elif condition2:

Code to execute if condition2 is True

else:

Code to execute if all conditions are False

age = 18

if age < 18: print("You are a minor.") elif age == 18: print("You just became an adult!") else: print("You are an adult.")

Syntax:

Example:

Using range() :

The range() function generates a sequence of numbers.

Example:

While Loops in Python

What are While Loops?

While loops execute a block of code as long as a condition is True. They are useful when the number of iterations is not known in advance.

Syntax:

for item in sequence:

Code to execute for each item

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

for fruit in fruits: print(fruit)

for i in range(5): print(i) # Output: 0, 1, 2, 3, 4

while condition:

Code to execute while condition is True

Example:

Infinite Loops:

Be careful to avoid infinite loops by ensuring the condition eventually becomes False.

Example of an infinite loop:

Break, Continue, and Pass Statements

Break

The break statement is used to exit a loop prematurely.

Example:

Continue

The continue statement skips the rest of the code in the current iteration and moves to the next iteration.

count = 0

while count < 5: print(count) count += 1

while True: print("This will run forever!")

for i in range(10): if i == 5: break print(i) # Output: 0, 1, 2, 3, 4

Strings in Python

Introduction

Strings are one of the most fundamental data types in Python. A string is a sequence of characters enclosed within either single quotes ( ' ), double quotes

( " ), or triple quotes ( ''' or โ€œโ€œโ€œ).

Creating Strings

You can create strings in Python using different types of quotes:

String Indexing

Each character in a string has an index:

Single-quoted string

a = 'Hello, Python!'

Double-quoted string

b = "Hello, World!"

Triple-quoted string (useful for multi-line strings)

c = '''This is a multi-line string.'''

text = "Python" print(text[0]) # Output: P print(text[1]) # Output: y print(text[-1]) # Output: n (last character)

String Slicing

You can extract parts of a string using slicing:

String Methods

Python provides several built-in methods to manipulate strings:

String Formatting

Python offers multiple ways to format strings:

Multiline Strings

Triple quotes allow you to create multi-line strings:

text = "Hello, Python!" print(text[0:5]) # Output: Hello print(text[:5]) # Output: Hello print(text[7:]) # Output: Python! print(text[::2]) # Output: Hlo Pto!

text = " hello world " print(text.upper()) # Output: " HELLO WORLD " print(text.lower()) # Output: " hello world " print(text.strip()) # Output: "hello world" print(text.replace("world", "Python")) # Output: " hello Python " print(text.split()) # Output: ['hello', 'world']

name = "John" age = 25

Using format()

print("My name is {} and I am {} years old.".format(name, age))

Using f-strings (Python 3.6+)

print(f"My name is {name} and I am {age} years old.")

String Slicing

Slicing allows you to extract a portion of a string using the syntax string[start:stop:step].

Step Parameter

The step parameter defines the interval of slicing.

Practical Uses of Slicing

String slicing is useful in many scenarios: - Extracting substrings - Reversing strings

  • Removing characters - Manipulating text efficiently

Summary

Indexing allows accessing individual characters. Positive indexing starts from 0, negative indexing starts from -1. Slicing helps extract portions of a string. The step parameter defines the interval for selection.

text = "Hello, Python!" print(text[0:5]) # Output: Hello print(text[:5]) # Output: Hello (same as text[0:5]) print(text[7:]) # Output: Python! (from index 7 to end) print(text[::2]) # Output: Hlo Pto! print(text[-6:-1]) # Output: ython (negative indexing)

text = "Python Programming" print(text[::2]) # Output: Pto rgamn print(text[::-1]) # Output: gnimmargorP nohtyP (reverses string)

text = "Welcome to Python!" print(text[:7]) # Output: Welcome print(text[-7:]) # Output: Python! print(text[3:-3]) # Output: come to Pyt

Using [::-1] reverses a string.

String Methods and Functions

Introduction

Python provides a variety of built-in string methods and functions to manipulate

and process strings efficiently.

Common String Methods

Changing Case

Removing Whitespace

Finding and Replacing

Splitting and Joining

text = "hello world" print(text.upper()) # Output: "HELLO WORLD" print(text.lower()) # Output: "hello world" print(text.title()) # Output: "Hello World" print(text.capitalize()) # Output: "Hello world"

text = " hello world " print(text.strip()) # Output: "hello world" print(text.lstrip()) # Output: "hello world " print(text.rstrip()) # Output: " hello world"

text = "Python is fun" print(text.find("is")) # Output: 7 print(text.replace("fun", "awesome")) # Output: "Python is awesome"

text = "apple,banana,orange" fruits = text.split(",") print(fruits) # Output: ['apple', 'banana', 'orange']