0% found this document useful (0 votes)
9 views41 pages

Introduction To Python

This document provides a comprehensive guide on installing Python, using variables, and performing basic operations in Python. It covers topics such as flowcharting, data types, input/output functions, and various data structures like lists, tuples, dictionaries, and sets. Additionally, it explains how to use functions like max() and the importance of comments in code.

Uploaded by

Shivansh Verma
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)
9 views41 pages

Introduction To Python

This document provides a comprehensive guide on installing Python, using variables, and performing basic operations in Python. It covers topics such as flowcharting, data types, input/output functions, and various data structures like lists, tuples, dictionaries, and sets. Additionally, it explains how to use functions like max() and the importance of comments in code.

Uploaded by

Shivansh Verma
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

UNIT-2


 To install Python, visit [Link] and download the
appropriate installer for your operating system
(Windows, macOS, or Linux), then run the installer
and follow the on-screen instructions.
 Here's a more detailed breakdown:
 1. Download the Python Installer:
 Go to the official Python website.
 Select the installer for your operating system
(Windows, macOS, or Linux).
 Choose the latest stable version of Python 3.

 Run the Installer:
 Double-click the downloaded installer file.
 Follow the on-screen instructions to complete the installation.
 Important: During the installation process, consider adding Python
to your system's PATH environment variable. This allows you to
run Python commands from the command line or terminal.
 3. Verify the Installation:
 Open a command-line or terminal window.
 Type python --version or python3 --version.
 If Python is installed correctly, you should see the version number.
 You can also check if pip (Python's package installer) is installed by
typing pip --version or pip3 --version.



PYTHON SHELL

 Flow Chart Symbols

In the previous section of this chapter, we have learnt to
write algorithms, i.e. step-bystep process of solving a
problem. We can also show these steps in graphical form
by using some symbols. This is called flowcharting.
 Flowchart Symbols
 Some of the standard symbols along with respective
function(s) that are used for making flowchart are as
follows:

Variable

In Python, a variable is a name that refers to a value
stored in memory. You can think of a variable like a
labeled box that holds something — a number, text, list,
etc. — and you can access or change what's inside the
box later.
x=5
name = "Alice"
is_active = True

 x is a variable that holds the integer 5.
 name holds the string "Alice".
 is_active holds the boolean value True.
 Key points:
 You don't need to declare the type of a variable;
Python figures it out for you (this is called dynamic
typing).
 Variable names are case-sensitive (Name and name
are different).
 You can change what a variable refers to at any time.

 Naming rules:
 Must start with a letter or underscore (_)
 Can contain letters, digits, and underscores
 Cannot be a Python keyword like if, while, class, etc.
USING PYTHON AS A
CALCULATOR

 Python's interactive shell, also known as the REPL (Read-Eval-
Print Loop), serves as a powerful tool for performing
calculations directly from the command line. This feature allows
you to execute arithmetic operations and evaluate expressions
in real-time, making Python an effective calculator.
 Accessing the Python Interactive Shell:
 Open Terminal or Command Prompt:
 On Windows: Press Win + R, type cmd, and press Enter.
 Start the Python Shell:
 Type python or python3 (depending on your installation) and
press Enter.
 You should see the Python prompt >>>, indicating that the shell
is ready for input.
Performing
Calculations:

 Once in the Python shell, you can execute various arithmetic operations:
 Addition: >>> 7 + 3
 Output: 10
 Subtraction: >>> 10 - 4
 Output: 6
 Multiplication: >>> 5 * 6
 Output: 30
 Division: >>> 20 / 5
 Output: 4.0
 Exponentiation: >>> 2 ** 3
 Output: 8
 Modulus (remainder): >>> 10 % 3
 Output: 1
Using the Underscore
(_) for Previous Results:

 The Python shell stores the result of the last
executed expression in the underscore (_) variable:
 >>> 15 * 2
 30
 >>> _ + 10
 40
What is Syntax?

 In simplest words, Syntax is the arrangement of words
and phrases to create well-formed sentences in a language.
In the case of a computer language, the syntax is the
structural arrangement of comments, variables,
numbers, operators, statements, loops, functions,
classes, objects, etc. which helps us understand the
meaning or semantics of a computer language.
Input/output function
in python

 Print Function:
 In Python, the print() function is a fundamental tool
used to display output to the console or other
standard output devices. It can handle various data
types, including strings, numbers, lists, and more,
converting them to strings before printing.
 Basic Usage: To print a simple message or value,
pass it as an argument to the print() function:
 print("Hello, World!")

 Printing Multiple Items: You can print multiple items by separating them with
commas. By default, print() separates these items with a space:
 name = "Alice"
 age = 30
 print("Name:", name, "Age:", age)
 Output:Name: Alice Age: 30
 Customizing Separators: To change the default space separator, use the sep
