Python For Absolute Newbies

Download as pdf or txt
Download as pdf or txt
You are on page 1of 109

PYTHON

FOR
ABSOLUTE
NEWBIES

ABBAS ALI
Python For Absolute Newbies
Table Of Content
=> Introduction

=> Set-Up

=> Hello World!

=> Variables

=> Datatypes
-> str
-> int
-> float
-> bool

=> Operators
-> Arithmetic Operators
-> Comparison Operators
-> Assignment Operators
-> Logical Operators
-> Identity Operators
-> Membership Operators

=> Built-in Data Structures


-> List and its Methods
-> Tuple and its Methods
-> Set and its Methods
-> Dictionary and its Methods

=> String Manipulation

=> Control Flow


-> if, if-else, if-elif-else
-> while loop
-> for loop
-> break and continue

=> Functions

=> User-Input

=> Projects
-> Project-1: Currency Converter💵💶💱
-> Project-2: Rock-Paper-Scissors🪨📄✂️
-> Project-3: Simple Calculator🧮
-> Project-4: Number Guessing Game🔢
-> Project-3: Quiz Game❓
Introduction
Hey there!

First of all, Congratulations. The fact that you have downloaded

this book and reading these lines says that you are really

interested in learning to code in Python and you are taking the

necessary steps to learn it.

I am writing this book for people who are totally new to Python

Programming. No problem if you haven’t written a single line of

code in your life because in this book I will be covering Python

from Scratch.

Before moving ahead. I would like to share with you the

opportunities that will open for you once you get good at writing

code in Python.

As you might have already known, AI (Artificial Intelligence) is

a fast-growing field currently, and under AI we have plenty of

sub-fields such as,

-> Machine Learning

-> Deep Learning


-> Data Science

-> Natural Language Processing

-> Computer Vision

-> Generative AI and so on.

If you want to get into any of the fields I mentioned above the

first step towards that is to learn Python.

If you want to become a Machine Learning Engineer, you need

to learn Python.

If you want to become a Data Scientist, you need to learn

Python.

If you want to become a Data Analyst, you need to learn

Python.

All the currently trending IT roles require Python coding skills.

Learning Python is the best thing you can do for your career

right now. Believe me, you will never regret learning Python.

Enough. Let’s get into the content of the book.


This book is a Hands-on book, just reading the words is not

going to help you. You need to code along, make mistakes,

correct your mistakes, make more mistakes, and learn through

trial and error.

Don’t get demotivated if you are not able to understand

something. It’s normal as a newbie. Slowly but surely you will

start to understand them. So, just stay calm and learn

consistently.

Before reading further I want you to do some set-up.

All you need is a Laptop and a good internet Connection. That’s

it. I am not going to tell you to install any application. This is

going to be really easy.

Follow the Set-Up Section below.


Set-up
Step-1: Open your favourite web browser.

Step-2: Search “Google Colab”.


Step-3: Click on the First Link.

Step-4: Click on “New notebook”. (If you haven’t signed in with


your Gmail, first do that).
Step-5: Now you have a fresh notebook to start your Python
Learning Journey.

Step-6: Click on the “Untitled.ipynb” and change the name of


the file to “Learning Python”.

Now you are all set to code. Let’s write our first line of code.
Hello World!
In the first cell just write, print(“Hello World!), and press
Shift + Enter.

The print() function in Python allows you to print something on

the output screen. You can simply use the print() function and

print anything you want.

Now use the print() function and print your name.

Done? Okay.

Let’s move on to the next topic.


Variables
In Python, Variables are containers that store data in them. Let

me make it more simple for you. For example, “Hello World!”

that we just printed is a data of type String (We will come to

that soon).

Here is the definition:

Definition: Variables in Python are like containers that hold

information. They allow you to give a name to data so you can

use it later in your program.

Simply put, Variables are containers that store a value in them.

a = "Hello World!"

print(a)

In the above code, we have assigned the value “Hello World!” to

a variable called “a”.


I created a variable named “a” just to explain to you what is a

variable but it is always recommended to give a proper name

when creating variables.

greetings = "Hello World!"

Now, the value “Hello World!” is stored in a variable called

“greetings”. This variable name makes more sense than “a”.

Also, there are certain naming conventions that you need to

follow when giving a name to your variable. Let’s say you want to

store your first name in a variable.

first name = "Abbas"

# OUTPUT: SyntaxError: invalid syntax

The above code will give you a syntax error because you cannot

use space between words when creating variables instead you

can use underscore(_).


first_name = "Abbas"

print(first_name)

# OUTPUT: Abbas

Now, here is a simple exercise for you. Create 5 different

variables and store your age, first name, last name, country

name, and phone number. Below is mine.

age = 23

first_name = "Abbas"

last_name = "Ali"

country = 'India'

phone_number = 7200000000

Let’s know what are data types.


Datatypes

As the name conveys datatypes are just the types of the data.

For example,

When we have text data we call it a string(str). Example: “Hello

World!”, “abcd”, “xyz”. (String (str)data are always enclosed

between quotes it can be a single quote (‘ ’) or a double quote(“

”)).

When our data is a number we call it integer(int). Example: 34,

65, 0, 1.

When our data is a decimal number we call it float.

Example: 3.14, 0.343, 453.34324.

When our data is in the form of True or False we call

it boolean(bool).

age = 23 #int

first_name = "Abbas" #str

last_name = "Ali" #str

country = 'India' #str


phone_number = 7200000000 #int

weight = 50.34 #float

married = False #bool

Let’s see some examples for all 4 datatypes one by one.

