0% found this document useful (0 votes)
14 views18 pages

Unit 1

Help full

Uploaded by

manu1202manu123
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)
14 views18 pages

Unit 1

Help full

Uploaded by

manu1202manu123
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/ 18

Introduction to Python

Python is a high-level, interpreted programming language that emphasizes readability and simplicity. Created by
Guido van Rossum and first released in 1991, Python has gained immense popularity due to its easy syntax and
broad range of applications.

Python's design philosophy focuses on code readability and the use of significant indentation. Unlike many
programming languages, Python doesn’t require curly braces or semicolons for structuring the code, making it
more intuitive for beginners.

Why Python?

Python is widely used in various fields, including web development, data science, artificial intelligence,
automation, and scientific computing. Some reasons for Python’s popularity include:

• Simple and Readable Syntax: The syntax is clear and readable, which makes it an excellent choice for
beginners.

• Vast Library Support: Python has an extensive standard library and a large ecosystem of third-party
libraries, which makes it easier to implement almost any functionality.

• Cross-Platform: Python is available on all major platforms (Windows, macOS, Linux), making it portable
and platform-independent.

• Open Source: Python is free to use and has a large and active community for support.
Features of Python

Simple and Easy


to Learn

Large GUI
Community Programming
Support Support

Cross-Platform Python Interpreted


Language Features Language

Extensive
Dynamically
Standard
Typed
Library
Open Source
and Free

• Simple and Easy to Learn: Python has a clean and straightforward syntax that resembles plain English.
This makes Python an ideal language for beginners. The simplicity helps developers focus more on solving
problems rather than on the language syntax.
• Interpreted Language: Python is an interpreted language, which means the code is executed line by line
by the interpreter. Unlike compiled languages (e.g., C, C++), you do not need to compile your code before
running it. This provides quick feedback and faster debugging.
• Dynamically Typed: Python does not require you to declare the type of a variable. It determines the type
at runtime, meaning you can assign different types of data to the same variable.

Example:

x = 5 # Integer
x = “Hello” # Now a string
• Extensive Standard Library: Python comes with a rich set of built-in libraries (known as the Python
Standard Library) that help you perform various tasks like file handling, regular expressions,
mathematical operations, web services, and much more.
• Cross-Platform Language: Python can run on various platforms such as Windows, macOS, Linux, etc.
You can write a Python program on one platform and execute it on another without any changes to the
code.
• Large Community Support: Python has a massive and active community that continuously contributes
to improving the language and creating third-party packages. This means ample tutorials, documentation,
and support are available for Python developers.
• Open Source and Free: Python is freely available for everyone to use and distribute, including for
commercial use. The Python interpreter and its source code are freely available for modification.
• GUI Programming Support: Python provides libraries like Tkinter, PyQt, and Kivy for building
Graphical User Interfaces (GUIs). These libraries allow the development of desktop applications with
Python.
Applications of Python

• Web Development: Python is widely used in web development, with popular frameworks like Django
and Flask. These frameworks simplify the development of dynamic websites and web applications.
• Data Science and Machine Learning: Python is a leading language in data science and machine learning,
thanks to libraries like NumPy, Pandas, Matplotlib, Scikit-learn, and TensorFlow.
• Automation (Scripting): Python is commonly used for automation tasks such as web scraping (using
BeautifulSoup, Selenium), file handling, and system automation.
• Game Development: Though not as common, Python can be used for game development using libraries
like Pygame.
• Artificial Intelligence (AI) and Robotics: Python is extensively used in AI, machine learning, deep
learning, and robotics. Libraries like TensorFlow and PyTorch provide powerful tools for implementing
AI models.
• Scientific Computing: Python is used in scientific computing fields such as astronomy, physics, and
engineering with libraries like SciPy, SymPy, and Matplotlib.
Python Variables
A variable is a name that refers to a memory location used to store data in a program. In Python, variables are
created when you assign a value to them, and they do not need explicit declaration. The type of the variable is
inferred based on the value assigned.

Example:

x = 5 # x is an integer
name = "John" # name is a string
pi = 3.14 # pi is a float

