0% found this document useful (0 votes)
10 views16 pages

2 Core_Python_1

Uploaded by

8530206489s
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)
10 views16 pages

2 Core_Python_1

Uploaded by

8530206489s
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/ 16

bytesbizztechnology@gmail.

com

Core Python
Keyword
import keyword
print("The list of keywords is : ")
print(keyword.kwlist)

def
def keyword is used to declare user defined functions

class
class keyword is used to declare user defined classes.

Return Keyword
 return : This keyword is used to return from the function.

as
as keyword is used to create module import. E.g import math as mymath.

pass
pass is the null statement in python. This is used to prevent indentation errors and used as a
placeholder.

Import, From
 import : This statement is used to include a particular module into current program.
 from : Generally used with import, from is used to import particular functionality from the
module imported.

Exception Handling Keywords – try, except, raise, finally, and


assert
del
del is used to delete a reference to an object. Any variable or list value can be deleted using del.

Global
 global: This keyword is used to define a variable inside the function to be of a global scope.

Control Flow in Python

If statement
if statement is the most simple decision-making statement. It is used to decide whether a certain
statement or block of statements will be executed or not i.e if a certain condition is true then a block
of statement is executed otherwise not.

# python program to illustrate If statement

i = 25

if (i > 15):
print("i is less than 25")
print("")

if-else
The if statement alone tells us that if a condition is true it will execute a block of statements and if
the condition is false it won’t. But what if we want to do something else if the condition is false.
Here comes the else statement. We can use the else statement with if statement to execute a block of
code when the condition is false.
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
A nested if is an if statement that is the target of another if statement. Nested if statements mean an
if statement inside another if statement. Yes, Python allows us to nest if statements within if
statements. i.e, we can place an if statement inside another if statement.

i = 10
if (i == 10):

if (i < 15):
print("i is smaller than 15")

if (i < 12):
print("i is smaller than 12 too")
else:
print("i is greater than 15")

If-elif-else ladder
It can decide among multiple options. The if statements are executed from the top down. As soon as
one of the conditions controlling the if is true, the statement associated with that if is executed, and
the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will
be executed.
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")

Short Hand if-else statement

i = 10
print(True) if i < 15 else print(False)

Using split() method :

This function helps in getting multiple inputs from users. It breaks the given input by the specified
separator. If a separator is not provided then any white space is a separator.

input().split(separator, maxsplit)

x, y = input("Enter two values: ").split()


print("Number 1: ", x)
print("Number 2: ", y)
print()
x, y, z = input("Enter three values: ").split()
print("Total number : ", x)
print("Number 1 is : ", y)
print("Number 2 is : ", z)
print()
a, b = input("Enter two values: ").split()
print("First number is {} and second number is {}".format(a, b))
print()
Data Type
T1 = ()
print(" empty Tuple: ")
print(T1)

L1 = [1, 2, 3, 4, 5]
print("\nTuple using List: ")
print(tuple(L1))

T1 = tuple('one')
print("\nTuple with the use of function: ")
print(T1)

T1 = tuple("Two")
print("\nFirst element of Tuple: ")
print(T1[0])

*concatenation of two tuples


T1 = (0, 1, 2, 3)
T2 = ('one', 'two', 'three',’four’)
T3 = T1 + T2
print(T3)

*Slicing

T1 = tuple('Hiringwebdevloper')
print("Removal of First Element: ")
print(T1[1:])
print("\nTuple after sequence of Element is reversed: ")
print(T1[::-1])
print("\nPrinting elements between Range: ")
print(T1[3:11])

*use dict() method

# Python code to convert into dictionary


def Convert(T1, D1):
D1 = dict(T1)
return D1
T2 = [("one", 10), ("two", 12), ("three", 14),
("four", 20)]
dictionary = {}
print (Convert(T2, dictionary))

Using count()):
The idea is to use method count() to count number of occurrences.

def Count(tup, en):


return tup.count(en)
tup = (2, 8, 6, 2, 4, 4, 6, 4, 2, 6, 4, 2)
en1 = 2
en2 = 4
en3 = 6
print(Count(tup, en1), "times")
print(Count(tup, en2), "times")
print(Count(tup, en3), "times")

*Remove-empty-tuples-list

def Remove(tuples):
for i in tuples:
if(len(i)==0):
tuples.remove(i)
return tuples
tuples = [(), ('one','10'), (), ('two', 'three'),
('',''),()]
print(Remove(tuples))

Lists
List is a collection of things, enclosed in [ ] and separated by commas.
The list is a sequence data type which is used to store the collection of data. Tuples and String are
other types of sequence data types.