str

text = "Hey, how are you?"

To know the type of data stored in a variable there is a function

called type(). Let’s use the type function to see what type of

data is present in the variable “text”.

type(text) #str

When you run the above code you will get “str” as your output,

stating that the variable text has data of type string.


You can simply run the above code in Google Colab but if you are

using other platforms to code then you need to use

the print() function.

print(type(text)) # <class 'str'>

int

Similarly,

number = 123

type(number) #int

float

decimal_number = 0.3333

type(decimal_number) #float
bool

boolean = True

type(boolean) #bool

I have just created one example for each of the datatypes but I

want you to create and try different names and numbers. Just

play with it.


Operators

In Python, operators are special symbols or keywords that allow

us to perform different operations on variables and values.

Mainly, there are 6 types of Operators. Namely,

1. Arithmetic Operators

2. Comparison Operators

3. Assignment Operators

4. Logical Operators

5. Identity Operators

6. Membership Operators

Let’s explore them one by one.


Arithmetic Operators

The Arithmetic Operators are used to perform arithmetic

operations such as Addition, Subtraction, Multiplication,

Division, Modulus (remainder of division), Exponentiation

(power), and Floor division (quotient without remainder).

Below are the symbols we will use to perform those operations.

+ # Addition

- # Subtraction

* # Multiplication

/ # Division

// # Floor division (quotient without remainder)

% # Modulus (remainder of division)

** # Exponentiation (power)

Let’s use the symbols one by one and perform different

arithmetic operations.
Addition:

4 + 8 # 12

We can also add the values stored inside variables.

num1 = 34

num2 = 66

print(num1 + num2) # 100

Try out different numbers. Let’s move to subtraction.

Subtraction:

56 - 34 # 22

56 + 34 - 29 # 61
Let’s try with variables.

num1 = 45

num2 = 25

print(num1 - num2) # 20

Multiplication:

To multiply we use the asterisk symbol (*).

262 * 3 # 786

45 * 3 + 35 - 23 # 147
num1 = 467

num2 = 345

print(num1 * num2) # 161115

Division:

For Division, we use the forward-slash (/).

100 / 4 # 25.0

When we divide two numbers using normal division(/) we will get

a decimal value output. If you want your output to be an integer