Variable Naming Rules

• Variable names must start with a letter (a-z, A-Z) or an underscore (_).

• The rest of the name can contain letters, numbers (0-9), and underscores.

• Variable names are case-sensitive (name and Name are different variables).

• Reserved keywords (such as if, else, for, etc.) cannot be used as variable names.

Example:

my_variable = 10 # Valid
MyVariable = "hello" # Valid (case-sensitive)
1variable = 10 # Invalid (cannot start with a number)

Assigning Values to Variables

Variables can be assigned values using the assignment operator (=).

Example:

x = 10 # Assign an integer to x
y = "Hello" # Assign a string to y
z = 3.14 # Assign a float to z

Multiple Assignment

Python allows assigning values to multiple variables in one line.

Example:

a, b, c = 5, "apple", 2.5 # a = 5, b = "apple", c = 2.5

Variable Types

Python is a dynamically typed language, meaning variables can change types during runtime.

Example:

x = 5 # x is an integer
x = "hello" # Now x is a string
Python Operators
Python supports several types of operators that allow you to perform different operations on variables.

a. Arithmetic Operators

These operators are used to perform mathematical operations like addition, subtraction, multiplication, and
division.

Operator Description Example

+ Addition a+b

- Subtraction a-b

* Multiplication a*b

/ Division a/b

// Floor Division a // b

% Modulus (remainder) a%b

** Exponentiation a ** b

Example:

