0% found this document useful (0 votes)
2 views

Python Btech

Uploaded by

Saurabh Verma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Btech

Uploaded by

Saurabh Verma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Unit-I

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.

🐍 Why the Name 'Python'?

 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.

Timeline of Major Python Versions

✅ 1991 – Python 0.9.0

 Included classes, functions, exception handling, and core data types like str, list, dict.

✅ 1994 – Python 1.0

 First official full release.


 Introduced modules, lambda, map, filter, and reduce.

✅ 2000 – Python 2.0

 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.

✅ 2008 – Python 3.0

 Known as "Python 3000" or "Py3k".


 Not backward-compatible with Python 2.
 Introduced print() function, better Unicode handling, and new syntax.

🔄 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.

In this guide, we will cover:

Getting Started with Python

Python is a versatile, high-level programming language that is widely


supported across all major operating systems.

You can run Python on your computer using the following two methods:

 Run Python online

 Install Python on your computer

In this tutorial, you will learn both methods.

Run Python Online

To execute Python code, you need to have a Python interpreter installed on


your system. However, if you want to start immediately, you can use our
free online Python editor.
The online editor enables you to run Python code directly in your browser—
no installation required.

Install Python on Your Computer

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

To install Python on your Windows, just follow these steps:

1. Install VS Code

2. Download Python Installer File

3. Run the Installer

4. Install Python

5. Verify your installation

Here is a detailed explanation of each of the steps:

Step 1: Install VS Code

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.

Click Finish to complete the installation process

Step 2: Download the Python Installer File


Go to the official Python website and download the latest version (Python
3.12.2 at the time of writing this tutorial) for Windows.

The website automatically detects your operating system and gives you the
right installer.

Step 3: Run the 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.

Simply allow it and proceed.

Step 4: Install Python

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.

 Check on Add python.exe to PATH as it ensures Python is added to


our system's PATH variable.(Recommended)

 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.

You should see Hello World printed to the command prompt.

Note: Type python3 in command prompt for macOS and Linux.

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.

Your First Python Program

In the previous tutorial, you learned how to install Python on your computer.
Now, let's write a simple Python program.

The following program displays Hello, World! on the screen.

print("Hello, World!")
Output

Hello World!

Note: A Hello World! program includes the basic syntax of a programming


language and helps beginners understand the structure before getting
started. That's why it is a common practice to introduce a new language
using a Hello World! program.

Working of the Program

Congratulations on writing your first Python program. Now, let's see how the
above program works.

In Python, anything inside print() is displayed on the screen.

There are two things to note about print():

 Everything we want to display on the screen is included inside the


parentheses ().

 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!")

o be consistent, we will be using double quotes throughout the tutorials.

Next, we will be learning about Python comments.

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)

Here, # print a number is a comment.

Comments are completely ignored and not executed by code editors.

Important: The purpose of this tutorial is to help you understand comments,


so you can ignore other concepts used in the program. We will learn about
them in later tutorials.

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

n the above example, we have used three single-line comments:

 # 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

Note: Remember the keyboard shortcut to apply comments. In most text


editors, it's Ctrl + / if you are on Windows & Cmd + / if you are on a Mac.
Multiline Comments

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.

Let's look at an example.

# This is an example of a multiline comment

# created using multiple single-line commenced

# The code prints the text Hello World

print("Hello, World!")

We can also use multiline strings as comments like:

'''This is an example

of multiline comment'''

print("Hello, World!")

Output

Hello World

Note: Remember you will learn about these programming concepts in


upcoming tutorials. For now. you can just focus on the usage of comments.

Prevent Executing Code Using Comments

Comments are valuable when debugging code.

If we encounter an error while running a program, instead of removing code


segments, we can comment them out to prevent execution. For example,

number1 = 10

number2 = 15

sum = number1 + number2

print("The sum is:", sum)

print("The product is:", product)


Here, the code throws an error because we have not defined
a product variable. Instead of removing the line causing an error, we can
comment it.

For example,

number1 = 10

number2 = 15

sum = number1 + number2

print("The sum is:", sum)

# print('The product is:', product)

Output

The sum is 25

Here, the code runs without any errors.

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.

Why Use Comments?

We should use comments:

 For future references, as comments make our code readable.

 For debugging.

 For code collaboration, as comments help peer developers to


understand each other's code.

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

In programming, a variable is a container (storage area) to hold data. For


example,

number = 10

Here, number is a variable storing the value 10.

Assigning values to Variables in Python

As we can see from the above example, we use the assignment


operator = to assign a value to a variable.

# assign value to site_name variable

site_name = 'Facebook'

print(site_name)

# Output: Facebook

Output

Facebook

In the above example, we assigned the value Facebook to


