Python For Absolute Newbies
Python For Absolute Newbies
Python For Absolute Newbies
FOR
ABSOLUTE
NEWBIES
ABBAS ALI
Python For Absolute Newbies
Table Of Content
=> Introduction
=> Set-Up
=> Variables
=> Datatypes
-> str
-> int
-> float
-> bool
=> Operators
-> Arithmetic Operators
-> Comparison Operators
-> Assignment Operators
-> Logical Operators
-> Identity Operators
-> Membership Operators
=> 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!
this book and reading these lines says that you are really
I am writing this book for people who are totally new to Python
from Scratch.
opportunities that will open for you once you get good at writing
code in Python.
If you want to get into any of the fields I mentioned above the
to learn Python.
Python.
Python.
Learning Python is the best thing you can do for your career
right now. Believe me, you will never regret learning Python.
consistently.
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 output screen. You can simply use the print() function and
Done? Okay.
that soon).
a = "Hello World!"
print(a)
follow when giving a name to your variable. Let’s say you want to
The above code will give you a syntax error because you cannot
print(first_name)
# OUTPUT: Abbas
variables and store your age, first name, last name, country
age = 23
first_name = "Abbas"
last_name = "Ali"
country = 'India'
phone_number = 7200000000
As the name conveys datatypes are just the types of the data.
For example,
”)).
65, 0, 1.
it boolean(bool).
age = 23 #int
str
called type(). Let’s use the type function to see what type of
type(text) #str
When you run the above code you will get “str” as your output,
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
1. Arithmetic Operators
2. Comparison Operators
3. Assignment Operators
4. Logical Operators
5. Identity Operators
6. Membership Operators
+ # Addition
- # Subtraction
* # Multiplication
/ # Division
** # Exponentiation (power)
arithmetic operations.
Addition:
4 + 8 # 12
num1 = 34
num2 = 66
Subtraction:
56 - 34 # 22
56 + 34 - 29 # 61
Let’s try with variables.
num1 = 45
num2 = 25
print(num1 - num2) # 20
Multiplication:
262 * 3 # 786
45 * 3 + 35 - 23 # 147
num1 = 467
num2 = 345
Division:
100 / 4 # 25.0
Floor Division:
100 // 4 # 25
num1 = 78
num2 = 8
Both Division and Floor Division will give us the value that we will
Modulus:
9%3#0
45 % 20 # 5
Let’s try Exponentiation.
Exponentiation:
In Exponentiation,
2² = 2**2 = 2x2
2³ = 2**3 = 2x2x2
2⁴ = 2**4 = 2x2x2x2
and so on.
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
as simple as that.
== # Equal to
!= # Not equal to
Equal to (==):
45 == 45 # True
It says True because 45 is equal to 45. That’s Obvious.
56 == 90 # False
Let’s try.
sensitive which means for Python “a” and “A” are different.
This will return True if two values are not equal to each other
34 != 35 # True
Less than(<):
21 < 56 # True
.
num1 = 66
num2 = 99
Greater than(>):
97 > 89 # True
num1 = 456
num2 = 329
67 <= 85 # True
Operator.
= # Assign value
x=7
print(x) # 7
x += 3
print(x) # 10
Actually, x += 3 is similar to x = x + 3.
variable.
Let’s quickly go through them.
x = 45
print(x) # 45
x -= 35
print(x) # 10
x=4
print(x) # 4
x *= 20
print(x) # 80
Divide and assign(/=):
x = 50
print(x) # 50
x /= 20
print(x) # 2.5
x = 50
print(x) # 50
x //= 20
print(x) # 2
Modulus and assign(%=):
x = 50
print(x) # 50
x %= 20
print(x) # 10
x = 20
print(x) # 20
x **= 2
print(x) # 400
Done.
the above codes are just examples. You should try different
Operators.
100 but greater than 90 in such cases the Logical Operators will
come in handy.
x = 92
As you can see from the above example, both x < 100 and x >
90 are True. When both the conditions are True and statement
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
x = 89
Now one condition in the above code is False thus the whole
or:
x = 89
not:
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
x = 89
the same memory address or not. This can be very well explained
object)
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
Variable a has 90 in it, variable b also has 90, and variable c has
a is b # False
a is c # True
Even though a and b have the same value 90 they are stored in
b”.
But “a is c” is True because the 90 inside the variable c is the
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
And conversely,
a is not b # True
a is not c # False
dictionary.
We have only covered string so far, in the next section you will
The above code returned True because the letter “a” is present
topic.
Built-in Data Structures
1. List
2. Tuple
3. Set
4. Dictionary
lists.
l1 = [1,2,3,4,5]
You can also store the same value twice in the list because the
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
l4[0] # 1
l4[6] # "a"
Now you know what is a list and how to create them. Let’s
List Methods
We have plenty of methods to work with the list but the most
append()
pop()
remove()
insert()
sort()
count()
index()
copy()
clear()
append()
lst1.append('helicopter')
Now you how to add an element to a list. Let’s see how to remove
pop()
Using the pop() method we can remove an element from the list.
The pop() method removes the last element of the list but if you
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
lst2.pop(1)
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
cars.remove('toyota')
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
cars.insert(2, 'tesla')
Now you know how to add and remove elements from the list at
cars[3] = 'lambo'
cars.sort()
The above code sorted the elements present in the cars list in
alphabetical order.
numbers.sort()
numbers.sort(reverse=True)
order. But if you want to sort your list in descending order you
can do that by passing a parameter called ‘reverse’ and setting
count()
avengers.count('iron-man') # 3
avengers.count('thor') # 2
index()
avengers.index('doctor-strange') # 4
strange’ is 4.
copy()
variable.
abcd_copy = abcd.copy()
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
abcd.clear()
print(abcd) # []
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
To access the element inside the tuple we can simply use their
print(tup1[2]) # carrot
your tuple you first need to convert your tuple into a list then
after performing the modifications you can convert the list back
lst1 = list(tup1)
lst1.append('potato')
tup1 = tuple(lst1)
First I printed the tuple so that you know what are all the
converted the tuple into a list using the list() method. Then
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
tup2.count('d') # 4
tup2.index('c') # 4
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
set1 = {1, 2, 3, 4, 5}
print(set1) # {1, 2, 3, 4, 5}
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
them.
To add a new value to our set we can use a method called add().
set2.add('f')
set2.remove('b')
Using the update() method we can join two sets. Let’s see how it
works.
'notebook'}
This is enough about the set built-in data structure. Let’s get
we did for the list and the tuple that is why for each element in
print(d1)
Now in the above code, the “name”, “age”, and “country” are the
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
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
('country', 'India')])
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.
d1['name'] = 'abbas'
learning about lists. We can use the same pop() method in the
d1.pop('age')
d1.clear()
print(d1) # {}
dictionary and how to add, change, and remove elements from it.
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
list, tuple, set, and dictionary it also has its own methods that is
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
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
upper()
lower()
lower-case(small letters).
print(s1.lower()) # i am learning python
replace()
split()
s3 = 'I,am,learning,python,programming'
s4 = 'I;am;learning;python;programming'
'programming']
'programming']
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
print(s1) # My age is 23
the quotes where you want to display the value stored inside
your variable.
name = 'Ali'
age = 23
Flow.
Control Flow
2) while loop
3) for loop
is True. A code example will make more sense to you than the
if (5 > 3):
print("Yes") # Yes
In the above code, the if statement will execute the code inside
condition is True the block of code will get executed. Let’s try a
False condition.
The condition in the above code is False thus the block of code
comes in handy.
else:
print('No') # No
your understanding.
if 'o' in 'Python':
else:
True
else:
that will executed but if it is False it will then move to the else
statement.
code examples.
if ('z' 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
score = 85
grade = 'A'
grade = 'B'
grade = 'C'
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
The while loop executes the same block of code until the
becomes False.
a=0
while a < 5:
print(a)
a += 1
# OUTPUT:
you learn every day and start building simple Python projects you
value “0” top variable “a”. Then I created a while loop that runs
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
Now the value is 2. The same happens until a becomes 5 and the
while 'a' in a:
print(a)
a.pop()
#OUTPUT:
['a', 'a']
['a']
For each loop an “a” gets removed from the list and when the list
String iteration:
for i in "python":
print(i)
# OUTPUT:
List Iteration:
print(i)
# OUTPUT:
Tuple Iteration:
print(i)
# OUTPUT:
5
Set Iteration:
print(i)
# OUTPUT:
for i in range(10):
print(i)
# OUTPUT:
1
2
parameters.
print(i)
# OUTPUT:
3
4
10
11
12
13
14
15
16
17
18
19
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
# 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
I believe now you know how to work with for loop. Let’s move on
The break statements is used to exit or break the loop. And the
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
loop when we met “date” in the fruits list but we also missed the
statement.
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.
sequence objects. After completing the task you can join the
# Syntax
def functionName():
block of code...
Let’s create a simple function that prints “Hey, How are you?”
when it is called.
def greeting():
We can also pass arguments inside the function. Let’s see how to
do that.
as "name"
"Ali"
# OUTPUT:
My name is Ali
numbers.
def add(num1, num2):
print(num1 + num2)
add(2, 3)
add(4, 5)
add(45, 24)
# OUTPUT:
69
can do this.
def areaofcircle(radius):
print(areaofcircle(10))
The above function will return me the area of circle value of the
keyword inside the function only returns the value and does not
square. The more Python code you write the better you will get
We use the input() function to get input from the user. The
print(name)
# OUTPUT:
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
print(num1 + num2)
# OUTPUT:
Enter num1: 44
Enter num2: 56
4456
program 44 and 56 are in string data types thus the “+” will be
need to convert the input() value into an integer. Let’s see how
to do that.
print("Adding two numbers:")
print(num1 + num2)
# OUTPUT:
Enter num1: 44
Enter num2: 56
100
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
Build a lot of projects. Don’t get demotivated when you are not
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
project works, then break them down and write the codes your
# Currency Convertor
print("---------Currency Convertor---------")
if user_choice == 1:
elif user_choice == 2:
print("Invalid Choice!")
Project-2: Rock-Paper-Scissors🪨📄✂️
import random
computer_choice = random.choice(choices)
Scissors): ")
if computer_choice == user_choice.capitalize():
print("Draw")
print("You Win!")
"Scissors":
print("You Win!")
else:
print("Computer Wins!")
# Simple Calculator
print("----------Simple Calculator----------")
print("1. +")
print("2. -")
print("3. *")
print("4. /")
if user_choice == 1:
elif user_choice == 2:
elif user_choice == 3:
elif user_choice == 4:
div = num1/num2
else:
print("Invalid Entry! Try Entering 1, 2, 3, or 4!")
import random
chances = 1
if secret_number == user_guess:
{chances} guess!")
break
else:
if chances < 3:
chances += 1
else:
break
# Quiz Game
score = 0
print("1. Lion")
print("2. Tiger")
print("3. Chetha")
print("4. Panter")
if answer1 == 2:
print("👍")
score += 1
else:
print("👎")
print("1. Lotus")
print("2. Lily")
print("3. Rose")
print("4. Sunflower")
if answer2 == 1:
print("👍")
score += 1
else:
print("👎")
print("4. Despacito")
if answer3 == 3:
print("👍")
score += 1
else:
print("👎")
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
Medium: medium.com/@iabbasali
https://abbasaliebooks.gumroad.com/