Python Btech (1)
Python Btech (1)
Introduction to Python
History of Python Programming Language
🧑💻 Creator:
Guido van Rossum, a Dutch programmer, started working on Python in the late 1980s.
He officially released it as Python 0.9.0 in February 1991.
Guido named it "Python" after the British comedy group Monty Python, not the snake.
He wanted a name that was short, unique, and slightly mysterious.
Included classes, functions, exception handling, and core data types like str, list, dict.
Introduced list comprehensions, garbage collection using reference counting and cycle-
detecting GC.
Python 2 series lasted till Python 2.7 (2010), which was supported until January 1, 2020.
🔄 Python Today
The latest stable version is part of the Python 3 series.
Python is one of the most popular programming languages due to its simplicity,
versatility, and wide range of applications: web development, AI/ML, data science,
automation, etc.
🧠 Fun Fact:
Python is open-source and has a huge community contributing to its development via PEPs
(Python Enhancement Proposals).
Python is one of the top programming languages in the world, widely used in
fields such as AI, machine learning, data science, and web development.
The simple and English-like syntax of Python makes it a go-to language for
beginners who want to get into coding quickly.
Because Python is used in multiple fields, there is a high demand for Python
developers, with competitive base salaries.
You can run Python on your computer using the following two methods:
For those who prefer to install Python on your computer, this guide will walk
you through the installation process on Windows, macOS, and Linux
(Ubuntu).
Windows
1. Install VS Code
4. Install Python
Go to the VS Code Official website and download the Windows installer. Once
the download is complete, run the installer and follow the installation
process.
The website automatically detects your operating system and gives you the
right installer.
Now, go to your download folder and run the installer you just downloaded.
Depending on your security settings, you might be prompted to allow access.
Once you have run the installer, you will come across this screen.
On the screen, you will see two options: Install Now and Customize
Installation. We suggest you skip all customization steps and simply
click Install Now.
Click Install Now, as it will include all the necessary files needed later.
This makes it easier to run a Python Program from the command prompt
(cmd) directly without specifying the full path of the Python executable.
After using this option, Python will be successfully installed in your device.
Step 4: Verify your installation
After the installation is complete, you can verify whether Python is installed
by using the following command in the command prompt.
python --version
Note: The version number might differ from the one above, depending on
your installed version.
Now, you are all set to run Python programs on your device.
Run Your First Python Program
First open VS Code, click on the File in the top menu and then select New
File.
Then, save this file with a .py extension by clicking on File again, then Save
As, and type your filename ending in .py. (Here, we are saving it as
Hello_World.py)
Before you start coding, make sure the Python extension is installed in VS
Code. Open VS Code and click on Extensions on the left sidebar. Then, search
for the Python extension by Microsoft and click on install.
Now, write the following code into your file:
print("Hello World")
Then click on the run button on the top right side of your screen.
Now that you have set everything up to run Python programs on your
computer, you'll be learning how the basic program works in Python in the
next tutorial.
In the previous tutorial, you learned how to install Python on your computer.
Now, let's write a simple Python program.
print("Hello, World!")
Output
Hello World!
Congratulations on writing your first Python program. Now, let's see how the
above program works.
The text we want to print is placed within double quotes " ".
We can also use single quotes to print text on the screen. For example,
print('Hello World!')
is same as
print("Hello World!")
Python Comments
In the previous tutorial, you learned to write your first Python program. Now,
let's learn about Python comments.
Important!: We are introducing comments early in this tutorial series
because we will be using them to explain the code in upcoming tutorials.
Comments are hints that we add to our code to make it easier to understand.
Python comments start with #. For example,
# print a number
print(25)
Single-line Comment
We use the hash (#) symbol to write a single-line comment. For example,
# declare a variable
name = "John"
# print name
print(name) # John
# declare a variable
# print name
# John
A single-line comment starts with # and extends up to the end of the line.
We can also use single-line comments alongside the code:
print(name) # John
Unlike languages such as C++ and Java, Python doesn't have a dedicated
method to write multi-line comments.
However, we can achieve the same effect by using the hash (#) symbol at
the beginning of each line.
print("Hello, World!")
'''This is an example
of multiline comment'''
print("Hello, World!")
Output
Hello World
number1 = 10
number2 = 15
For example,
number1 = 10
number2 = 15
Output
The sum is 25
We have resolved the error using a comment. Now if you need to calculate
the product in the near future, you can uncomment it.
Note: This approach comes in handy while working with large files. Instead
of deleting any line, we can use comments and identify which one is causing
an error.
For debugging.
Note: Comments are not and should not be used as a substitute to explain
poorly written code. Always try to write clean, understandable code, and
then use comments as an addition.
In most cases, always use comments to explain 'why' rather than 'how' and
you are good to go.
Python Variables and Literals
In the previous tutorial you learned about Python comments. Now, let's learn
about variables and literals in Python.
Python Variables
number = 10
site_name = 'Facebook'
print(site_name)
# Output: Facebook
Output
site_name = 'Hospital'
print(site_name)
site_name = 'apple.com'
print(site_name)
Output
Hospital
apple.com
a, b, c = 5, 3.2, 'Hello'
Here, we have assigned the same string value 'Asif' to both the
variables site1 and site2.
snake_case
MACRO_CASE
camelCase
CapWords
2. Create a name that makes sense. For example, vowel makes more sense
than v.
3. If you want to create a variable name having two words, use underscore to
separate them. For example:
my_name
current_salary
var num = 5
var Num = 55
print(num) # 5
print(Num) # 55
6. Avoid using keywords like if, True, class, etc. as variable names.
Python Literals
There are different types of literals in Python. Let's discuss some of the
commonly used types in detail.
1. Integer Literals
2. Floating-Point Literals
3. Complex Literals
Here, numerals are in the form a + bj, where a is real and b is imaginary. For
example, 6+9j, 2+3j.
In Python, texts wrapped inside quotation marks are called string literals..
"This is a string."
float_number = 1.23
new_number = integer_number + float_number
print("Value:",new_number)
print("Data Type:",type(new_number))
Output
Value: 124.23
Then we added these two variables and stored the result in new_number.
As we can see new_number has value 124.23 and is of the float data type.
It is because Python always converts smaller data types to larger data types
to avoid the loss of data.
Note:
We get TypeError, if we try to add str and int. For example, '12' + 23.
Python is not able to use Implicit Conversion in such conditions.
We use the built-in functions like int(), float(), str(), etc to perform explicit type
conversion.
This type of conversion is also called typecasting because the user casts
(changes) the data type of the objects.
Example 2: Addition of string and integer Using Explicit Conversion
num_string = '12'
num_integer = 23
num_string = int(num_string)
print("Sum:",num_sum)
Output
Sum: 35
num_string = int(num_string)
Finally, we got the num_sum value i.e 35 and data type to be int.
4. Explicit Type Conversion is also called Type Casting, the data types of
objects are converted using predefined functions by the user.
Python Output
In Python, we can simply use the print() function to print output. For
example,
print('Python is powerful')
Python Output
In Python, we can simply use the print() function to print output. For
example,
print('Python is powerful')
Syntax of print()
Here,
end (optional) - allows us to add add specific values like new line "\n",
tab "\t"
file (optional) - where the values are printed. It's default value
is sys.stdout (screen)
Output
Good Morning!
It is rainy today
In the above example, the print() statement only includes the object to be
printed. Here, the value for end is not used. Hence, it takes the default
value '\n'.
Output
Notice that we have included the end= ' ' after the end of the
first print() statement.
Output
Notice that we have used the optional parameter sep= ". " inside
the print() statement.
We can also use the print() function to print Python variables. For example,
number = -10.6
name = "Programiz"
# print literals
print(5)
# print variables
print(number)
print(name)
Output
5
-10.6
Programiz
We can also join two strings together inside the print() statement. For
example,
Output
Programiz is awesome.
Here,
Output formatting
Sometimes we would like to format our output to make it look attractive. This
can be done by using the str.format() method. For example,
x=5
y = 10
Here, the curly braces {} are used as placeholders. We can specify the order
in which they are printed by using numbers (tuple index).
To learn more about formatting the output, visit Python String format().
Python Input
While programming, we might want to take the input from the user. In
Python, we can use the input() function.
Syntax of input()
input(prompt)
Output
Enter a number: 10
You Entered: 10
In the above example, we have used the input() function to take input from
the user and stored the user input in the num variable.
To convert user input into a number we can use int() or float() functions as:
Here, the data type of the user input is converted from string to integer .
Python Operators
print(5 + 6) # 11
Here's a list of different types of Python operators that we will learn in this
tutorial.
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
6. Special Operators
sub = 10 - 5 # 5
Operat
Operation Example
or
+ Addition 5+2=7
- Subtraction 4-2=2
* Multiplication 2*3=6
/ Division 4/2=2
// Floor Division 10 // 3 = 3
% Modulo 5%2=1
** Power 4 ** 2 = 16
a=7
b=2
# addition
# subtraction
# multiplication
# division
# floor division
# modulo
# a to the power b
Output
Sum: 9
Subtraction: 5
Multiplication: 14
Division: 3.5
Floor Division: 3
Modulo: 1
Power: 49
+ to add a and b
- to subtract b from a
* to multiply a and b
/ to divide a by b
// to floor divide a by b
# assign 5 to x
x=5
Operat
Name Example
or
+= Addition Assignment a += 1 # a = a + 1
-= Subtraction Assignment a -= 3 # a = a - 3
*= Multiplication Assignment a *= 4 # a = a * 4
/= Division Assignment a /= 3 # a = a / 3
%= Remainder Assignment a %= 10 # a = a % 10
# assign 10 to a
a = 10
# assign 5 to b
b=5
a += b #a=a+b
print(a)
# Output: 15
Similarly, we can use any other assignment operators as per our needs.
a=5
b=2
Operat
Meaning Example
or
a=5
b=2
# equal to operator
print('a == b =', a == b)
print('a != b =', a != b)
Output
a == b = False
a != b = True
a > b = True
a < b = False
a >= b = True
a <= b = False
a=5
b=6
Here, and is the logical operator AND. Since both a > 2 and b >= 6 are True,
the result is True.
Operat
Example Meaning
or
Logical AND:
and a and b
True only if both the operands are True
Logical OR:
or a or b
True if at least one of the operands is True
Logical NOT:
not not a
True if the operand is False and vice-versa.
# logical AND
# logical OR
# logical NOT
Identity operators
In Python, is and is not are used to check if two values are located at the
same memory location.
It's important to note that having two variables with equal values doesn't
necessarily mean they are identical.
Operat
Meaning Example
or
True if the operands are not identical (do not refer x is not
is not
to the same object) True
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
Here, we see that x1 and y1 are integers of the same values, so they are
equal as well as identical. The same is the case with x2 and y2 (strings).
But x3 and y3 are lists. They are equal but not identical. It is because the
interpreter locates them separately in memory, although they are equal.
Membership operators
In Python, in and not in are the membership operators. They are used to test
whether a value or variable is found in a sequence
(string, list, tuple, set and dictionary).
In a dictionary, we can only test for the presence of a key, not the value.
Operat
Meaning Example
or
Output
True
True
True
False
Similarly, 1 is key, and 'a' is the value in dictionary dict1. Hence, 'a' in
y returns False.
Python if Statement
Syntax
if condition:
# body of if statement
if number > 0:
Sample Output 1
Enter a number: 10
10 is a positive number.
If user enters 10, the condition number > 0 evaluates to True. Therefore, the
body of if is executed.
Sample Output 2
Enter a number: -2
A statement outside the if statement.
If user enters -2, the condition number > 0 evaluates to False. Therefore, the
body of if is skipped from execution.
Indentation in Python
x=1
total = 0
if x != 0:
total += x
print(total)
Here, the body of if has two statements. We know this because two
statements (immediately after if) start with indentation.
We usually use four spaces for indentation in Python, although any number
of spaces works as long as we are consistent.
You will get an error if you write the above code like this:
# Error code
x=1
total = 0
if x != 0:
total += x
print(total)
Here, we haven't used indentation after the if statement. In this case, Python
thinks our if statement is empty, which results in an error.
Syntax
if condition:
# body of if statement
else:
if number > 0:
print('Positive number')
else:
Sample Output 1
Enter a number: 10
Positive number
If user enters 10, the condition number > 0 evalutes to True. Therefore, the
body of if is executed and the body of else is skipped.
Sample Output 2
Enter a number: 0
If user enters 0, the condition number > 0 evalutes to False. Therefore, the
body of if is skipped and the body of else is executed.
Syntax
if condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block 3
number = -5
if number > 0:
print('Positive number')
print('Negative number')
else:
print('Zero')
Negative number
Here, the first condition, number > 0, evaluates to False. In this scenario, the
second condition is checked.
number = 5
# outer if statement
if number >= 0:
# inner if statement
if number == 0:
print('Number is 0')
else:
print('Number is positive')
else:
print('Number is negative')
Output
Number is positive