parameter:
 print("apple", "banana", "cherry", sep=", ")
 Output:
 apple, banana, cherry
 Suppressing Newlines: By default, print() ends with a newline character. To prevent
this and continue printing on the same line, use the end parameter:
 print("Hello", end=" ")
 print("World!")
 Output:
 Hello World!
INPUT FUNCTION

 In Python, the input() function is used to capture user
input from the console. When called, it pauses
program execution and waits for the user to type
something, returning the entered data as a string.
 Basic Usage:
 user_input = input("Enter something: ")
 print("You entered:", user_input)
 //In this example, the prompt "Enter something: " is
displayed, and whatever the user types is stored in
the variable user_input and then printed.
Converting Input to
Other Data Types:

 Since input() returns a string, you may need to convert it
to other data types:
 # For integer input
 age = int(input("Enter your age: "))
 print("Next year, you will be", age + 1)

 # For float input


 height = float(input("Enter your height in meters: "))
 print("Your height is", height, "meters")
 //In these examples, the input is converted to int and float
respectively to perform numerical operations.
COMMENTS

Comments are notes in the code that Python ignores
during execution. They’re used to explain code, make it
readable, or temporarily disable code.
 1. Single-line Comments
 Use the # symbol at the beginning of a line.
# This is a single-line comment
x = 10 # This is an inline comment

 2. Multi-line Comments
 Python doesn’t have a specific multi-line comment
