Python Fundamentals

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 7

PYTHON FUNDAMENTALS

VARIABLES

o •Store Data

o •No need explicitly specify the type of Data

o •PEP –8

STATICALLY VS DYNAMICALLY TYPE


•Statically typed –if the type of Variable is known at compile time, so before running the
script

•C, C++, Java are statically typed languages

•Dynamically typed –associated with run time values. Values stored in variables have type
and not the name or variable itself

PYTHON DATA TYPES

•Numbers: Integers, Floating point and Complex numbers

•Booleans: Logical values indicating False, True and None

•Strings: Ordered sequence of characters

•Lists: Ordered mutable sequence of objects

•Tuples: Ordered immutable sequence of objects

•Sets: Mutable collections of unordered unique objects

•Dictionaries: Collections of unordered key: valuepairs

MATH OPERATORS

Python Numbers: Integers, floats


 Arithmetic operators –are used with numeric values to perform common mathematical
operations
 Addition +
 Subtraction -
 Division /
 Floor or intdivision //
 Multiplication *
 Exponentiation or raising to a power **
 Modulus(mod) %
•Assignment Operators –are used to assign values to variables
 Simple assignment =
 Increment assignment +=
 Decrement assignment -=
 Multiplication assignment *=
 Division assignment /=
 Power assignment **=
 Modulus assignment %=
 Floor division assignment //=

Comparison Operators –are used to compare values and it either return true or false according
to the condition.
 Equal to ==
 Not Equal to !=
 Greater than >
 Greater than or equal to >=
 Less than <
 Less than or equal to <=
INTRO TO STRINGS
STRINGS –is an ordered sequence of characters
my_str1 = ‘I Learn Python’
my_str2 = “I Learn Python”
In PyCharmwe need to Use built in function print to display the value of the variable unlike
in python cmd
GET USER INPUT
print('An Example of using input() function')
name = input()
print('Your name is:', name)
BUILT-IN FUNCTION
len() –returns the number of items in an object. When the object is a string, the len() function
returns
the number of characters in a string.
COUNT METHOD
The count() method returns the number of elements with the specific value. Occurrence of a
specific value
Syntax
variableName.count(‘a’)
a = letter or Special character
SUBSCRIPT
Subscript or subscripting is a method of pulling out a particular element from a string. the
number in between the square brackets determines which character you're going to pull
out,andit just goes up from zero to one to two and so on and so forth.
Syntax
variableName[0]

Type Error is an exception that occurs when the data type of an object in an operation is
inappropriate
The Type Checking of the variable type is done at run-time. Also, the type system of the
language doesn't force to explicitly declare the 'data-type' of the variable before its usage.

Type Conversion is the process of converting a data type into another data type
Program Flow Program
If..elif..else
A Block of code is a piece of program that is executed as an unit

Python uses Identationto delimiter blocks of code. It uses 4 spaces of indetation.

If..elif.else

 If some_condition_is_true:
o Execute this code
 elifsome_other_condition_is_true:
o Execute this code
 else:
o Execute the code

For Loop means a possibility to execute repetitive task

An object is iterable if we can iterate over that object

If we have a collection of items, iterating over the collection means a way to get items out of the
collection one by one

iterable_object= [1,2,5,9]
foritem initerable_object:
A Range is a type that represents an immutable sequence of numbers and is commonly used
for looping a specific number of times in for loops.
The built in function range() returns ranges of numbers
Range(start, stop, step)
By Default
Start = 0
Step = 1
Start is included
Stop is excluded

Continue
The continue statement in Python returns the control to the beginning of the loop. The
continue statement rejects all the remaining statements in the current iteration of the loop and
moves the control back to the top of the loop.
The continue statement can be used in both while
‘Break’ in Python is a loop control statement. It is used to control the sequence of the loop.
Suppose you want to terminate a loop and skip to the next code after the loop; break will help
you do that. A typical scenario of using the Break in Python is when an external condition
triggers the loop’s termination for loops.