you can use floor division(//).

Floor Division:

For Floor Division, we will use double forward-slashs(//).

100 // 4 # 25
num1 = 78

num2 = 8

print(num1 / num2) # 9.75

Both Division and Floor Division will give us the value that we will

get as quotient after dividing two numbers but what if we want

the reminder value?

To get the reminder value we can use the Modulus Operator(%).

Modulus:

% is the symbol for Modulus Operation.

9%3#0

As you know, when we divide 9 by 3 the remainder will be 0.

45 % 20 # 5
Let’s try Exponentiation.

Exponentiation:

Using the Exponentiation Operator(**) we can find the square,

cube, and more of any number.

In Exponentiation,

2² = 2**2 = 2x2

2³ = 2**3 = 2x2x2

2⁴ = 2**4 = 2x2x2x2

and so on.

Let’s see some code examples.

3**2 # 9
65**12 # 5688009063105712890625

num = 89

power = 6

print(num**power) # 496981290961

Before moving to the next section try out all the operators

differently.
Comparison Operators

The comparison Operators are used to compare two values. It’s

as simple as that.

Below are all the Comparison Operators:

== # Equal to

!= # Not equal to

< # Less than

> # Greater than

<= # Less than or equal to

>= # Greater than or equal to

These operators will return boolean values as output.

Equal to (==):

This operator compares if two values are equal to each other.

45 == 45 # True
It says True because 45 is equal to 45. That’s Obvious.

(Note: “=” is used to assign a value to a variable whereas “==” is

used to compare if two values are equal or not.

56 == 90 # False

We can also use this operator for string values.

"abbas" == "abbas" # True

Let’s try.

"ali" == 'ALI' # False

The above code will output False because Python is case-

sensitive which means for Python “a” and “A” are different.

Not equal to(!=):


This operator is the opposite of the operator that we just say.

This will return True if two values are not equal to each other

and return False if they are equal to each other.

34 != 35 # True

765 != 765 # False

'PYTHON' != 'python' # True

Less than(<):

“<” is used to compare if a value is less than the other value.

21 < 56 # True
.

num1 = 66

num2 = 99

print(num1 < num2) # True

Greater than(>):

“>” is used to compare if a value is greater than the other value.

97 > 89 # True

num1 = 456

num2 = 329

print(num1 >num2) # True


Less than or Equal to(<=):

“<=” will return True if a number is less than or equal to the

other number else returns False.

67 <= 85 # True

Greater than or Equal to(<=):

“>=” will return True if a number is greater than or equal to the

other number else returns False.

100 >= 99 # True

We are done with the Comparison Operators.


Assignment Operators

The Assignment Operators are used to assign values to a

variable. We have already used “=” which is itself an Assignment

Operator.

But there are some more Assignment Operators that we need to

Explore. They are,

= # Assign value

+= # Add and assign

-= # Subtract and assign

*= # Multiply and assign

/= # Divide and assign

//= # Floor divide and assign

%= # Modulus and assign

**= # Exponentiate and assign

Add and assign(+=):

With this operator, we can add more value to an existing

variable that already has some value in it.


Don’t worry if you are not able to understand it yet. You will

understand once you see the example.

x=7

print(x) # 7

x += 3

print(x) # 10

In the above code, first I created a variable x and stored an

integer value 7 in it, and when I printed x it returned me 7.

In the next line, I used the “+=” operator to add 3 to x.

x already has the value 7 in it when added 3, x becomes 10.

Actually, x += 3 is similar to x = x + 3.

Simply put, adding more value to an already-existing variable.

Similarly, we can do subtraction, multiplication, and other

arithmetic operations that we saw earlier to an already-existing

variable.
Let’s quickly go through them.

Substract and assign(-=):

x = 45

print(x) # 45

x -= 35

print(x) # 10

Multiplication and assign(*=):

x=4

print(x) # 4

x *= 20

print(x) # 80
Divide and assign(/=):

x = 50

print(x) # 50

x /= 20

print(x) # 2.5

Floor Division and assign(//=):

x = 50

print(x) # 50

x //= 20

print(x) # 2
Modulus and assign(%=):

x = 50

print(x) # 50

x %= 20

print(x) # 10

Exponentiation and assign(**=):

x = 20

print(x) # 20

x **= 2

print(x) # 400

Done.

I hope now you have a clear idea of Assignment Operators. All

the above codes are just examples. You should try different

things on your own using the operators.


Logical Operators

The Logical Operators are always used alongside the Comparison

Operators.

Logical Operators are used to combine conditional statements.

For example, let’s say I want to know if a number is less than

100 but greater than 90 in such cases the Logical Operators will

come in handy.

No problem if you still haven’t understood. Once you see the

example you will understand.

The 3 main Logical Operators are,

and # Logical AND (both conditions must be True)

or # Logical OR (at least one condition must be True)

not # Logical NOT (inverts the result of the condition)


and:

x = 92

(x < 100) and (x > 90) #True

As you can see from the above example, both x < 100 and x >

90 are True. When both the conditions are True and statement

will return True but if even one condition is False it will

return False.

This may not make sense to you now but once you start learning

Control flow statements like if, if-else, for loop, and while

loop you will understand how useful these operators are.

x = 89

(x < 100) and (x > 90) # False

Now one condition in the above code is False thus the whole

statement is False because we are using the and operator.


If you want to return True even if one addition is True you need

to use the or operator.

or:

x = 89

(x < 100) or (x > 90) # True

not:

The not operator is used

alongside and and or. The not operator returns True when it’s

False and returns False when it’s True. See the codes below.

x = 89

not (x < 100 or x > 90) # False


x = 89

not (x < 100 and x > 90) # False

x = 89

not (x < 100 and x > 90) # True

That’s it. It’s time to learn about Identity Operators.


Identity Operators

Identity Operators are used to know if two variables belong to

the same memory address or not. This can be very well explained

with an example than words.

Identity Operators are,

is # True if the operands are identical (refer to the same

object)

is not # True if the operands are not identical

a = 90

b = 90

c=a

print(id(a)) # 134294240873488

print(id(b)) # 134294240873456

print(id(c)) # 134294240873488
In the above code, the id() function is used to print the memory

address where the variable is stored.

Variable a has 90 in it, variable b also has 90, and variable c has

the value 90 that a has.

When printing their memory address as you can see

variables a and c have the same memory address.

Let’s use the Identity to compare them.

a is b # False

a is c # True

Even though a and b have the same value 90 they are stored in

different memory addresses which is why we get False for “a is

b”.
But “a is c” is True because the 90 inside the variable c is the

same 90 inside variable a and they have the same memory

address.

If you want to compare the values you can use the “==” operator

but if you want to know whether two variables share the same

memory address then you need to use the “is” operator.

And conversely,

a is not b # True

a is not c # False

And finally, we have reached the last topic of this section.


Membership Operators

This operator is used when we want to know if a value is present

in a sequence. A sequence can be a string, list, tuple, set, or

dictionary.

We have only covered string so far, in the next section you will

learn about lists, tuples, sets, and dictionaries.

The Membership Operators are,

in # True if the value is found in the sequence

not in # True if the value is not found in the sequence

'a' in 'abbas' # True

The above code returned True because the letter “a” is present

in the string “abbas”.

Let’s try “z”.


"z" in "abbas" # False

As “z” is not present in the sequence it says False. It will return

true if we use the “not in” operator.

"z" not in "abbas" # True

We are done with the Operators. Let’s move on to the next

topic.
Built-in Data Structures

Built-in data structures in Python allow you to efficiently

organize and store data. There are mainly 4 built-in data

structures in Python, namely,

1. List

2. Tuple

3. Set

4. Dictionary

Let’s go through them one by one.


List and its Methods

List is a built-in data structure that can be used to store

multiple elements of different data types in one variable.

List is mutable meaning that we can modify, insert, or remove

the elements present in the list using various methods.

We create lists using square brackets([]). Let’s create some

lists.

l1 = [1,2,3,4,5]

l2 = ['a', 'b', 'c', 'd', 'e']

l3 = [1, 'b', 'apple', 4.5, True, 99]

I have created 3 lists named l1, l2, and l3. In l1 I stored 5

elements or values of just integers, in l2 I stored 5 string

elements, and in l3 I stored 6 elements of different datatypes.

You can also store the same value twice in the list because the

list allows duplicate values in it.


l4 = [1, 2, 4, 4, 5, 6, 'a', 5.6]

Each element in the list has an index value, we can access them

using their index value. For example, the index value of the first

element of the list is 0, the index value of the second element is

1, the third element is 2, and so on.

List and their respective Index values

If I want to access the first element I can simply write,

l4[0] # 1

Let’s access the 7th element of the list.

l4[6] # "a"
Now you know what is a list and how to create them. Let’s

perform some operations on them using their methods.

List Methods

We have plenty of methods to work with the list but the most

important ones are,

append()

pop()

remove()

insert()

sort()

count()

index()

copy()

clear()

append()

The append() method is used to add a new element to an already-

existing list. Below is the code example.


lst1 = ['aeroplane', 'boat', 'car', 'bike']

print(lst1) # ['aeroplane', 'boat', 'car', 'bike']

lst1.append('helicopter')

print(lst1) # ['aeroplane', 'boat', 'car', 'bike', 'helicopter']

In the above code, we added an element “helicopter” to the

list lst1 using the append() method.

Now you how to add an element to a list. Let’s see how to remove

an element from the list.

pop()

Using the pop() method we can remove an element from the list.

lst2 = ['a', 'b', 'c', 'd', 'e']

print(lst2) # ['a', 'b', 'c', 'd', 'e']


lst2.pop()

print(lst2) # ['a', 'b', 'c', 'd']

The pop() method removes the last element of the list but if you

want to remove some other element you need to specify the

index value of the element you want to remove inside the pop().

For example, let’s say I want to remove ‘b’ from the list and the

index value of ‘b’ is 1. So,

lst2.pop(1)

print(lst2) # ['a', 'c', 'd']

Now ‘b’ is removed from the list. You can remove any element

you want from the list by specifying its index value inside the

pop() method.
remove()

In case, if you don’t the index value of an element that you want

to remove but you know the value of the element then you can

remove the element using the remove() method.

cars = ['bmw', 'audi', 'toyota', 'benz']

print(cars) # ['bmw', 'audi', 'toyota', 'benz']

cars.remove('toyota')

print(cars) # ['bmw', 'audi', 'benz']

insert()

When you use the append() method you can only insert a new

element in the last index position of the list but what if you

want to insert an element in the 3rd index position or in the 5th

index position or any other index position?

That’s when the insert() method comes in handy. Using the

insert() method we can insert any value in any index position we

want. Below is the code example.


cars = ['bmw', 'audi', 'mclaren', 'benz', 'royce']

print(cars) # ['bmw', 'audi', 'mclaren', 'benz', 'royce']

cars.insert(2, 'tesla')

print(cars) # ['bmw', 'audi', 'tesla', 'mclaren', 'benz', 'royce']

As you can see, using the insert() method I inserted ‘tesla’ in

the 2nd index position of the list.

Now you know how to add and remove elements from the list at

any index position. But you haven’t learned how to modify or

change an element in the list.

To change an element in the list we don’t have to use any

methods. Below is the code,

cars[3] = 'lambo'

print(cars) # ['bmw', 'audi', 'tesla', 'lambo', 'benz', 'royce']

Previously, in the 3rd index position we had ‘mclaren’ but now I

changed the element to ‘lambo’.


sort()

The sort() method is used to sort the list.

cars.sort()

print(cars) # ['audi', 'benz', 'bmw', 'lambo', 'royce', 'tesla']

The above code sorted the elements present in the cars list in

alphabetical order.

Let’s see how the sort() method works for numbers.

numbers = [56, 34, 87, 12, 43, 23, 35, 90]

numbers.sort()

print(numbers) # [12, 23, 34, 35, 43, 56, 87, 90]

numbers.sort(reverse=True)

print(numbers) # [90, 87, 56, 43, 35, 34, 23, 12]

By default, the sort() method sorts the element in ascending

order. But if you want to sort your list in descending order you
can do that by passing a parameter called ‘reverse’ and setting

its value to True.

count()

The count() method is used to count how many times an element

is present in the list.

avengers = ['iron-man', 'captain-america', 'hulk', 'thor', 'doctor-

strange', 'iron-man', 'iron-man', 'thor']

avengers.count('iron-man') # 3

avengers.count('thor') # 2

The element ‘iron-man’ is present 3 times in the list and ‘thor’ is

present 2 times in the list.

index()

The index() method will return the index value of an element.


avengers.index('hulk') # 2

avengers.index('doctor-strange') # 4

The index value of ‘hulk’ is 2 and the index value of ‘doctor-

strange’ is 4.

copy()

Using copy() method we can copy a list in a variable into another

variable.

abcd = ['a', 'b', 'c', 'd', 'e', 'f']

abcd_copy = abcd.copy()

print(abcd_copy) # ['a', 'b', 'c', 'd', 'e', 'f']


Before performing any form of modification in your list you can

make a copy of it using the copy() method because if you make

any mistakes while modifying the list you can use the copy later.

clear()

If you want to remove all the elements in your list and want to

make it empty you can use the clear() method.

abcd.clear()

print(abcd) # []

Now the list abcd is empty.

That’s it. Now you know how to create a list, add elements to it,

remove elements from it, sort the elements in it, make a copy of

it, and more.

Let’s move to the next built-in data structure.


Tuple and its Methods

A Tuple is very similar to a list. But the only difference is like a

list we cannot change or modify a tuple using various methods.

We create lists using square brackets ([]), similarly, to create

tuples we use parentheses (()).

tup1 = ('onion', 'tomato', 'carrot', 'beetroot')

To access the element inside the tuple we can simply use their

indexes. Let’s access the carrot.

print(tup1[2]) # carrot

As I told you before we cannot add, update, or remove an

element from a tuple but there is a way to do that.

If you really want to add, update, or remove an element from

your tuple you first need to convert your tuple into a list then

after performing the modifications you can convert the list back

to a tuple. Below is a code example of how to do that.


print(tup1) # ('onion', 'tomato', 'carrot', 'beetroot')

lst1 = list(tup1)

lst1.append('potato')

tup1 = tuple(lst1)

print(tup1) # ('onion', 'tomato', 'carrot', 'beetroot', 'potato')

First I printed the tuple so that you know what are all the

elements that are already present in the tuple. Then I

converted the tuple into a list using the list() method. Then

using the append() method I added an element(“potato”) to the

list.

After adding the value I again converted the list back to a tuple

using the tuple() method. Finally, I printed the tuple and the

new value was added to it.

We cannot perform any modification but we can check the

number of times an element is present and the index value of an

element like we did for the list.


tup2 = ('a', 'a', 'b', 'd', 'c', 'd', 'd', 'd', 'b')

tup2.count('d') # 4

The number of times ‘d’ present in the tuple is 4.

tup2.index('c') # 4

The index value of the element ‘c’ is 4.

In tuple, there is a concept called unpacking which allows us to

store each and every element in the tuple in separate variables.

Below is the code.

tup3 = ('apple', 'banana', 'cherry')

a, b, c = (tup3)

print(a) # apple

print(b) # banana

print(c) # cherry
That’s it. There is nothing much about tuple. Let’s move to the

next topic.
Set and its Methods

A set data structure is very much different from both the list

and the tuple. As we know lists and tuples allow duplicate values

in them but the set does not allow duplicated values.

For a list, we store the elements inside square brackets([]), for

a tuple, we store the elements inside parentheses (()), similarly,

for a set, we store the elements inside curly brackets({}).

Let’s create a set.

set1 = {1, 2, 3, 4, 5}

set2 = {'b', 'c', 'd', 'e'}

print(set1) # {1, 2, 3, 4, 5}

print(set2) # {'c', 'e', 'd', 'b'}

Unlike a list or a tuple, a set does not have any index position

values for its element. Also, the set is unordered meaning that it

arranges the element in any order it wants to for example, see

“set2” in the above code.


We can only perform add and remove operations on set. Let’s try

them.

To add a new value to our set we can use a method called add().

set2.add('f')

print(set2) # {'e', 'c', 'd', 'f', 'b'}

Similarly, to remove an element from our set we can use a

method called remove().

set2.remove('b')

print(set2) # {'e', 'c', 'd', 'f'}

There is also another set method called the update().

Using the update() method we can join two sets. Let’s see how it

works.

set3 = {'pen', 'pencil', 'eraser'}

set4 = {'ruler', 'marker', 'notebook'}


set3.update(set4)

print(set3) # {'ruler', 'eraser', 'pen', 'marker', 'pencil',

'notebook'}

In the above code, we updated set3 with the elements in set4

using the update() method.

This is enough about the set built-in data structure. Let’s get

started with the dictionaries.


Dictionary and its Methods

The dictionary stores elements in a key-value pair manner. We

cannot access the elements in the dictionary using the index as

we did for the list and the tuple that is why for each element in

the dictionary we need to give a key value.

The elements in the dictionary are accessed using their key

values. Let’s see an example.

d1 = {'name': 'ali', 'age': 23, 'country': 'India'}

print(d1)

Now in the above code, the “name”, “age”, and “country” are the

keys, and “ali”, 23, and “India” are the values.

If I want to access any of the values from the dictionary d1 I

can simply use their keys.

print(d1['name']) # ali

print(d1['age']) # 23

print(d1['country']) # India
There is also a method called get() to do the same thing that

the above code does.

print(d1.get('name')) # ali

print(d1.get('age')) # 23

print(d1.get('country')) # India

If you want to access all the keys in the dictionary you can use

the keys() method.

print(d1.keys()) # dict_keys(['name', 'age', 'country'])

Similarly, if you want to access all the values in the dictionary

you can use the values() method.

print(d1.values()) # dict_values(['ali', 23, 'India'])

There is also a method called items() If you want to access both

the keys and the values from the dictionary.


print(d1.items()) # dict_items([('name', 'ali'), ('age', 23),

('country', 'India')])

We can easily change an already existing value in the dictionary

by using the key of the value you want to change. The code

below will change the value “ali” to “abbas” in the “name” key.

print(d1) # {'name': 'ali', 'age': 23, 'country': 'India'}

d1['name'] = 'abbas'

print(d1) # {'name': 'abbas', 'age': 23, 'country': 'India'}

Like this, you can change any value you want.

I hope you remember the pop() method we used when we were

learning about lists. We can use the same pop() method in the

dictionary as well to remove a key-value pair from it. Let’s see

how it’s done.


print(d1) # {'name': 'abbas', 'age': 23, 'country': 'India'}

d1.pop('age')

print(d1) # {'name': 'abbas', 'country': 'India'}

If you want to remove all the key-value pairs from the

dictionary you can simply use the clear() method.

print(d1) # {'name': 'abbas', 'country': 'India'}

d1.clear()

print(d1) # {}

That’s enough for the dictionary. Now you know what is a

dictionary and how to add, change, and remove elements from it.

Let’s move to the next topic.


String Manipulation

By now you know how to work with the 4 main built-in data

structures.

Unlike other data types such as int, float, and boolean string is a

sequence as we discussed earlier. Because it’s a sequence like a

list, tuple, set, and dictionary it also has its own methods that is

what we are going to cover in this section.

Like other sequence objects(list, tuple, etc…) string also has

index values for each of its characters. For example, for “apple”

the index value of “a” is 0, the index of “p” is 1, the index of the

other “p” is 2, and so on.

Let’s create a simple string and access different characters

from it so that you can understand it clearly.

s1 = 'I am Learning Python'

print(s1[0]) # I
print(s1[1]) #

print(s1[2]) # a

As you can see from the above code the index of “I” is 0 and the

next character after the “I” is space. In Python, even a space is

considered as a character so the index of that space is 1, and

then we got “a” in the second index position.

Let’s see some methods.

upper()

The upper() method converts all the characters in the string to

upper- case(CAPITAL LETTERS).

print(s1.upper()) # I AM LEARNING PYTHON

lower()

The lower() method converts all the characters in the string to

lower-case(small letters).
print(s1.lower()) # i am learning python

replace()

With the help of the replace() method, we can replace a

character or a group of characters with different characters.

Below is the code example.

print(s1.replace('Python', 'To Code')) # I am Learning To Code

The code replaced the word “Python” with “To Code”.

split()

The split() method converts a string to a list by splitting the

characters in the string based on the parameter passed inside

the split() method.

s2 = 'I am learning python programming'

s3 = 'I,am,learning,python,programming'
s4 = 'I;am;learning;python;programming'

print(s2.split(" ")) # ['I', 'am', 'learning', 'python',

'programming']