a = 10
b = 3
print(a + b) # Output: 13
print(a - b) # Output: 7
print(a * b) # Output: 30
print(a / b) # Output: 3.33 (floating-point division)
print(a // b) # Output: 3 (integer division)
print(a % b) # Output: 1 (remainder)
print(a ** b) # Output: 1000 (10^3)
b. Comparison Operators

These operators compare two values and return a boolean (True or False).

Operator Description Example

== Equal to a == b

!= Not equal to a != b

> Greater than a>b

< Less than a<b

>= Greater than or equal to a >= b

<= Less than or equal to a <= b

Example:

a = 10
b = 5
print(a == b) # Output: False
print(a != b) # Output: True
print(a > b) # Output: True
print(a <= b) # Output: False

c. Logical Operators

Logical operators are used to combine conditional statements.

Operator Description Example

and Returns True if both conditions are true a and b

or Returns True if at least one condition is true a or b

not Returns True if the condition is false not a

Example:

a = True
b = False
print(a and b) # Output: False
print(a or b) # Output: True
print(not a) # Output: False
d. Assignment Operators

Assignment operators are used to assign values to variables and combine assignment with arithmetic operations.

Operator Description Example

= Assigns value to a variable a=5

+= Adds and assigns the value a += 3

-= Subtracts and assigns the value a -= 3

*= Multiplies and assigns the value a *= 3

/= Divides and assigns the value a /= 3

**= Exponentiation and assigns a **= 3

Example:

a = 5
a += 2 # a = a + 2, now a = 7
a *= 3 # a = a * 3, now a = 21

e. Bitwise Operators

These operators work on bits and perform bit-by-bit operations.

Operator Description Example

& AND a&b

| OR a|b

^ XOR a^b

~ NOT (inverts bits) ~a

<< Left shift a << b

>> Right shift a >> b

Example:

a = 6 # In binary: 110
b = 3 # In binary: 011
print(a & b) # Output: 2 (binary: 010)
print(a | b) # Output: 7 (binary: 111)
f. Membership Operators

These operators check for membership in a sequence such as strings, lists, or tuples.

Operator Description Example

In Returns True if a value is in the sequence a in list

not in Returns True if a value is not in the sequence a not in list

Example:

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


print("banana" in fruits) # Output: True
print("grape" not in fruits) # Output: True
Introduction to Python Code Block
A block of code in Python is a group of statements that are intended to execute together. These blocks are
executed as a unit and are typically used in defining functions, control structures (like if, while, for loops), and
classes. Unlike many programming languages that use braces ({}) to define blocks, Python uses indentation.

Importance of Indentation in Python

In Python, indentation (whitespace at the beginning of the line) is used to define blocks of code. It is mandatory
and determines the grouping of statements. Code that is indented to the same level is considered to be part of the
same block. If the indentation is incorrect, Python will raise an error.

Example:

if True:

print("This is part of the block") # This line is indented, part of the block

print("This is outside the block") # This line is not indented, outside the block

In this example:

• The first print() statement is part of the if block because it is indented.

• The second print() statement is outside of the block because it is not indented.

Nested Blocks of Code

Python allows nested blocks, which means a block can contain another block inside it. For example, you can nest
control structures inside one another or have loops inside functions.

Example:

x = 10

y = 5

if x > 0:

print("x is positive")

if y > 0:

print("y is also positive")

else:

print("y is not positive")

Avoiding Common Indentation Errors

Since indentation is critical in Python, it's important to maintain consistency. Here are some tips to avoid errors:

• Use the same number of spaces for each level of indentation (Python commonly uses 4 spaces).

• Do not mix spaces and tabs. This can lead to indentation errors.

• Check for missing or extra indentation. Blocks should be indented under their respective control
structure or function.
IndentationError

If your code's indentation is incorrect, Python will raise an IndentationError. This occurs when you don't follow
the proper indentation rules.

Example:

if True:

print("This will raise an error") # No indentation

The above code will cause an IndentationError because the print statement is not indented under the if condition.
Python Data Types

Python is a dynamically typed language, meaning you don't need to declare the type of a variable when you create
it. Python determines the variable type at runtime based on the assigned value. Following are the different data
types that Python provides.

Number
Number stores numeric values. Python creates Number objects when a number is assigned to a variable.

Python supports 3 types of numeric data.

1.int 2. float 3. complex

Variables of numeric types are created when you assign a value to them

You can get the data type of any object by using the type() function:

a= 10 Output:
b = 27.88 <class 'int'>
c = 5j <class 'float'>
type(a) <class 'complex'>
type(b)
type(c)
Data Type – Number - (int)

Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.

i.e.

x= 1
y= 35656222554887711
z = -3255522

In Python 3, there is effectively no limit to how long an integer value can be. Of course, it is constrained
by the amount of memory your system has, as are all things, but beyond that an integer can be as long
as you need it to be:

The following strings can be prepended to an integer value to indicate a base other than 10:

Prefix Interpretation Base Example

print(0b10)

2
0b (zero + lowercase letter 'b')
Binary 2
0B (zero + uppercase letter 'B') type(0b10)

<class 'int'>

print(0o10)

8
0o (zero + lowercase letter 'o')
Octal 8
0O (zero + uppercase letter 'O') type(0o10)

<class 'int'>

print(0x10)

16
0x (zero + lowercase letter 'x')
Hexadecimal 16
0X (zero + uppercase letter 'X') type(0x10)

<class 'int'>
Data Type – Number - (complex)

Complex numbers are specified as <real part>+<imaginary part>j. For example:

x= 3+5j
y=5j
z = -5j

>>> 2+3j
(2+3j)
>>>type(2+3j)
<class 'complex'>

Boolean Type:

Python 3 provides a Boolean data type. Objects of Boolean type may have one of two
values, True or False (case sensitive).

>>>type((True)
<class 'bool'>
>>>type(False)
<class 'bool'>

Floating-Point Numbers

The float type in Python designates a floating-point number. float values are specified with a decimal
point. Optionally, the character e or E followed by a positive or negative integer may be appended to
specify scientific notation:

>>> 4.2
4.2
>>> type(4.2)
<class 'float'>
>>> 4.
4.0
>>> .2
0.2

>>> .4e7
4000000.0
>>> type(.4e7)
<class 'float'>
>>> 4.2e-4
0.00042
NONE

The None keyword is used to define a null variable or an object. In Python, None keyword is an object,
and it is a data type of the class NoneType.

We can assign None to any variable, but you can not create other NoneType objects.

All variables that are assigned None point to the same object.

Important Point

• None is not the same as False.

• None is not 0.

• None is not an empty string.

• Comparing None to anything will always return False except None itself.

a= None
print(type(a))
<class ‘NoteType’>
Python List
List is an ordered sequence of items. It is one of the most used data type in Python and is very flexible.
All the items in a list do not need to be of the same type.

Declaring a list is pretty straight forward. Items separated by commas are enclosed within brackets [ ].

We can use the slicing operator [ ] to extract an item or a range of items from a list.

Index starts form 0 in Python.

>>>a= [5,10,15,20,25,30,35,40]
>>>print(type(a))
<class ‘list’>
>>>print(a)
[5, 10, 15, 20, 25, 30, 35, 40]
>>>print(a[2])
15
>>>print(a[0:3])
[5, 10, 15]
>>>print(a[5:])
[30, 35, 40]
>>>print(a[:])
[5, 10, 15, 20, 25, 30, 35, 40]
Python Tuple
Tuple is an ordered sequence of items same as list. The only difference is that tuples are immutable.
Tuples once created cannot be modified.
Tuples are used to write-protect data and are usually faster than list as it cannot change dynamically.
It is defined within parentheses () where items are separated by commas.
We can use the slicing operator [] to extract items but we cannot change its value.

>>>t = (5, "program", 2.5)


>>>print(t)
(5, 'program', 2.5)
>>>print(t[1])
program
>>>print(t[0:3])
(5, 'program', 2.5)
>>>t[1] = 30

ERROR!
Traceback (most recent call last):
File "<main.py>", line 5, in <module>
TypeError: 'tuple' object does not support item assignment

Python string
String is sequence of Unicode characters. We can use single quotes or double quotes to represent strings.
Multi-line strings can be denoted using triple quotes, ''' or """.

Like list and tuple, slicing operator [ ] can be used with string. Strings are immutable.

h e l l o w o r l d !

0 1 2 3 4 5 6 7 8 9 10 11

>>>s= "Hello World!"


>>>print(type(s))
<class 'str'>
>>>print(s[4])
o
>>>print(s[6:11])
World
>>>s[5] = "d"
ERROR!
Traceback (most recent call last):
File "<main.py>", line 5, in <module>
TypeError: 'str' object does not support item assignment
Python Dictionary
Dictionary is an unordered collection of key-value pairs. It is generally used when we have a huge
amount of data. Dictionaries are optimized for retrieving data. We must know the key to retrieve the
value.

In Python, dictionaries are defined within braces {} with each item being a pair in the form key: value.
Key and value can be of any type.

We use key to retrieve the respective value. But not the other way around.

>>>student = {"name":"Aman Singh","age":20,'course':"Btech",5:"Five"}


>>>print(type(student))
<class 'dict'>
>>>print(student["name"])
Aman Singh
>>>print(student[5])
Five
>>>print(student["xyz"])
ERROR!
Traceback (most recent call last):
File "<main.py>", line 5, in <module>
KeyError: 'xyz'

Python Set
Set is an unordered collection of unique items. Set is defined by values separated by comma inside
braces { }. Items in a set are not ordered.

We can perform set operations like union, intersection on two sets. Set have unique values. They
eliminate duplicates.

Since, set are unordered collection, indexing has no meaning. Hence the slicing operator [] does not
work.

>>>s={10,10,20,20,30,35,40,50,60}
>>>print(s)
{50, 35, 20, 40, 10, 60, 30}
>>>print(type(s))
<class 'set'>
>>>print(s[2])
ERROR!
Traceback (most recent call last):
File "<main.py>", line 4, in <module>
TypeError: 'set' object is not subscriptable
Type Conversion
We can convert data types by using different type conversion functions like:

int(), float(), str(), list(), tuple() etc.

Conversion from float to int will truncate the value (make it closer to zero).

>>>int(10.6)
10
>>>int(-10.6)
10

Conversion to and from string must contain compatible values.


>>>float('2.5')
2.5
>>>str(25)
'25'

We can even convert one sequence to another.

>>>set([1,2,3])
{1, 2, 3}
>>>tuple({5,6,7})
(5, 6, 7)
>>>list('hello')
['h', 'e', 'l', 'l', 'o']

You might also like