feature like some other languages, but you can use
multiple # lines:
# This is a multi-line
# comment using several
# single-line comment symbols.

 3. Multi-line String Trick (Not Recommended as a
Comment)
 You can use triple quotes (''' or """) to write block
comments, but this is actually a string that is not assigned
— Python ignores it, but it's not officially a comment.
'''
This is a block of text
used like a comment,
but it's technically a string.
'''
Literal in Python

 In Python, a literal is a notation for representing a fixed value
directly within the source code. These are constant values that
remain unchanged during the execution of a program. Literals can
be numbers, strings, booleans, or other data types.
 Types of Literals in Python:
 Numeric Literals:
 Integer Literals: Whole numbers without a fractional component, e.g.,
10, -3.
 Floating-Point Literals: Numbers with a decimal point or in
exponential form, e.g., 3.14, 2e5.
 String Literals:
 Single-Line Strings: Text enclosed within single ('...') or double ("...")
quotes, e.g., 'Hello', "World".
 Multi-Line Strings: Text spanning multiple lines, enclosed within
triple quotes ('''...''' or """..."""), e.g., '''This is a multi-line string'''.

 Boolean Literals:
 Represent truth values: True and False.
 Special Literal:
 None: Represents the absence of a value or a null value.
 Collection Literals:
 List Literals: Ordered collection of items, e.g., [1, 2, 3].
 Tuple Literals: Immutable ordered collection of items,
e.g., (1, 2, 3).
 Dictionary Literals: Collection of key-value pairs, e.g.,
{'a': 1, 'b': 2}.
 Set Literals: Unordered collection of unique items, e.g.,
{1, 2, 3}.
List in Python

 In Python, a list is a built-in data structure that’s an ordered, mutable
(changeable) collection of items. Lists can hold elements of different data
types — like integers, strings, floats, even other lists — all in one place.
 Here’s how to create a list:
# A list of different data types
my_list = [1, "hello", 3.14, True]
print(my_list) # Output: [1, 'hello', 3.14, True]
 Some common list operations:
 Accessing elements:
print(my_list[0]) # First element: 1
print(my_list[-1]) # Last element: True
Slicing:
print(my_list[1:3]) # ['hello', 3.14]
Modifying elements:

my_list[1] = "world"
print(my_list) # [1, 'world', 3.14, True]
Adding elements:
my_list.append(42) # Add to the end
print(my_list)

my_list.insert(1, "new") # Insert at index 1


print(my_list)
Sorting and reversing:
numbers = [4, 2, 9, 1]
[Link]() # Sorts in ascending order
print(numbers)

[Link]() # Reverses the list


print(numbers)

Checking length:
print(len(my_list)) # Number of items in list
Removing elements:
my_list.remove(3.14) # Removes first occurrence of
3.14
print(my_list)
Tuple

 In Python, a tuple is an immutable, ordered collection of items.
Tuples are similar to lists, but once you create a tuple, you can’t
change its contents — meaning you can’t add, remove, or
modify elements. This immutability makes tuples faster and
safer for data that shouldn’t change.
 Here’s how to create and work with tuples:
 Creating a tuple:
 # Tuple with elements
 fruits = ('apple', 'banana', 'cherry')

 # Tuple without parentheses (using commas)


 numbers = 1, 2, 3

Accessing elements:
print(fruits[0]) # 'apple'
print(fruits[-1]) # 'cherry'
Slicing tuples:
print(fruits[1:3]) # ('banana', 'cherry')
Tuple methods:
numbers = (1, 2, 3, 2, 4, 2)
print([Link](2)) # 3 (how many times 2
appears)
Dictionary in Python

In Python, a dictionary is a built-in data type that stores key-
value pairs. It's defined using curly braces {} and allows for fast
lookups, insertions, and deletions.
Creating a Dictionary
# Empty dictionary
my_dict = {}

# Dictionary with initial values


person = {
"name": "Alice",
"age": 25,
"city": "New York"
}

Accessing Values
print(person["name"]) # Output: Alice

If the key is not found, it raises a KeyError. To avoid this, use .get():
print([Link]("name"))

Adding and Updating Values


person["job"] = "Engineer" # Adding a new key-value pair
person["age"] = 26 # Updating an existing key

Removing Items
del person["city"] # Removes 'city' key

 Update function
 [Link]({"country": "USA", "age": 27})

 Nested Dictionary
 students = {
 "Alice": {"age": 25, "grade": "A"},
 "Bob": {"age": 24, "grade": "B"}
}

 print(students["Alice"]["grade"]) # Output: A
MAX FUNCTION

 The max() function in Python is used to find the largest
item in an iterable (like a list, tuple, or dictionary) or the
largest of multiple arguments.
 1. Basic Usage with Numbers
 print(max(3, 7, 2, 9, 5)) # Output: 9

 2. Using max() with Lists


 numbers = [10, 45, 78, 34, 89]
 print(max(numbers)) # Output: 89
 3. Using max() with Strings
 print(max("apple", "banana", "cherry")) # Output: cherry
(alphabetically last)

 4. Using max() with a Key Function
 You can use the key parameter to customize how the maximum
value is determined.
 Find the longest word
 words = ["cat", "elephant", "tiger", "mouse"]
 longest_word = max(words, key=len)
 print(longest_word) # Output: elephant
 [Link] the maximum value in a dictionary
 students = {"Alice": 85, "Bob": 92, "Charlie": 88}
 top_student = max(students, key=[Link]) # Finds the key
with max value
 print(top_student) # Output: Bob
Set in Python

 Set in Python
 A set is an unordered, mutable collection of unique elements in Python. It
is defined using curly braces {} or the set() function.
Creating a Set
# Using curly braces
my_set = {1, 2, 3, 4, 5}
print(my_set) # Output: {1, 2, 3, 4, 5}

# Using the set() function


another_set = set([3, 4, 5, 6, 7])
print(another_set) # Output: {3, 4, 5, 6, 7}

# Creating an empty set (Note: {} creates a dictionary, not a set)


empty_set = set()
print(empty_set) # Output: set()

 Set Properties
 Unordered: The elements have no fixed position.
 Unique Elements: Duplicates are automatically
removed.
 Mutable: You can add or remove elements.
example_set = {1, 2, 2, 3, 4, 4, 5}
print(example_set) # Output: {1, 2, 3, 4, 5} (duplicates
removed)

 Set Operations
 1. Adding Elements
 my_set = {1, 2, 3}
 my_set.add(4)
 print(my_set) # Output: {1, 2, 3, 4}

 2. Removing Elements
 my_set.remove(2)
 print(my_set) # Output: {1, 3, 4}

 3. Checking Membership
 print(3 in A) # Output: True
 print(10 in A) # Output: False

 Examples:
 Integer Literal: age = 25
 Floating-Point Literal: pi = 3.14159
 String Literal: greeting = "Hello, World!"
 Boolean Literal: is_active = True
 None Literal: data = None
 List Literal: fruits = ['apple', 'banana', 'cherry']
 Tuple Literal: coordinates = (10, 20)
 Dictionary Literal: student = {'name': 'Alice', 'age': 21}
 Set Literal: unique_numbers = {1, 2, 3}
Strings in Python

 In Python, a string is a sequence of characters enclosed in
quotes. Strings are one of the most commonly used data
types, and Python makes working with them easy and
flexible.
 # Using single or double quotes
 string1 = 'Hello'
 string2 = "World"

 # Using triple quotes for multiline strings


 multiline_string = '''This is
 a multiline
 string.'''
 Accessing Characters:

 text = "Python"
 print(text[0]) # 'P' (Indexing starts at 0)
 print(text[-1]) # 'n' (Negative index for last character)
 Slicing Strings:
 print(text[0:3]) # 'Pyt' (Characters from index 0 to 2)
 print(text[3:]) # 'hon' (From index 3 to end)
 print(text[:4]) # 'Pyth' (From start to index 3)
 String Methods:
 text = " hello world "
 print([Link]()) # ' HELLO WORLD '
 print([Link]()) # ' hello world '
 print([Link]()) # 'hello world' (Removes spaces at start/end)
 print([Link]('world', 'Python')) # ' hello Python '
 print([Link]()) # ['hello', 'world']

String Formatting:
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
# f-string (Python 3.6+)
Checking Substrings:
text = "Python is fun"
print('Python' in text) # True
print('Java' not in text) # True

You might also like