print(s3.split(",")) # ['I', 'am', 'learning', 'python', 'programming']

print(s4.split(";")) # ['I', 'am', 'learning', 'python',

'programming']

In the above code, words in s2 are separated by space so we can

split each word by passing space in the split() methods

parameter. Similarly, in s3 words are separated by comma(,), and

in s4 words are separated by semi-colon(;).

There is also a technique we can use along with string, it is called

format string. Using format string we can add a variable inside a

string.

You might not understand what I am trying to say but you will

understand how it works once you see the code example below.
age = 23

s1 = f"My age is {age}"

print(s1) # My age is 23

To create a format string you just need to add an f before the

quotes(“”) and then you need to create a curly bracket({}) inside

the quotes where you want to display the value stored inside

your variable.

Let’s see one more example.

name = 'Ali'

age = 23

s2 = f"My name is {name} and my age is {age}"

print(s2) # My name is Ali and my age is 23

We are done with string manipulation. Let’s get into Control

Flow.
Control Flow

Control flow in Python refers to the order in which statements

are executed based on specific conditions. Python provides

several control flow statements namely,

1) if, if -else, if-elif-else

2) while loop

3) for loop

4) break and continue

Let’s go through them one by one to understand better.


if, if-else, if-elif-else

The if statement executes a block of code if the condition in it

