0% found this document useful (0 votes)
22 views36 pages

PP Unit 1

Uploaded by

palanurag7047
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)
22 views36 pages

PP Unit 1

Uploaded by

palanurag7047
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/ 36

Computer Engineering / Information Technology

Python Programming
Unit-1
Introduction, Data types and
operators
Contents
• Installation and working with python
• Data types of python
• Variables in python
• Computations and logical statements using python’s operators
• String Operations
Installation and working with python
Introduction to python
• Python is popular programming language, created by Guido van Rossum and first released in 1991
• It was designed with emphasis on code readability and its syntax allows programmers to express
code in fewer lines of code,
• It is an object oriented programming language and it is interpreted.
• There is no need to declare variables in python as we do in C, and it is dynamically typed.
• Its syntax is easy to understand but we can say that ii is slow language as compared to C language.
Why Python?
• Open source and community development, Portable across Operating systems
• Versatile, Easy to read, learn and write
• User-friendly data structures
• High-level language
• Popularly used for machine learning purpose as it has many built in libraries.
• Dynamically typed language
• Portable and Interactive
• Ideal for prototypes – provide more functionality with less coding
• Highly Efficient
• (IoT)Internet of Things Opportunities
Organisations using Python
• Yahoo (Maps)
• Spotify
• Dropbox
• Mozilla
• Pinterest
• Quora
• Google (Components of Google Spider and Search Engine)
Python and its Libraries
• Python has huge amount of additional libraries:
1. Matplotlib (For plotting graphs and charts)
2. NumPy (For Scientific Computing)
3. Pandas (For performing Data analysis)
4. Beautiful Soup (For HTML and XML parsing)
5. SciPy (Engineering applications, science and mathematics)
6. Scikit (For machine learning)
Print Statement
• 1. Simple Print Statement:
print("Hello, World!")

• 2. Print with Multiple arguments:


print("Hello,", "World!")

• 3. Print with variables:


name = "Alice"
print("Hello,", name)
Print Statement
• 4. Using f-strings # Inside an f-string, {} are used to enclose expressions that need to be
evaluated and included in the string.
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")

• 5. Using .format() method #Uses format method to insert variables into string
name = "Alice"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
Datatypes and Variables
Data Types
• Python has the following built-in data types:

Name Type Description

Integer int Whole numbers such as 0,1,5,-5, etc..

Float float Numbers with decimal points 1.5, 1.7,..

String str Sequence of ordered character such as ‘name’ , ‘surname’

Boolean bool Logical values such as true or false


Data Structures
• Python has the following built-in data structures:

Name Type Description

List list Ordered sequence of objects represented with [ ].


Tuple tuple Ordered immutable sequence of objects represented with ( ).
Set set Unordered collection of unique objects represented with { }.
Set types are: set, frozenset.
Dictionary dict Unordered key: value pair of objects represented with { }.
Data Structures (Mutable)
• In python mutable objects can be changed after they are created.
• This means you can modify their content without creating a new object.

• Examples of mutable data structure includes:


1. Lists: We can add, remove or modify elements in a list.
2. Dictionaries: We can add, remove or update key-value pairs.
3. Sets : We can add or remove elements from a set.
Data Structures (Immutable)
• Immutable objects cannot be changed after they are created.
• Any operation that appears to modify an immutable object actually creates a new object with the
modified value.

• Examples of immutable data structures include:


1. Data types: integers, floats and complex numbers
2. Strings: Cannot modify individual characters in a string
3. Tuples: Similar to lists but are immutable
Data Structures
• Example:
list=[1,2,3,4,5] Output:
list[0]=10 10,2,3,4,5

print(list)

tuple=(1,2,3,4,5)
tuple[0]=10 Here, in tuple we cannot update index [0]
as it is immutable while in lists we can.
print(tuple)
Python Variables
• Variable is a reserved memory location to store values.
• Unlike other programming languages, python has no command for declaring variables.
• Variable is created when you assign value to it.

• There are certain rules for creating a variable:


1. Name cannot start with digit
2. Space not allowed
3. Cannot contain special character
4. Python keywords not allowed and variable should be in lower case.
Getting the types of Python Variables
• Example:
x=20
Output:
print(x)
20
print(type(x)) <class ‘int’>
Gandhinagar University
y=“Gandhinagar University” <class ‘str’>