L1 = ["One", "Two", "Three"]


print(L1)

L1 = ["One", "Two", "Three"]


print("\nList Items: ")
print(L1[0])
print(L1[2])
L1 = [2, 4, 'one', 8, 'one']
print("\nList with the use of Mixed Values: ")
print(L1)

L1 = []
print(len(L1))
L2 = [10, 20, 30]
print(len(L2))

*Taking Input

str = input("Enter element ")


L1 = str.split()
print('The list is:', L1)

*Append() method

L1 = []
print("Initial blank List: ")
print(L1)
L1.append(5)
L1.append(6)
L1.append(7)
print("\nList after Addition of Three elements: ")
print(L1)

*insert() method

L1 = [1,2,3,4]
print("Initial List: ")
print(L1)
L1.insert(0, 'one')
L1.insert(2, 20)
print("\nList after performing Insert Operation: ")
print(L1)

*extend() method

L1 = [1, 2, 3, 4]
print("Initial List: ")
print(L1)
L1.extend([10, 11, 13, 'one', 'two'])
print("\nList after Extend method: ")
print(L1)

* Reversing a List
L1 = [1, 2, 3, 'one']
L1.reverse()
print(L1)

* Remove Element(Remove() method )

L1 = [1, 2, 3, 4, 5, 6, 7]
print("Initial List: ")
print(L1)
L1.remove(1)
L1.remove(5)
print("\nList after Removal of two elements: ")
print(L1)

*Pop() method (Using Index)

L1 = [1, 2, 3, 4, 5]
L1.pop()
print("\nList after popping an element: ")
print(L1)
L1.pop(1)
print("\nList after popping a specific element: ")
print(L1)

other : [3:9], [::-1],[:]

String
A. Length of a String:
We can find the length of a string using len() function.

fruit = "Mango"
len1 = len(fruit)
print("Mango is a", len1, "letter word.")

A string is essentially a sequence of characters also called an array. Thus we can access the elements
of this array.
p = "Bytesbiz"
print(p[:5])
print(p[5:])
print(p[2:6])
print(p[-8:])

String Methods
Python provides a set of built-in methods that we can use to alter and modify the strings.

upper() : The upper() method converts a string to upper case.


Example:
str1 = "AbcDEfghIJ"
print(str1.upper())

Output:

ABCDEFGHIJ

lower() : The lower() method converts a string to upper case.


Example:
str1 = "AbcDEfghIJ"
print(str1.lower())

Output:
abcdefghij

strip() : The strip() method removes any white spaces before and after the string.
Example:
str2 = " Silver Spoon "
print(str2.strip)

Output:
Silver Spoon

rstrip() : the rstrip() removes any trailing characters.


Example:
str3 = "Hello !!!"
print(str3.rstrip("!"))

Output:
Hello
replace() : the replace() method replaces a string with another string.
Example:
str2 = "Silver Spoon"
print(str2.replace("Sp", "M"))

split() : The split() method splits the give string at the specified instance and returns the
separated strings as list items.
Example:
str2 = "Silver Spoon"
print(str2.split(" ")) .

capitalize() : The capitalize() method turns only the first character of the string to uppercase
and the rest other characters of the string are turned to lowercase. The string has no effect if
the first character is already uppercase.
Example:
str1 = "hello"
capStr1 = str1.capitalize()
print(capStr1)
str2 = "hello WorlD"
capStr2 = str2.capitalize()
print(capStr2)

center() : The center() method aligns the string to the center as per the parameters given by
the user.
Example:
str1 = "Welcome to the Console!!!"
print(str1.center(50))

We can also provide padding character. It will fill the rest of the fill characters provided by the user.

Example:
str1 = "Welcome to the Console!!!"
print(str1.center(50, "."))

count() : The count() method returns the number of times the given value has occurred within
the given string.
Example:
str2 = "Abracadabra"
countStr = str2.count("a")
print(countStr)
endswith() : The endswith() method checks if the string ends with a given value. If yes then
return True, else return False.
Example 1:
str1 = "Welcome to the Console !!!"
print(str1.endswith("!!!"))

Example 2:
str1 = "Welcome to the Console !!!"
print(str1.endswith("Console"))

index() : The index() method searches for the first occurrence of the given value and returns
the index where it is present. If given value is absent from the string then raise an exception.
Example:
str1 = "He's name is one. Dan is an honest man."
print(str1.index("one"))

islower() : The islower() method returns True if all the characters in the string are lower case,
else it returns False.
Example 1:
str1 = "hello world"
print(str1.islower())

