Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Basic Python

cxvdvvv

Uploaded by

test7946975
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Basic Python

cxvdvvv

Uploaded by

test7946975
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

What is Python?

Python is a popular programming language. It was created by Guido van Rossum, and released in
1991. Python is an open-source programming language, having features like object-oriented,
interpreted and high-level too.

It is used for:

 web development (server-side),

 software development,

 mathematics,

 system scripting.

Python Variables
Variables are containers for storing data values.

 variable name must start with a letter or the underscore character

 A variable name cannot start with a number

 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _
)

 Variable names are case-sensitive (age, Age and AGE are three different variables)

 A variable name cannot be any of the Python keywords

x=5
y = "John"
print(x)
print(y)

Python Data Types


Python Data Types are used to define the type of a variable.
Python Casting
int() - constructs an integer number from an integer literal, a float literal (by removing all decimals),
or a string literal (providing the string represents a whole number)

float() - constructs a float number from an integer literal, a float literal or a string literal (providing
the string represents a float or an integer)

str() - constructs a string from a wide variety of data types, including strings, integer literals and float
literals Casting

x = int(1) # x will be 1

y = int(2.8) # y will be 2

z = int("3") # z will be 3

Python Operators
Operators are used to perform operations on variables and values.

 Arithmetic operators

 Assignment operators

 Comparison operators

 Logical operators

 Identity operators

 Membership operators

 Bitwise operators

Arithmetic Operators
Consider the following table for a detailed explanation of arithmetic operators.

Operator Description

+ (Addition) It is used to add two operands. For example, if a = 10, b = 10 => a+b = 20

- (Subtraction) It is used to subtract the second operand from the first operand. If the first operand is less than
the second operand, the value results negative. For example, if a = 20, b = 5 => a - b = 15

/ (divide) It returns the quotient after dividing the first operand by the second operand. For example, if a
= 20, b = 10 => a/b = 2.0

* It is used to multiply one operand with the other. For example, if a = 20, b = 4 => a * b = 80
(Multiplication)
% (reminder) It returns the reminder after dividing the first operand by the second operand. For example, if a
= 20, b = 10 => a%b = 0

** (Exponent) As it calculates the first operand's power to the second operand, it is an exponent operator.

// (Floor It provides the quotient's floor value, which is obtained by dividing the two operands.
division)

a = 32 # Initialize the value of a

b=6 # Initialize the value of b

print('Addition of two numbers:',a+b)

print('Subtraction of two numbers:',a-b)

print('Multiplication of two numbers:',a*b)

print('Division of two numbers:',a/b)

print('Reminder of two numbers:',a%b)

print('Exponent of two numbers:',a**b)