the site_name variable. Then, we printed out the value assigned
to site_name

Note: Python is a type-inferred language, so you don't have to explicitly


define the variable type. It automatically knows that Facebook is a string and
declares the site_name variable as a string.

Changing the Value of a Variable in Python

site_name = 'Hospital'

print(site_name)

# assigning a new value to site_name

site_name = 'apple.com'
print(site_name)

Output

Hospital

apple.com

Here, the value of site_name is changed from 'Hosital' to 'apple.com'.

Example: Assigning multiple values to multiple variables

a, b, c = 5, 3.2, 'Hello'

print (a) # prints 5

print (b) # prints 3.2

print (c) # prints Hello

If we want to assign the same value to multiple variables at once, we can do


this as:

site1 = site2 = 'Asif'

print (site1) # prints programiz.com

print (site2) # prints programiz.com

Here, we have assigned the same string value 'Asif' to both the
variables site1 and site2.

Rules for Naming Python Variables

1. Constant and variable names should have a combination of letters in


lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an
underscore (_). For example:

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

5. Python is case-sensitive. So num and Num are different variables. For


example,

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

Literals are representations of fixed values in a program. They can be


numbers, characters, or strings, etc. For example, 'Hello,
World!', 12, 23.0, 'C', etc.

Literals are often used to assign values to variables or constants. For


example,

site_name = 'My Name is Asif'

In the above expression, site_name is a variable, and 'My Name is Asif' is a


literal.

There are different types of literals in Python. Let's discuss some of the
commonly used types in detail.

Python Numeric Literals

Numeric Literals are immutable (unchangeable). Numeric literals can belong


to 3 different numerical types: Integer, Float, and Complex.

1. Integer Literals

Integer literals are numbers without decimal parts. It also consists of


negative numbers. For example, 5, -11, 0, 12, etc.

2. Floating-Point Literals

Floating-point literals are numbers that contain decimal parts.


Just like integers, floating-point numbers can also be both positive and
negative. For example, 2.5, 6.76, 0.0, -9.45, etc.

3. Complex Literals

Complex literals are numbers that represent complex numbers.

Here, numerals are in the form a + bj, where a is real and b is imaginary. For
example, 6+9j, 2+3j.

Python String Literals

In Python, texts wrapped inside quotation marks are called string literals..

"This is a string."

We can also use single quotes to create strings.

'This is also a string.'

Python Type Conversion

In programming, type conversion is the process of converting data of one


type to another. For example: converting int data to str.

There are two types of type conversion in Python.

 Implicit Conversion - automatic type conversion

 Explicit Conversion - manual type conversion

Python Implicit Type Conversion


In certain situations, Python automatically converts one data type to another.
This is known as implicit type conversion.

Example 1: Converting integer to float


Let's see an example where Python promotes the conversion of the lower
data type (integer) to the higher data type (float) to avoid data loss.
integer_number = 123

float_number = 1.23
new_number = integer_number + float_number

# display new value and resulting data type

print("Value:",new_number)

print("Data Type:",type(new_number))

Output

Value: 124.23

Data Type: <class 'float'>

In the above example, we have created two


variables: integer_number and float_number of int and float type
respectively.

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.

 Python has a solution for these types of situations which is known as


Explicit Conversion.

Explicit Type Conversion


In Explicit Type Conversion, users convert the data type of an object to
required data type.

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

print("Data type of num_string before Type Casting:",type(num_string))

# explicit type conversion

num_string = int(num_string)

print("Data type of num_string after Type Casting:",type(num_string))

num_sum = num_integer + num_string

print("Sum:",num_sum)

print("Data type of num_sum:",type(num_sum))

Output

Data type of num_string before Type Casting: <class 'str'>

Data type of num_string after Type Casting: <class 'int'>

Sum: 35

Data type of num_sum: <class 'int'>

In the above example, we have created two


variables: num_string and num_integer with str and int type values
respectively. Notice the code,

num_string = int(num_string)

Here, we have used int() to perform explicit type conversion of num_string to


integer type.
After converting num_string to an integer value, Python is able to add these
two variables.

Finally, we got the num_sum value i.e 35 and data type to be int.

Key Points to Remember

1. Type Conversion is the conversion of an object from one data type to


another data type.

2. Implicit Type Conversion is automatically performed by the Python


interpreter.

3. Python avoids the loss of data in Implicit Type Conversion.

4. Explicit Type Conversion is also called Type Casting, the data types of
objects are converted using predefined functions by the user.

5. In Type Casting, loss of data may occur as we enforce the object to a


specific data type.

Python Basic Input and Output

Python Output

In Python, we can simply use the print() function to print output. For
example,

print('Python is powerful')

# Output: Python is powerful

You might also like