is True. A code example will make more sense to you than the

definition so let’s see the code example.

if (5 > 3):

print("Yes") # Yes

In the above code, the if statement will execute the code inside

it which in this case “print(“Yes”) if the condition is true. The

condition is (5 > 3). It’s obvious that 5 is greater than 3 so the

condition is True the block of code will get executed. Let’s try a

False condition.

if (67 > 97):

print("Yes") # This will print nothing.

The condition in the above code is False thus the block of code

inside the if statement will not be executed. But what if you

want to print something even when the condition in


the if statement is False that’s when the if-else statement

comes in handy.

if (67 > 97):

print("Yes") # Will not get printed because the condition is False

else:

print('No') # No

I hope now you can understand how if statements and if-

else statements work. Let’s see some more examples to improve

your understanding.

if 'o' in 'Python':

print("Yes, there is 'o' in Python") # Yes, there is 'o' in Python

else:

print("Nope") # Will not get printed because the condition is

True

Let’s try one more.


if 4 in [1, 2, 3, 4, 5]:

print("Yes, 4 is there in the list") # Yes, 4 is there in the List

else:

print("Nope") # Will not get printed.

There is also another statement called the if-elif-else. Using

this we can check many conditions. If the condition in the if

statement is False it will move to the elif statement if the

condition in the elif statement is True the block of code inside