print(y)
print(type(y))
Operators of python
Operators of python
• Operators are used to perform operations on variables and values.
• Python divides the operators in the following groups:
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Identity operators
6. Membership operators
7. Bitwise operators
Arithmetic Operators
• Arithmetic operators are used with numeric values to perform common mathematical operations.

Operator Name Example


+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Assignment Operators
• Assignment operators are used to assign values to variables.

Operator Example Same as


= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
Assignment Operators
Operator Example Same as
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
:= print(x := 3) x = 3, print(x)
Comparison Operators
• Comparison operators are used to compare two values.

Operator Name Example


== Equal to x == y
!= Not equal to x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Logical Operators
• Logical operators are used to combine conditional statements.

Operator Description Example


and Returns True if both statements are true. x < 5 and x < 10
or Returns True if one of the statements is true. x < 5 or x < 4
not Reverse the result, returns False if the result is true. not(x < 5 and x < 10)
Identity Operators
• Identity operators are used to compare the objects, not if they are equal, but if they are actually the
same object, with the same memory location.

Operator Description Example


is Returns True if both variables are the same object. x is y
is not Returns True if both variables are not the same object. x is not y
Membership Operators
• Membership operators are used to test if a sequence is presented in an object.

Operator Description Example


in Returns True if a sequence with the specified value is x in y
present in the object
not in Returns True if a sequence with the specified value is not x not in y
present in the object
Bitwise Operators
• Bitwise operators are used to compare (binary) numbers.

Operator Name Description Example


& AND Sets each bit to 1 if both bits are 1. x&y
| OR Sets each bit to 1 if one of two bits is 1. x|y
^ XOR Sets each bit to 1 if only one of two bits is 1. x^y
~ NOT Inverts all the bits. ~x
<< Zero fill Shift left by pushing zeros in from the right and let the x << 2
left shift leftmost bits fall off.
>> Signed Shift right by pushing copies of the leftmost bit in from the x >> 2
right shift left, and let the rightmost bits fall off.
String Functions in Python
String Functions in Python
• There are some built-in string functions supported in Python are listed below:

Method Description

capitalize(), lower(), upper() Converts the characters accordingly.

len() Counts the length of a string.

Count() Returns the number of times a specified value occurs in a string.

istitle(), islower(), isupper() Returns TRUE if it satisfies the condition.

Find() Searches the string for a specified value and returns the position of
where it was found.
String functions in Python
Method Description

replace() Returns a string where a specified value is replaced with a specified value.

strip() Returns a trimmed version of the string(removes whitespace) .

lstrip() Returns a left trim version of the string.

rstrip() Returns a right trim version of the string.

Index() Searches the string for a specified value and returns the position of where it was
found.
String Functions: Example
• Example:
x=“Gandhinagar University, CE”
Output:
print(x) Gandhinagar University, CE
count=x.count(‘i’) 3
print(count) Gandhinagar University, Ce
t=x.title() gandhinagar university, Ce
GANDHINAGAR UNIVERSITY, CE
l=x.lower()
u=x.upper()
print(t)
print(l)
print(u)
String Functions: Example
# Sample string
sample_string = "Hello, Let’s explore Python string functions.“

1. len() - Returns the length of the string


length = len(sample_string)
print(f"Length of the string: {length}")

2. lower() - Converts all characters in the string to lowercase


lowercase_string = sample_string.lower()
print(f"Lowercase: {lowercase_string}")
String Functions: Example
3. upper() - Converts all characters in the string to uppercase
uppercase_string = sample_string.upper()
print(f"Uppercase: {uppercase_string}")

4. capitalize() - Capitalizes the first character of the string


capitalized_string = sample_string.capitalize()
print(f"Capitalized: {capitalized_string}")
String Functions: Example
5. find() - Returns the index of the first occurrence of a substring
index_of_python = sample_string.find(“explore")
print(f"Index of ‘explore': {index_of_python}")
Output: Index of ‘explore’ : 12 # count the space also.

6. split() - Splits the string into a list of substrings


split_string = sample_string.split()
print(f"Splitted: {split_string}")
Output: Splitted : [‘’ Hello,‘’, “Let’s”, “explore”, …. ]

You might also like