str1 = "welcome Mike"


print(str1.islower())
str2 = "Hurray!!!"
print(str2.islower())

isprintable() : The isprintable() method returns True if all the values within the given string
are printable, if not, then return False.
Example 1:
str1 = "We wish you a Merry Christmas"
print(str1.isprintable())
str2 = "Hello, \t\t.Mike"
print(str2.isprintable())

isspace() : The isspace() method returns True only and only if the string contains white spaces,
else returns False.
Example 1:
str1 = " "
print(str1.isspace())
str2 = " "
print(str2.isspace())

istitle() : The istitile() returns True only if the first letter of each word of the string is
capitalized, else it returns False.
Example 1:
str1 = "World Health Organization"
print(str1.istitle())

Output:
True

Example 2:
str2 = "To kill a Mocking bird"
print(str2.istitle())

Output:
False

isupper() : The isupper() method returns True if all the characters in the string are upper
case, else it returns False.
Example 1:
str1 = "WORLD HEALTH ORGANIZATION"
print(str1.isupper())

Output:
True

Example 2:
str2 = "To kill a Mocking bird"
print(str2.isupper())

Output:
False
replace() : The replace() method can be used to replace a part of the original string with
another string.
Example:
str1 = "Python is a Compiled Language."
print(str1.replace("Compiled", "Interpreted"))

Output:
Python is a Interpreted Language.

startswith() : The endswith() method checks if the string starts with a given value. If yes then
return True, else return False.
Example 1:
str1 = "Python is a Interpreted Language"
print(str1.startswith("Python"))

Output:
True

Example 2:
str1 = "Python is a Interpreted Language"
print(str1.startswith("a"))

Output:
False

We can even also check for a value in-between the string by providing start and end index positions.
Example:
str1 = "Python is a Interpreted Language"
print(str1.startswith("Inter", 12, 20))

Output:
True

swapcase() : The swapcase() method changes the character casing of the string. Upper case
are converted to lower case and lower case to upper case.
Example:
str1 = "Python is a Interpreted Language"
print(str1.swapcase())

Output:
pYTHON IS A iNTERPRETED lANGUAGE

title() : The title() method capitalizes each letter of the word within the string.
Example:
str1 = "He's name is Dan. Dan is an honest man."
print(str1.title())

Output:
He'S Name Is Dan. Dan Is An Honest Man.

Format Strings
What if we want to join two separated strings?
We can perform concatenation to join two or more separate strings.
Example:
str4 = "Captain"
str5 = "America"
str6 = str4 + " " + str5
print(str6)

Output:
Captain America

In the above example, we saw how one can concatenate two strings. But how can we concatenate a
string and an integer?
name = "Guzman"
age = 18
print("My name is" + name + "and my age is" + age)

Output:
TypeError: can only concatenate str (not "int") to str

As we can see, we cannot concatenate a string to another data type.


So what’s the solution?
We make the use of format() method. The format() methods places the arguments within the string
wherever the placeholders are specified.
Example:
name = "Guzman"
age = 18
statement = "My name is {} and my age is {}."
print(statement.format(name, age))

Output:
My name is Guzman and my age is 18.

We can also make the use of indexes to place the arguments in specified order.
Example:
quantity = 2
fruit = "Apples"
cost = 120.0
statement = "I want to buy {2} dozen {0} for {1}$"
print(statement.format(fruit,cost,quantity))

Output:
I want to buy 2 dozen Apples for $120.0

Escape Characters
Escape Characters are very important in python. It allows us to insert illegal characters into a string
like a back slash, new line or a tab.
Single/Double Quote: used to insert single/double quotes in the string.
Example:
str1 = "He was \"Flabergasted\"."
str2 = 'He was \'Flabergasted\'.'
print(str1)
print(str2)

Output:
He was "Flabergasted".
He was 'Flabergasted'.

New Line: inserts a new line wherever specified.


Example:
str1 = "I love doing Yoga. \nIt cleanses my mind and my body."
print(str1)

Output:
I love doing Yoga.
It cleanses my mind and my body.

Tab: inserts a tab wherever specified.


Example:
str2 = "Hello \t\tWorld \t!!!"
print(str2)

Output:
Hello World !!!

Backspace: erases the character before it wherever it is specified.


Example:
str2 = "Hello \bWorld !!!"
print(str2)

Output:
Hello World !!!
Backslash: used to insert a backslash into a string.
Example:
str3 = "What will you eat? Apple\\Banana"
print(str3)

Output:
What will you eat? Apple\Banana

You might also like