that will executed but if it is False it will then move to the else

statement.

We can create as many elif statements we want. Below are the

code examples.

if ('z' in 'abbas'):

print("Yes, 'z' is there in 'abbas'") # This is False

elif ('s' in 'abbas'):

print("Yes, 's' is there in 'abbas'") # Yes, 's' is there in 'abbas'

else:
print("Both if and elif conditions are False") # elif statement is

True

I hope you can understand how the above code works. It’s simple

based on the condition the block of codes will be executed.

Here is one more example for you.

score = 85

if score >= 90:

grade = 'A'

elif score >= 80:

grade = 'B'

elif score >= 70:

grade = 'C'

elif score >= 60:

grade = 'D'

else:

grade = 'F'
print(f"For a score of {score}, the grade is {grade}")

If you can understand the above code it is a sign that you almost

learned Python. If you are not able to understand it yet no

problem as time progresses you will start to understand. But it

is important that you learn consistently.

Now it’s time to learn about while loops.


while loop

The while loop executes the same block of code until the

condition is True. It stops its execution only when the condition

becomes False.

a=0

while a < 5:

print(a)

a += 1

# OUTPUT:

Stay calm. It’s initially hard to understand while loops. But as

you learn every day and start building simple Python projects you

will get it.


So, let me explain how the above code works. First I assigned

value “0” top variable “a”. Then I created a while loop that runs

until the condition becomes False.

In the first loop, the condition is True becomes “a” is 0. So, the

block of code inside the while loop will get executed. The block

of code first prints the value inside the variable a and then

updates it by 1.

Now after the first loop the value of “a” is now 1. Still, the

condition is True so a gets printed and updated by 1.

Now the value is 2. The same happens until a becomes 5 and the

condition becomes False.