While loop will continue to execute a block of code while some test condition remains True
while some_Boolean_condition_is_true:
do something(while block of code)
else:
another block of code
List and Tuples in Python
LIST
It can hold any object type
Supports Indexing and Slicing. We can refer any item in the sequence by using its index
number
A list is a mutable object and that means it can be modified
A list uses SQUARE BRACKETS and COMMAS to separate elements
list1 = [9, 5, ‘Hello World’, (2, 4)]
list1[2]
‘Hello World’
List Operations

Iteration

my_ips= ['192.168.0.1', '192.168.0.2', '192.168.0.23']

for ipin my_ips:

print(f'Connectingto {ip}')

Connecting to 192.168.0.1

Connecting to 192.168.0.2

Connecting to 192.168.0.23

Concatenation (= vs. +=)

list1 = list1 + list2 -> creates a new list

list1 += list2 -> concatenates/extends list2 to list1 (doesn’t create a new list)
Assignment (=) operator

It creates a reference to the same memory address

Append object to the end of the list.


Extend list - by appending elements from the iterable.
Insert - object before index.
Clear - Remove all items from list.
Pop -Remove and return item at index (default last).
Remove - Remove and return item at index (default last). Raises Index Error if list is empty
or index is out of range.
Index - Returns the index of a certain Value.
Count - how many occurrence of a certain value
Sort - objects from ascending to descending order
Max - Returns the Maximum value in the List
Min - Returns the Minimum value in the List
Sum - Calculate the sum of the elements of the list. Type Error for different type of elements.
Tuples are another type of ordered sequence of items. Tuples are very similar to lists, and like
lists support indexing and slicing;
A tuple is an immutable sequence. This is the key difference between tuples and lists.
Immutable –Cotentcannot be change by adding removing replacing elements. If you need
to modify a tuple you need to create a new one
To create a tuple we use parentheses and commas to separate elements.
Tuple Operations
Iteration
days = ('Monday','Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday') for day in
days:
print(day, end=' ')
Monday Tuesday Wednesday Thursday Friday Saturday Sunday
Concatenation
t1 = (1,2,3)
t2 = (4, 5)
t3 = t1 + t2
t3
(1, 2, 3, 4, 5)
Slicing
days[0:3]
('Monday', 'Tuesday', 'Wednesday')
Repetition
t2 * 2
(4, 5, 4, 5)
Tuple Methods
Tuples are immutable.Fewer Methods are used
Count
Index
Syntax Same as List.
 Tuples are faster and more efficient than lists. Python uses a process called constant
folding. This means recognizing and evaluating constant expressions at compile time rather
than computing them at run time;
One important remark is that tuples are really efficient when they contain immutable
objects like numbers, strings or other tuples.
Tuples are safer that lists. This is called data integrity.
Tuples can be used as keys in dictionaries. Lists are not valid as keys.
Storage efficiency. Less memory consumption;
SETS
•Sets are unordered collections of unique elements. A set is not a sequence type in Python.
add() -> Adds an element to the set
clear() -> Removes all the elements from the set
copy() -> Returns a copy of the set
!! the assignment operator (=) creates a reference to the same set object
discard() and remove() -remove the specified element from the set
DICTIONARY
●In Python a dictionary is an unordered collection of key: value pairs, separated by commas
and enclosed by curly braces;
●A dictionary is mutable object meaning that we can add or remove elements from the
dictionary.
●The basic structure of a dictionary: key and value pairs
●Values can be any Python object, but keys need to be hashableor immutable objects and
unique.
●Membership operation: in and not in
person = {'name': 'John', 'age': 30, 'grades':[7, 9, 10]}
'name' in person
True
●Dictionary Views:
○dict.keys() -> returns keys only
○dict.values() -> returns values only
○dict.items() -> returns (key, value) pairs
●Iteration
for k in person.keys():
print(f'keyis {k}')
for k, v in person.items():
print(f'key:{k} , value:{v}')
key:name, value:Johnkey:age, value:30
key:grades, value:[7, 9, 10]

You might also like