print('Floor division of two numbers:',a//b)

Comparison operator

Operator Description

== If the value of two operands is equal, then the condition becomes true.

!= If the value of two operands is not equal, then the condition becomes true.

<= The condition is met if the first operand is smaller than or equal to the second operand.

>= The condition is met if the first operand is greater than or equal to the second operand.

> If the first operand is greater than the second operand, then the condition becomes true.

< If the first operand is less than the second operand, then the condition becomes true.

a = 32 # Initialize the value of a

b=6 # Initialize the value of b

print('Two numbers are equal or not:',a==b)

print('Two numbers are not equal or not:',a!=b)


print('a is less than or equal to b:',a<=b)

print('a is greater than or equal to b:',a>=b)

print('a is greater b:',a>b)

print('a is less than b:',a<b)

Assignment Operators

Operator Description

= It assigns the value of the right expression to the left operand.

+= By multiplying the value of the right operand by the value of the left operand, the left operand receives
a changed value. For example, if a = 10, b = 20 => a+ = b will be equal to a = a+ b and therefore, a =
30.

-= It decreases the value of the left operand by the value of the right operand and assigns the modified
value back to left operand. For example, if a = 20, b = 10 => a- = b will be equal to a = a- b and
therefore, a = 10.

*= It multiplies the value of the left operand by the value of the right operand and assigns the modified
value back to then the left operand. For example, if a = 10, b = 20 => a* = b will be equal to a = a* b
and therefore, a = 200.

%= It divides the value of the left operand by the value of the right operand and assigns the reminder back
to the left operand. For example, if a = 20, b = 10 => a % = b will be equal to a = a % b and therefore,
a = 0.

**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4**2 = 16 to a.

//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3 = 1 to a.

a = 32 # Initialize the value of a

b=6 # Initialize the value of b

print('a=b:', a=b)

print('a+=b:', a+=b)

print('a-=b:', a-=b)

print('a*=b:', a*=b)

print('a%=b:', a%=b)

print('a**=b:', a**=b)

print('a//=b:', a//=b)
Bitwise Operators

Operator Description

& (binary and) A 1 is copied to the result if both bits in two operands at the same location are 1. If not, 0 is copied.

| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will be 1.

^ (binary xor) If the two bits are different, the outcome bit will be 1, else it will be 0.

~ (negation) The operand's bits are calculated as their negations, so if one bit is 0, the next bit will be 1, and vice
versa.

<< (left shift) The number of bits in the right operand is multiplied by the leftward shift of the value of the left
operand.

>> (right shift) The left operand is moved right by the number of bits present in the right operand.

a=5 # initialize the value of a

b=6 # initialize the value of b

print('a&b:', a&b)

print('a|b:', a|b)

print('a^b:', a^b)

print('~a:', ~a)

print('a<<b:', a<<1)

print('a>>b:', a>>1)

Logical Operators
The assessment of expressions to make decisions typically uses logical operators. The examples of
logical operators are and, or, and not. In the case of logical AND, if the first one is 0, it does not depend
upon the second one. In the case of logical OR, if the first one is 1, it does not depend on the second
one. Python supports the following logical operators. In the below table, we explain the works of the
logical operators.

Operator Description

and The condition will also be true if the expression is true. If the two expressions a and b are the same,
then a and b must both be true.

or The condition will be true if one of the phrases is true. If a and b are the two expressions, then an or b
must be true if and is true and b is false.
not If an expression a is true, then not (a) will be false and vice versa.

a=5 # initialize the value of a

print(Is this statement true?:',a > 3 and a < 5)

print('Any one statement is true?:',a > 3 or a < 5)

print('Each statement is true then return False and vice-versa:',(not(a > 3 and a < 5)))

Membership Operators
The membership of a value inside a Python data structure can be verified using Python membership
operators. The result is true if the value is in the data structure; otherwise, it returns false.

Operator Description

in If the first operand cannot be found in the second operand, it is evaluated to be true (list, tuple, or
dictionary).

not in If the first operand is not present in the second operand, the evaluation is true (list, tuple, or dictionary).
x = ["Rose", "Lotus"]

print(' Is value Present?', "Rose" in x)

print(' Is value not Present?', "Riya" not in x)

Identity operator

Operator Description

is If the references on both sides point to the same object, it is determined to be true.

is not If the references on both sides do not point at the same object, it is determined to be true.

x = ["apple", "banana"]

print("banana" in x) //true

x = ["apple", "banana"]

print("pineapple" not in x) //true


Python Lists
Lists are used to store multiple items in a single variable.

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

print(thislist)

List / Array Methods in Python

Let’s look at some different methods for lists in Python:

S.no MethodDescription

 1 append() Used for adding elements to the end of the List.


 2 copy() It returns a shallow copy of a list
 3 clear() This method is used for removing all items from the list.
 4 count() These methods count the elements.
 5 extend() Adds each element of an iterable to the end of the List
 6 index() Returns the lowest index where the element appears.
 7 insert() Inserts a given element at a given index in a list.
 8 pop() Removes and returns the last value from the List or the given index value.
 9 remove() Removes a given object from the List.
 10 reverse() Reverses objects of the List in place.
 11 sort() Sort a List in ascending, descending, or user-defined order
 12 min() Calculates the minimum of all the elements of the List
 13 max() Calculates the maximum of all the elements of the List

Python Tuples
Tuple items are ordered, unchangeable, and allow duplicate values.

Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has
been created.

thistuple = ("apple", "banana", "cherry")

print(thistuple)

Tuple Methods

count() Returns the number of times a specified value occurs in a tuple

index() Searches the tuple for a specified value and returns the position of where it was found

Python Sets
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List,
Tuple, and Dictionary, all with different qualities and usage.

A set is a collection which is unordered, unchangeable*, and unindexed.

Duplicates Not Allowed

thisset = {"apple", "banana", "cherry"}

print(thisset)

Set Methods

Python has a set of built-in methods that you can use on sets.

MethodDescription

add() Adds an element to the set

intersection() Returns a set, that is the intersection of two other sets

intersection_update() Removes the items in this set that are not present in other, specified set(s)

isdisjoint() Returns whether two sets have a intersection or not

issubset() Returns whether another set contains this set or not

issuperset() Returns whether this set contains another set or not

pop() Removes an element from the set

remove() Removes the specified element

union() Return a set containing the union of sets

Python Dictionaries
Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and do not allow duplicates

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

print(thisdict)

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

values() Returns a list of all the values in the dictionary

Conditional Statements
Python if statement :
# python program to illustrate If statement

i = 10

if (i > 15):

print("10 is less than 15")

print("I am Not in if")

Python If-Else Statement :


i = 20

if (i < 15):

print("i is smaller than 15")

print("i'm in if Block")

else:

print("i is greater than 15")

print("i'm in else Block")

print("i'm not in if and not in else Block")

Nested-If Statement in Python


# python program to illustrate nested If statement

i = 10

if (i == 10):

# First if statement

if (i < 15):

print("i is smaller than 15")


# Nested - if statement

# Will only be executed if statement above

# it is true

if (i < 12):

print("i is smaller than 12 too")

else:

print("i is greater than 15")

Python if-elif-else Ladder


# Python program to illustrate if-elif-else ladder

i = 20

if (i == 10):

print("i is 10")

elif (i == 15):

print("i is 15")

elif (i == 20):

print("i is 20")

else:

print("i is not present")

The while Loop


With the while loop we can execute a set of statements as long as a condition is true.

i=1

while i < 6:

print(i)

i += 1

Python For Loop


l = ["geeks", "for", "geeks"]

for i in l:

print(i)

Python For Loop with a step size

for i in range(0, 10, 2):

print(i)
Python Functions
def my_function():

print("Hello from a function")

my_function()

def my_function(fname, lname):

print(fname + " " + lname)

my_function("Emil", "Refsnes")

Python Classes and Objects


Almost everything in Python is an object, with its properties and methods.

A Class is like an object constructor, or a "blueprint" for creating objects.

class MyClass:

x=5

p1 = MyClass()

print(p1.x)

The __init__() Function

To understand the meaning of classes we have to understand the built-in __init__() function.

All classes have a function called __init__(), which is always executed when the class is being
initiated.

class Person:

def __init__(self, name, age):

self.name = name

self.age = age

p1 = Person("John", 36)

print(p1.name)

print(p1.age)
Exception Handling
The try block lets you test a block of code for errors.

The except block lets you handle the error.

try:

a = 10

b=0

print(a/b)

except Exception as e:

print("Error: Cannot divide by zero")

You might also like