I hope you can understand how it works.

Let’s see one more examples.

a = ['a', 'a', 'a', 'a', 'a']

while 'a' in a:

print(a)
a.pop()

#OUTPUT:

['a', 'a', 'a', 'a', 'a']

['a', 'a', 'a', 'a']

['a', 'a', 'a']

['a', 'a']

['a']

For each loop an “a” gets removed from the list and when the list

becomes empty with any more “a” the loop stops.

It’s time to learn for loop.


for loop

Using for loop we can iterate over any sequence objects(string,

list, tuple, etc…).

String iteration:

for i in "python":

print(i)

# OUTPUT:

List Iteration:

for i in ['a', 'b', 'c', 'd', 'e']:

print(i)
# OUTPUT:

Tuple Iteration:

for i in (1, 2, 3, 4, 5):

print(i)

# OUTPUT:

5
Set Iteration:

for i in {1, 2, 3, 4, 5}:

print(i)

# OUTPUT:

Not only this. We can also iterate a range of numbers using

the for loop and range() method.

for i in range(10):

print(i)

# OUTPUT:

1
2

The range() method can take 3 parameters (start, stop, step).

By default, it takes the start as 0. In the above code, the value

10 is the stop parameter and I didn’t mention

the step parameter. Let’s understand how to use these

parameters.

for i in range(2, 20):

print(i)

# OUTPUT:

3
4

10

11

12

13

14

15

16

17

18

19

I mentioned the start and stop values as 2 and 20 respectively

which prints me values till 19 because the stop value is 20. If we

set the stop value as 21 we can get till 20. Let’s also specify the

step parameter.
for i in range(2, 21, 2):

print(i)

# OUTPUT:

10

12

14

16

18

20

Now starting from 2 to 21 each value skips 2 steps. I mean, it

gets started at 2 and without printing 3 it will jump to 4 because

we specified 2 in our step parameter.

We can also create multiplication tables using this.


number = 87

for i in range(1, 11):

print(f"{number} x {i} = {number * i}")

# OUTPUT:

87 x 1 = 87

87 x 2 = 174

87 x 3 = 261

87 x 4 = 348

87 x 5 = 435

87 x 6 = 522

87 x 7 = 609

87 x 8 = 696

87 x 9 = 783

87 x 10 = 870

You can get any multiplication table you want by changing the

value of the number variable.

I believe now you know how to work with for loop. Let’s move on

to the next topic.


break and continue

The break statements is used to exit or break the loop. And the

continue statement is used to skip the loop.

Let’s how to use break inside for loop.

fruits = ["apple", "banana", "cherry", "date", "orange"]

for fruit in fruits:

if fruit == "date":

break

print(fruit)

# OUTPUT:

apple

banana

cherry

In the above code, the fruits list gets iterated, and when it

meets the condition fruit == “date” the for loop breaks because

of the break statement.


Because we used a break statement we were able to break the

loop when we met “date” in the fruits list but we also missed the

“orange” next to the “date”.

So, in this case, using a continue statement would be far better

because it only skips and not breaks. Let’s try continue

statement.

fruits = ["apple", "banana", "cherry", "date", "orange"]

for fruit in fruits:

if fruit == "date":

continue

print(fruit)

# OUTPUT:

apple

banana

cherry

orange
As you can see from the above output now we got “orange” as

well.

Enough for this topic.

Now, I am going to give you a task.

Your task is to use continue and break statements in different

sequence objects. After completing the task you can join the

next topic. See you then.


Functions

In Python, a function is a block of code that gets executed when

it is called. Functions help us reuse the code again and again

instead of writing them every time.

We create a function using the def keyword. The syntax for

creating a function is as follows:

# Syntax

def functionName():

block of code...

Let’s create a simple function that prints “Hey, How are you?”

when it is called.

def greeting():

print("Hey, How are you?")

greeting() # Function Call


# OUTPUT:

Hey, How are you?

We can also pass arguments inside the function. Let’s see how to

do that.

def myname(name): # Created function myname() with argument

as "name"

print(f"My name is {name}")

myname("Ali") # Function call and passing the argument value as

"Ali"

# OUTPUT:

My name is Ali

We can pass many arguments or parameters we want in side the

function. Let’s create a simple addition function that adds two

numbers.
def add(num1, num2):

print(num1 + num2)

add(2, 3)

add(4, 5)

add(45, 24)

# OUTPUT:

69

Using the format of the above code I want to you create a

subtraction function and a multiplication function. Come on you

can do this.

There is also another keyword which is used alongside function.

It is called return. Let’s see how it works.

def areaofcircle(radius):

area = 3.14 * radius * radius


return area

print(areaofcircle(10))

The above function will return me the area of circle value of the

argument I pass inside the areaofcircle() function. When

using return we need to print the function because the return

keyword inside the function only returns the value and does not

print it in the output screen thus we need to print it.

Now write functions to find the area of the rectangle and

square. The more Python code you write the better you will get

so don’t hesitate to experiment with all code examples.


User-Input

User-Input in Python allows the user to give input to the

computer. This helps in making our program more interactive.

We use the input() function to get input from the user. The

input() function is just opposite to the print() function. With the

print() function, we can output a value conversely with the

input() function we can get a value.

name = input("Enter Your Name: ")

print(name)

# OUTPUT:

Enter your name: abbas

abbas

When you run the above program first you will get a text box

saying “Enter Your Name:” Then after you enter your name it

gets printed.
By default, the input() function takes all the values you give as a

string for example, see the below code.

print("Adding two numbers:")

