Python Unit - 2
Python Unit - 2
Python Unit - 2
UNIT - 2
# What is a function ?
A function is like a small program inside a program. You can write your own functions in Python, just like the
print(), input() functions that you already know.
def hello():
print('Mayank!')
print('Mayank!!!')
print('Hello there.')
The code inside the function (the print statements) is run when you call the function, like this:
hello()
If you call hello() three times, it will print the messages three times. This is useful because you can write the
code once in the function, and then use it as many times as you want. This is better than copying and pasting
the same code many times.
If you copy and paste code, and later you need to change it, you have to remember to change it everywhere
you pasted it. But if you use a function, you only need to change the code in one place - inside the function.
This makes your programs shorter, easier to read, and easier to update. This process of removing duplicated
code is called “deduplication”.
In Python, you can make your own functions that take in some information, called arguments. Here’s an
example:
Python
def hello(name):
print('Hello ' + name)
In this function, name is a parameter. When you call the function with an argument like ‘Alice’ or ‘Mayank’,
that argument is stored in the name parameter. So when you run hello('Mayank'), it prints ‘Hello Mayank’.
But remember, after the function is done, it forgets the value stored in name. So if you try to print name after
running the function, you’ll get an error because name doesn’t exist outside the function. This is similar to
how a program forgets its variables when it ends.
In Python, when you use a function like len('Hello'), it gives you a result, like 5. This result is called the “return
value” of the function.
You can make your own functions that give a return value. You do this with the return keyword. Here’s an
example:
def getAnswer(number):
if number == 1:
return 'It is certain'
# ...and so on for other numbers...
In this function, depending on the number you give it, it returns a different message.
You can use the return value in your code. For example, you can store it in a variable, or print it:
answer = getAnswer(1)
print(answer) # This will print 'It is certain'
You can even use the return value directly in another function call:
So, a function call can be used anywhere you would use a value, because it gives you a return value.
In Python, there’s a special value called None. It’s used when there’s no other value to give. It’s the only
value of its own type, NoneType.
None is useful when you need a placeholder that won’t be mistaken for a real value. For example, the print()
function shows text on the screen, but doesn’t return anything. So, it returns None.
Here’s an example:
result = print('Hello!')
print(result == None) # This will print True
If a function doesn’t have a return statement, Python automatically adds return None at the end. Also, if you
use return by itself without a value, the function returns None.
In Python, you can give information to functions in two ways. One is by the order of the information, like
random.randint(1, 10). Here, 1 is the start and 10 is the end of the range.
The other way is by using “keyword arguments”. These are special words that you use when you call the
function. For example, the print() function has keyword arguments end and sep.
By default, print() adds a newline at the end, so each thing you print appears on a new line. But you can
change this with end. Like this:
print('Hello', end='')
print('World')
This will print HelloWorld on one line, because end='' means “don’t add anything at the end”.
Also, print() separates things with a space. But you can change this with sep. Like this:
This will print cats,dogs,mice, because sep=',' means “separate things with a comma”.
In Python, variables inside a function are “local” and variables outside are “global”. Local variables only exist
while the function is running. Global variables exist all the time.
Think of “scope” as a box holding variables. When the box is thrown away (like when a function ends),
everything inside is forgotten.
While it’s okay to use global variables in small programs, it’s not a good idea for big programs.
In Python, if you make a variable inside a function (like eggs in the function spam()), you can’t use it outside
the function. This is because it’s a “local” variable. It only exists while the function is running.If you try to print
eggs after running spam(), you’ll get an error.
def spam():
eggs = 31337
spam()
print(eggs)
If you run this program, the output will look like this:
This is because eggs doesn’t exist anymore after spam() is done. It’s like trying to use a word from a
language that doesn’t exist. That’s why you can only use “global” variables (made outside functions) in the
main part of your program.
For example, if you have two functions spam() and bacon(), and both have a local variable called eggs, these
are two different variables. The eggs in spam() is not the same as the eggs in bacon().
def spam():
u eggs = 99
v bacon()
w print(eggs)
def bacon():
ham = 101
x eggs = 0
y spam()
When a function finishes, all its local variables are forgotten. So if bacon() finishes and then spam() prints
eggs, it will print the eggs from spam(), not bacon().
In Python, if you make a variable outside a function (like eggs = 42), it’s a “global” variable. You can use it
inside a function.
Here’s an example:
def spam():
print(eggs)
eggs = 42
spam()
print(eggs)
In this program, spam() prints 42, because eggs is a global variable. Even though eggs is not made inside
spam(), spam() can still use it.
In Python, you can have a local variable and a global variable with the same name. But it can be confusing.
Here’s an example:
def spam():
eggs = 'spam local'
print(eggs) # prints 'spam local'
def bacon():
eggs = 'bacon local'
print(eggs) # prints 'bacon local'
spam()
print(eggs) # prints 'bacon local'
eggs = 'global'
bacon()
print(eggs) # prints 'global'
In this program, there are three variables called eggs. One is inside spam(), one is inside bacon(), and one is
outside all functions (so it’s global). Each eggs is separate from the others.
When you run this program, it prints bacon local, spam local, bacon local, global. This shows that each
function is using its own eggs, not the others’.
So, it’s better to avoid using the same name for different variables in different scopes. It makes your code
easier to understand.
In Python, if you want to change a global variable inside a function, you use the global keyword. Here’s an
example:
def spam():
global eggs
eggs = 'spam'
eggs = 'global'
spam()
print(eggs) # This will print 'spam'
In this program, eggs is a global variable. Inside spam(), we say global eggs, which means “I want to use the
global eggs, not make a new one”. So when we do eggs = 'spam', it changes the global eggs.
If you try to use a local variable before giving it a value, you’ll get an error. Like this:
def spam():
print(eggs) # ERROR!
eggs = 'spam local'
eggs = 'global'
spam()
In this program, spam() tries to print eggs before eggs has a value. So Python gives an error, because it
doesn’t know what eggs is.
ADDITIONAL :
In programming, you often use functions without knowing how they work. You just need to know what they
need (the inputs or parameters) and what they give you (the output).
This is like treating the function as a “black box”. You don’t see inside it, you just use it.
For example, Python has many functions made by other people. You can use these functions without
knowing how they work. And if these functions are well-made, you don’t have to worry about them messing
up your program.
So, a function is like a tool. You don’t need to know how the tool was made or what’s inside it. You just need
to know what it does.
# Exception Handling
In Python, if your program has an error (or “exception”), it stops. But you can make it handle the error and
keep going. Here’s how:
def spam(divideBy):
try:
return 42 / divideBy
except ZeroDivisionError:
print('Error: Invalid argument.')
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))
In this program, spam() tries to divide 42 by a number. If the number is 0, this causes a ZeroDivisionError.
But spam() catches this error with try and except. So instead of stopping, it prints Error: Invalid argument.
and keeps going.
You can also put try and except around calls to a function, like this:
def spam(divideBy):
return 42 / divideBy
try:
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))
except ZeroDivisionError:
print('Error: Invalid argument.')
In this program, if any call to spam() causes an error, it prints Error: Invalid argument. and skips the rest of
the try block. So it doesn’t print spam(1).
This is about learning two things in programming called ‘lists’ and ‘tuples’. Both of them can hold many
values at once, which is useful when you have a lot of data to work with. Lists can even hold other lists,
letting you organize data in layers.
In this part, you’ll learn the basics of lists and something called ‘methods’. Methods are special functions that
work with specific types of data. You’ll also get a quick look at tuples and strings, which are similar to lists.
A ‘list’ is like a container in programming that can hold many values in a certain order. For example, ['cat',
'bat', 'rat', 'elephant'] is a list that holds four values.
Just like you use quotes to start and end a string, you use square brackets to start and end a list. The values
inside the list are called ‘items’, and they are separated by commas.
● [1, 2, 3]
● ['cat', 'bat', 'rat', 'elephant']
● ['hello', 3.1415, True, None, 42]
● spam = ['cat', 'bat', 'rat', 'elephant']
In the last line, the variable ‘spam’ is holding a list. Even though the list has many items, it still counts as just
one value. An empty list [] is a list that doesn’t have any items, just like an empty string '' doesn’t have any
characters.
If you have a list like ['cat', 'bat', 'rat', 'elephant'], you can get each item in the list by its position, or ‘index’.
For example, spam[0] gives you ‘cat’, spam[1] gives you ‘bat’, and so on. The first item is at index 0, the
second item is at index 1, and so on.
You can also do things like 'Hello ' + spam[0] to get ‘Hello cat’.
But be careful, if you try to get an item at an index that doesn’t exist in the list (like spam[10000]), you’ll get
an error. Also, indexes have to be whole numbers (not decimals). So spam[1.0] will give an error, but
spam[int(1.0)] is okay because int(1.0) is the same as 1.
Lists can also have other lists inside them. You can get items in these inner lists by using two indexes. For
example, in spam = [['cat', 'bat'], [10, 20, 30, 40, 50]], spam[0][1] gives you ‘bat’, and spam[1][4] gives you 50.
Negative Indexes
In a list, you can also use negative numbers to get items. For example, -1 gives you the last item, -2 gives
you the second last item, and so on.
In a list, you can use something called a ‘slice’ to get a part of the list. A slice has two numbers separated by
a colon. The first number is where the slice starts, and the second number is where it ends. But the slice
doesn’t include the item at the end index.
You can also leave out the start or end index in a slice. If you leave out the start, it’s the same as starting
from 0. If you leave out the end, it’s the same as going to the end of the list.
So, spam[:2] gives the first two items, spam[1:] gives all items except the first one, and spam[:] gives all
items.
The len() function is used to find out how many items are in a list. For example, if you have a list like ['cat',
'dog', 'moose'], you can use len(spam) to find out that there are 3 items in the list.
In a list, you can change an item by using its index. For example, if you have a list like ['cat', 'bat', 'rat',
'elephant'], you can change ‘bat’ to ‘aardvark’ by using spam[1] = 'aardvark'.
So, spam[1] = 'aardvark' changes the second item to ‘aardvark’, spam[2] = spam[1] changes the third item to
the same as the second item, and spam[-1] = 12345 changes the last item to 12345.
In programming, you can use the + sign to join two lists together, just like you can join two words. You can
also use the * sign with a list and a number to repeat the list that many times.
[1, 2, 3] + ['A', 'B', 'C'] # This gives [1, 2, 3, 'A', 'B', 'C']
['X', 'Y', 'Z'] * 3 # This gives ['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']
spam = [1, 2, 3]
spam = spam + ['A', 'B', 'C'] # This changes spam to [1, 2, 3, 'A', 'B', 'C']
So, [1, 2, 3] + ['A', 'B', 'C'] joins the two lists together, ['X', 'Y', 'Z'] * 3 repeats the list ‘XYZ’ three times, and
spam = spam + ['A', 'B', 'C'] adds ‘A’, ‘B’, ‘C’ to the end of the list in spam.
In programming, you can use the del command to remove an item from a list. When you remove an item, all
the items after it move up one spot.
You can also use del to remove a whole variable. But if you try to use it after that, you’ll get an error because
it doesn’t exist anymore. But usually, you use del to remove items from lists, not to remove whole variables.
When you start programming, you might want to use a separate variable for each similar thing. For example,
if you have many cats, you might want to use a separate variable for each cat’s name like this:
catName1 = 'Zophie'
catName2 = 'Pooka'
catName3 = 'Simon'
# and so on...
But this is not a good way to write code. If the number of cats changes, your program can’t handle it. Also,
there’s a lot of repeated code.
Instead, you can use a list to store all the cat names in one place. This way, your program can handle any
number of cats. Here’s how you can do it:
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) + ' (Or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] # This adds the new name to the list
When you run this program, it asks you for cat names one by one until you choose to stop. Then it prints all
the cat names. Using a list like this makes your program more flexible and easier to work with.
In programming, you can use a ‘for loop’ to do something for each item in a list. For example, if you use for i
in range(4): print(i), it will print 0, 1, 2, 3. This is because range(4) gives you a list of numbers from 0 to 3.
You can also use a list directly in a for loop like this: for i in [0, 1, 2, 3]: print(i). This will do the same thing.
A common way to use a for loop with a list is for i in range(len(someList)). This lets you go through each
index in the list. Here’s an example:
This prints each item in the ‘supplies’ list with its index. So, range(len(supplies)) gives you all the indexes in
the ‘supplies’ list.
In programming, you can use ‘in’ and ‘not in’ to check if something is or isn’t in a list. For example, 'howdy' in
['hello', 'hi', 'howdy', 'heyas'] checks if ‘howdy’ is in the list, and it gives ‘True’ because ‘howdy’ is in the list.
You can also use this to check if a pet name is in a list of pet names. If the name is not in the list, it says “I do
not have a pet named (name)”. If the name is in the list, it says “(name) is my pet”. So, if you enter ‘Footfoot’,
it says “I do not have a pet named Footfoot” because ‘Footfoot’ is not in the list.
Now, ‘size’ is ‘fat’, ‘color’ is ‘black’, and ‘disposition’ is ‘loud’. But be careful, the number of variables and the
number of items in the list have to be the same. If they’re not the same, you’ll get an error. So, size, color,
disposition, name = cat gives an error because there are 4 variables but only 3 items in the list.
In programming, you can use special shortcuts to change the value of a variable. For example, if you have a
number like 42 and you want to add 1 to it, you can use spam += 1 instead of spam = spam + 1. Both of
these will make ‘spam’ 43.
You can also use these shortcuts with words and lists. For example, spam += ' world!' adds ’ world!’ to the
end of ‘spam’. And bacon *= 3 repeats the list ‘bacon’ three times. So, if ‘spam’ is ‘Hello’ and ‘bacon’ is
[‘Zophie’], spam += ' world!' makes ‘spam’ ‘Hello world!’, and bacon *= 3 makes ‘bacon’ [‘Zophie’, ‘Zophie’,
‘Zophie’].
# Methods
A ‘method’ is like a special function that you use with a value. For example, if you have a list called ‘spam’,
you can use a method like spam.index('hello') to find where ‘hello’ is in the list.
Each type of thing (like lists or numbers) has its own methods that you can use. For example, lists have
methods that can find items, add items, remove items, and do other things with the list.
In programming, you can use index() to find where a value is in a list. For example, if you have a list like
['hello', 'hi', 'howdy', 'heyas'], you can use spam.index('hello') to find that ‘hello’ is at the first spot in the list.
But if you try to find something that’s not in the list, like spam.index('howdy howdy howdy'), you’ll get an error.
If a value is in the list more than once, index() gives you the first place it’s found. So, if ‘spam’ is ['Zophie',
'Pooka', 'Fat-tail', 'Pooka'], spam.index('Pooka') gives 1, not 3, because ‘Pooka’ is found first at the second
spot.
Adding Values to Lists with the append() and insert() Methods
In programming, you can use append() to add a value to the end of a list, and insert() to add a value at any
place in the list. For example, if you have a list like ['cat', 'dog', 'bat'], you can use spam.append('moose') to
add ‘moose’ to the end, and spam.insert(1, 'chicken') to add ‘chicken’ at the second spot.
But be careful, you can only use append() and insert() with lists, not with other things like words or numbers.
So, eggs.append('world') and bacon.insert(1, 'world') give errors because ‘eggs’ is a word and ‘bacon’ is a
number, not lists.
In programming, you can use remove() to take out a value from a list. For example, if you have a list like
['cat', 'bat', 'rat', 'elephant'], you can use spam.remove('bat') to take out ‘bat’ from the list.
But if you try to take out something that’s not in the list, like spam.remove('chicken'), you’ll get an error.
If a value is in the list more than once, remove() only takes out the first one. So, if ‘spam’ is ['cat', 'bat', 'rat',
'cat', 'hat', 'cat'], spam.remove('cat') makes the list ['bat', 'rat', 'cat', 'hat', 'cat'].
You can use remove() when you know the value you want to take out. If you know the place of the value in
the list, you can use del.
In programming, you can use sort() to put the items in a list in order. For example, if you have a list like [2, 5,
3.14, 1, -7], you can use spam.sort() to sort the numbers from smallest to largest. You can also use
spam.sort(reverse=True) to sort them from largest to smallest.
But be careful, you can’t sort a list that has both numbers and words, like spam = [1, 3, 2, 4, 'Alice', 'Bob'].
And when you sort words, it puts capital letters before small letters. So, if you want to sort words in normal
alphabetical order, you can use spam.sort(key=str.lower). This treats all the words as if they’re small letters
when it sorts them.
A dictionary is like a box where you can store multiple items. But unlike a list, you can use any type of label,
not just numbers, to find your items. These labels are called ‘keys’, and each key has a value attached to it.
Here’s an example:
In this example, ‘size’, ‘color’, and ‘disposition’ are keys. ‘fat’, ‘gray’, and ‘loud’ are their respective values.
You can find the value of ‘size’ like this:
myCat['size']
And it will give you ‘fat’. You can also use numbers as keys:
Dictionaries and lists are both used to store data, but they work differently. In a list, the order of items is
important. But in a dictionary, the order doesn’t matter.
Here’s an example:
In the above example, spam and bacon are lists. Even though they have the same items, the order is
different, so they are not equal. On the other hand, eggs and ham are dictionaries. They have the same keys
and values, so they are equal, even though the order is different.
If you try to find a key in a dictionary that doesn’t exist, you’ll get an error. For example:
But dictionaries are very useful when you want to store related information. For example, you can store your
friends’ birthdays like this:
birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'}
In this case, the names are the keys and the birthdays are the values. You can easily find someone’s
birthday by their name. If the name doesn’t exist, you can add it. But remember, all the data you enter will be
forgotten when the program ends.
Dictionaries have three methods: keys(), values(), and items(). These methods give you the keys, values, or
both from a dictionary. They don’t give you real lists, but you can use them in loops.
Here’s an example:
If you want a real list, you can convert the result to a list like this:
You can also get the key and value at the same time in a loop:
for k, v in spam.items():
print('Key: ' + k + ' Value: ' + str(v))
This will print “Key: age Value: 42” and “Key: color Value: red”.
You can use ‘in’ and ‘not in’ to check if a key or value is in a dictionary. Here’s an example:
In the last line, ‘color’ in spam is the same as ‘color’ in spam.keys(). So if you want to check if a key is in a
dictionary, you can just use ‘in’ with the dictionary.
Dictionaries have a method called get(). It helps you find the value of a key without getting an error if the key
doesn’t exist. You can give it a key and a default value. If the key is in the dictionary, get() gives you its value.
If not, it gives you the default value.
Here’s an example:
If you try to find the value of ‘eggs’ without using get(), like this:
The setdefault() method is a shortcut to add a new item to a dictionary only if the key does not exist. Here’s
an example:
# If you try to set 'color' to 'white', it won't change because 'color' is already a key
spam.setdefault('color', 'white') # This will still give you 'black'
You can use setdefault() to make sure a key exists. For example, you can count how many times each letter
appears in a string like this:
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
print(count)
This will give you a dictionary where each key is a character from the string, and each value is how many
times that character appears. The setdefault() method makes sure each character is a key in the dictionary
before adding 1 to its count.
# Pretty Printing
The pprint module in Python helps you print dictionaries in a neat and sorted way. This is useful when you
want to see the items in a dictionary clearly.
Here’s an example:
import pprint
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
pprint.pprint(count)
When you run this, it will print the count dictionary in a sorted way. This is especially useful when the
dictionary has other dictionaries or lists inside it.
If you want to get the pretty printed text as a string, you can use pprint.pformat() like this:
print(pprint.pformat(someDictionaryValue))
This is the same as pprint.pprint(someDictionaryValue), but it gives you a string instead of printing it.
People used to play chess with others far away by mailing each other their moves. They used a special way
of writing moves called algebraic chess notation. In this, each square on the board has a letter and number,
like ‘a1’ or ‘g5’. Each piece has a letter, like ‘K’ for king or ‘N’ for knight. So, a move could be written as ‘Nf3’,
which means a knight moved to the square ‘f3’.
You don’t need a physical chessboard to play this way. You can just remember the moves and imagine the
board in your head.
Computers can do this too. They can remember billions of moves and imagine the chessboard. They use
data structures, like lists and dictionaries, to represent the chessboard. This way, they can play chess without
a physical board.
Sometimes, you might need to use lists and dictionaries inside other lists and dictionaries. For example, you
can use a dictionary to keep track of what items each person is bringing to a picnic.
Here’s an example:
allGuests = {'Alice': {'apples': 5, 'pretzels': 12},
'Bob': {'ham sandwiches': 3, 'apples': 2},
'Carol': {'cups': 3, 'apple pies': 1}}
In this example, allGuests is a dictionary where each key is a person’s name and each value is another
dictionary. The inner dictionaries have the items as keys and the number of each item as values. The
totalBrought() function can calculate the total number of each item being brought.
This might seem like a lot for a simple picnic. But imagine if you had thousands of guests each bringing
thousands of items. Then, this kind of data structure would be very useful.
When you’re programming, you can use data structures in any way that works for your program. Don’t worry
too much about the “right” way to do it. As you get more experience, you’ll find better ways to model your
data.
This is about how to use text in your programs. You can join two pieces of text with a plus sign. But there’s
more you can do. You can take out parts of the text, add or take away spaces, change letters to small or big
size, and check if the text is written right. You can also use Python to copy and paste text.
String Literals
In Python, you write text between single quotes. But what if you want to use a quote in the text? If you write
‘That is Alice’s cat.’, Python gets confused. It thinks the text ends at Alice. The rest (s cat.') doesn’t make
sense to Python. But don’t worry, there are other ways to write text.
Double Quotes
You can also use double quotes to write text in Python. The good thing about double quotes is that you can
use a single quote in your text. Like this:
Python knows the single quote is part of the text because the text starts with a double quote. But if you want
to use both single and double quotes in your text, you’ll need to use something called escape characters.
Escape Characters
Escape characters let you use certain special characters in text that you normally can’t use. An escape
character is a backslash (\) followed by the character you want to add. For example, the escape character for
a single quote is '. You can use this in a text that starts and ends with single quotes. Like this:
Python knows that the single quote in Bob's is part of the text because it has a backslash before it. The
escape characters \’ and \" let you put single and double quotes in your text.
Here are some escape characters you can use:
Hello there!
How are you?
I'm doing fine.
Raw Strings
If you put an r before the first quote of a text, it becomes a raw string. A raw string doesn’t care about escape
characters and will print any backslash in the text. Like this:
Python thinks the backslash is part of the text, not an escape character. Raw strings are good if your text has
a lot of backslashes, like in regular expressions.
In Python, you can write text that goes over many lines. You do this with three single quotes or three double
quotes at the start and end. Anything in between, like quotes, tabs, or new lines, is part of the text. The
normal rules for indents in Python don’t apply here.
Here’s an example:
print('''Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob''')
Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob
You’ll see that the single quote in Eve’s doesn’t need a backslash before it. You don’t have to escape single
and double quotes in raw strings. You can write the same text without using a multiline string like this:
print('Dear Alice,\\n\\nEve\'s cat has been arrested for catnapping, cat burglary, and
extortion.\\n\\nSincerely,\\nBob')
Multiline Comments
In Python, you can use the hash sign (#) to write a comment that goes until the end of the line. But if you
want to write a comment that goes over many lines, you can use a multiline string. This is a string that starts
and ends with three double quotes. Here’s an example:
In this code, the text between the triple quotes is a comment that explains what the code does.
In Python, you can look at parts of a text (or string) using indexes. Think of the string ‘Hello world!’ as a list.
Each letter in the string is an item with a number (or index). Like this: ’ H e l l o w o r l d ! ’ 0 1 2 3 4 5 6 7 8 9
10 11 ‘Hello world!’ has 12 letters, from H (0) to ! (11).
If you give a range (like 0:5), you get the letters from the first number up to (but not including) the second
number. So, spam[0:5] gives ‘Hello’, which includes spam[0] to spam[4], but not the space at 5.
Slicing a string doesn’t change the original string. You can save a slice in a new variable. Like this:
This way, you can keep the whole string and the slice for easy use.
In Python, you can use ‘in’ and ‘not in’ to see if one text is inside another text. This gives a True or False
answer. Here’s how you do it:
These checks see if the first text (exactly as it is, with big and small letters) can be found in the second text.
There are many ways (or methods) to work with text (or strings) in Python. These methods can check the
text or change it in some way. This part talks about the methods you’ll use a lot.
The upper() and lower() methods change all the letters in a text to big or small letters. They don’t change the
original text, they make a new one. Like this:
These methods are useful when you want to compare texts without worrying about big or small letters. For
example, ‘great’ and ‘GREat’ are not the same. But if you first change them to small letters, they become the
same.
The isupper() and islower() methods tell you if a text is all big or all small letters. They give a True or False
answer. Like this:
You can also use these methods one after the other. Like this:
Python has some methods that start with ‘is’ and tell you something about the text. They give a True or False
answer. Here are some of them:
● isalpha() gives True if the text has only letters and is not empty.
● isalnum() gives True if the text has only letters and numbers and is not empty.
● isdecimal() gives True if the text has only numbers and is not empty.
● isspace() gives True if the text has only spaces, tabs, and new lines and is not empty.
● istitle() gives True if the text has only words that start with a big letter followed by small letters.
These methods are useful when you want to check what the user has typed in. For example, you can keep
asking for their age until they type in a number. Or you can keep asking for a password until they type in
something with only letters and numbers. Like this:
while True:
print('Enter your age:')
age = input()
if age.isdecimal():
break
print('Please enter a number for your age.')
while True:
print('Select a new password (letters and numbers only):')
password = input()
if password.isalnum():
break
print('Passwords can only have letters and numbers.')
In this code, isdecimal() checks if the age is a number and isalnum() checks if the password has only letters
and numbers.
The startswith() and endswith() methods tell you if a text starts or ends with a certain piece of text. They give
a True or False answer. Here’s how you use them:
These methods are good if you want to check the start or end of a text, not the whole text.
The join() method takes a list of texts and puts them together into one text. You call join() on a text and give it
a list of texts. It gives back a text. The text you get has all the texts from the list put together. Like this:
The text that join() is called on is put between each text in the list.
The split() method does the opposite. It takes a text and gives you a list of texts. By default, it splits the text
wherever there is a space, tab, or new line. These are not included in the list. You can give split() a different
text to split on. Like this:
You can use split() to split a text with many lines into a list where each item is one line. Like this:
The rjust(), ljust(), and center() methods help you arrange your text. They add spaces to your text to make it
a certain length. Here’s how you use them:
In these examples, rjust(10) adds spaces to the left of ‘Hello’ to make it 10 characters long. You can also add
a different character instead of a space. Like this:
The center() method puts your text in the middle. Like this:
These methods are good when you want to print data in a table with the right spacing. Here’s an example:
In this code, printPicnic() takes a dictionary and two numbers for the width of the left and right columns. It
prints a title in the middle. Then it goes through the dictionary and prints each item on a line. The item name
is on the left and the number is on the right. The item name is padded with dots and the number is padded
with spaces. When you run this code, it prints the picnic items twice. The first time, the left column is 12
characters wide and the right column is 5 characters wide. The second time, they are 20 and 6 characters
wide.
Removing Whitespace with strip(), rstrip(), and lstrip()
The strip(), rstrip(), and lstrip() methods help you remove spaces from your text. They give you a new text
without spaces at the start, end, or both. Here’s how you use them:
You can also tell these methods to remove certain letters from the start or end of your text. Like this:
spam = 'SpamSpamBaconSpamEggsSpamSpam'
spam.strip('ampS') # This gives 'BaconSpamEggs'
Here, strip('ampS') removes the letters a, m, p, and S from the start and end of the text in spam. It doesn’t
matter what order you put the letters in. So, strip('ampS'), strip('mapS'), and strip('Spam') all do the same
thing.
The pyperclip module lets you copy and paste text to and from your computer’s clipboard. This is useful
when you want to paste the result of your program into an email or document.
pyperclip is not part of Python. You need to install it separately. After you install it, you can use it like this:
import pyperclip
pyperclip.copy('Hello world!')
pyperclip.paste() # This gives 'Hello world!'
If something else changes the clipboard, paste() will give you that. For example:
pyperclip.paste() # This gives 'For example, if I copied this sentence to the clipboard and then called paste(),
it would look like this:'
In this case, paste() gives you the sentence that was copied to the clipboard.