num1 = input('Enter num1: ')

num2 = input('Enter num2: ' )

print(num1 + num2)

# OUTPUT:

Adding two numbers:

Enter num1: 44

Enter num2: 56

4456

The output should be 100 but it says 4456 because in this

program 44 and 56 are in string data types thus the “+” will be

used for concatenation. If you want to add two numbers you

need to convert the input() value into an integer. Let’s see how

to do that.
print("Adding two numbers:")

num1 = int(input('Enter num1: '))

num2 = int(input('Enter num2: ' ))

print(num1 + num2)

# OUTPUT:

Adding two numbers:

Enter num1: 44

Enter num2: 56

100

Now I wrapped the input() function with the int() function to

convert any value it gets into an integer value. The output is 100

as expected.

The task for you is to get two numbers as input from the user

multiply them and return the output. Use the above code as a

reference and code it yourself.

Awesome!!! You have successfully completed all the fundamental

concepts of Python Programming. You are already ahead of 90%


of the people. Don’t stop continuing your Python learning journey.

Build a lot of projects. Don’t get demotivated when you are not

able to understand something. Just focus on learning

consistently.

Keep it up❤️‍🔥 .

Before you go, in the next section there are 5 projects for you

to apply everything you learned from this book. Read the codes

of the projects, and try to understand how each line in the

project works, then break them down and write the codes your

way or add more functionality to them.

Just play with it.


Projects

Project-1: Currency Converter💵💶💱

# Currency Convertor

print("---------Currency Convertor---------")

print("1. INR to USD")

print("2. USD to INR")

user_choice = int(input("Enter Your Choice(1 or 2): "))

if user_choice == 1:

amount = float(input("Enter Your INR Amount: "))

amount_in_usd = amount * 0.012033904

print(f"INR {amount} is USD {amount_in_usd}")

elif user_choice == 2:

amount = float(input("Enter Your USD Amount: "))

amount_in_inr = amount * 83.102881

print(f'USD {amount} is INR {amount_in_inr}')


else:

print("Invalid Choice!")

Project-2: Rock-Paper-Scissors🪨📄✂️

# Rock Paper Scissor

import random

choices = ['Rock', 'Paper', 'Scissors']

computer_choice = random.choice(choices)

user_choice = input("Enter Your Choice (Rock or Paper or

Scissors): ")

if computer_choice == user_choice.capitalize():

print("Draw")

elif computer_choice == 'Rock' and user_choice.capitalize() ==


"Paper":

print("You Win!")

elif computer_choice == "Paper" and user_choice.capitalize() ==

"Scissors":

print("You Win!")

else:

print("Computer Wins!")

Project-3: Simple Calculator🧮

# Simple Calculator

print("----------Simple Calculator----------")

print("1. +")

print("2. -")

print("3. *")

print("4. /")

user_choice = int(input("Chose Your Operator(1, 2, 3, or 4): "))


num1 = float(input("Enter Firt Number: "))

num2 = float(input("Enter Second Number:"))

if user_choice == 1:

add = num1 + num2

print(f"{num1} + {num2} = {sum}")

elif user_choice == 2:

sub = num1 - num2

print(f"{num1} - {num2} = {sub}")

elif user_choice == 3:

mul = num1 * num2

print(f"{num1} * {num2} = {mul}")

elif user_choice == 4:

div = num1/num2

print(f"{num1} / {num2} = {div}")

else:
print("Invalid Entry! Try Entering 1, 2, 3, or 4!")

Project-4: Number Guessing Game🔢

# Number Guessing Game

import random

print("Computer: I am thinking of a number between 1 to 10, can

you guess? I will give you 3 chances.")

secret_number = random.randint(1, 10)

chances = 1

while chances < 4:

user_guess = int(input("Enter your Guess: "))

if secret_number == user_guess:

print(f"Computer: Awesome!, You got the number in just

{chances} guess!")
break

else:

if chances < 3:

print("Computer: No, you are wrong, try again!")

chances += 1

else:

print(f"Computer: All 3 chances are over. The number that I

was think was {secret_number}")

break

Project-5: Quiz Game❓

# Quiz Game

print("----------General Knowlege Quiz----------")

score = 0

print("What is India's National Animal?")


print("Choose the correct option:")

print("1. Lion")

print("2. Tiger")

print("3. Chetha")

print("4. Panter")

answer1 = int(input("Enter your option: "))

if answer1 == 2:

print("👍")

score += 1

else:

print("👎")

print("What is India's National Flower?")

print("Choose the correct option:")

print("1. Lotus")

print("2. Lily")

print("3. Rose")

print("4. Sunflower")

answer2 = int(input("Enter your option: "))

if answer2 == 1:
print("👍")

score += 1

else:

print("👎")

print("What is India's National Song?")

print("Choose the correct option:")

print("1. Jai Ho")

print("2. Jana Gana Mana")

print("3. Vande Mataram")

print("4. Despacito")

answer3 = int(input("Enter your option: "))

if answer3 == 3:

print("👍")

score += 1

else:

print("👎")

print(f"Your total Score: {score} out of 3")


That’s it.

Hope this e-book was helpful to you.

You can find all the code examples used in this book using the link

below.

https://github.com/AbbasAli01/AbbasAli/blob/main/Python_For

_Absolute_Newbies.ipynb

Do connect with me on X:

X: x.com/@AbbasAli_X

You can also read my articles on Medium:

Medium: medium.com/@iabbasali

For more e-books check:

https://abbasaliebooks.gumroad.com/

Have an amazing day❤️‍🔥.

You might also like