0% found this document useful (0 votes)
17 views13 pages

Python Installation and Basics Guide

This document provides an introduction to Python, covering its features, installation steps on Windows, and how to run Python programs using both interactive and script modes. It explains Python's syntax, identifiers, variables, data types, and the concept of immutability, particularly focusing on numeric and string types. Additionally, it outlines the importance of indentation and reserved keywords in Python programming.

Uploaded by

Kailas Rahane
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views13 pages

Python Installation and Basics Guide

This document provides an introduction to Python, covering its features, installation steps on Windows, and how to run Python programs using both interactive and script modes. It explains Python's syntax, identifiers, variables, data types, and the concept of immutability, particularly focusing on numeric and string types. Additionally, it outlines the importance of indentation and reserved keywords in Python programming.

Uploaded by

Kailas Rahane
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit 1

Introduction and Syntax of Python Program


MARKS 8

Python
Python is an interpreted, object-oriented, high-level programming language with dynamic
semantics.
Python is designed to be highly readable.
It uses English keywords frequently where as other languages use punctuation, and it has fewer
syntactical constructions than other languages.

Created by : Guido van Rossum, and first released on February 20, 1991.
Named from :- BBC television comedy sketch series called Monty Python's Flying Circus.
Visit:-[Link]

 Getting Python

Windows Installation
Q] Write the steps to install Python on Windows Machine?
 Open a Web browser and go to official website of python [Link]
 Follow the link for the Windows installer [Link] file where XYZ is the version you need to
install.
 Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just
accept the default settings, wait until the install is finished, and you are done.

ARROW COMPUTER ACADEMY PWP Unit 1 Prof. Somwanshi A.A.(8788335443)


PATH variable
The PATH variable is a list of directories where each directory contains the executable file for a
command.
When a command is entered into the Windows command prompt, the prompt searches in the PATH
variable for an executable file with the same name as the command; in the case that the required file
is not found, it responds with an error message that states that the specified command was not
recognized.

How to add Python to PATH variable in Windows:-


C:\Users\Admin\AppData\Local\Programs\Python\Python311
C:\Users\Admin\AppData\Local\Programs\Python\Python311\Scripts

To check whether installed: -


Go to command prompt and type python - -version.

Ways to run python program:


o Using Interactive interpreter prompt
o Using a script file

1. Interactive interpreter prompt


Python provides us the feature to execute the Python statement one by one at the interactive prompt.
It is preferable in the case where we are concerned about the output of each line of our Python
program.
To open the interactive mode,
1. open the terminal (or command prompt) and type python.
2. Then simply type the Python statement on >>> prompt.
As we type and press enter we can see the output in the very next line.

ARROW COMPUTER ACADEMY PWP Unit 1 Prof. Somwanshi A.A.(8788335443)


Disadvantages of interactive mode
 The interactive mode is not suitable for large programs.
 The interactive mode doesn’t save the statements. Once we make a program it is for that time
itself, we cannot use it in the future. In order to use it in the future, we need to retype all the
statements.
 Editing the code written in interactive mode is a tedious task. We need to revisit all our previous
commands and if still, we could not edit we need to type everything again.

2. Using a script file (Script Mode Programming)


In the script mode, a python program can be written in a file.
This file can then be saved and executed using the command prompt.
We can view the code at any time by opening the file and editing becomes quite easy as we can open
and view the entire code as many times as we want.
Using the script mode, we can write multiple lines code into a file which can be executed later.
It is much preferred over interactive mode by experts in the program.
For this purpose, we need to open an editor like notepad, create a file named and save it
with .py extension, which stands for "Python".

The file made in the script mode is by default saved in the Python installation folder.

Step - 1: Open the Python interactive shell, and click "File" then choose "New", it will open a new
blank script in which we can write our code.
Step -2: Now, write the code and press "Ctrl+S" to save the file with .py extension.
Step - 3: After saving the code, we can run it by clicking "Run" or "Run Module". It will display the
output to the shell.
Step - 4: Apart from that, we can also run the file using the operating system terminal. But, we
should be aware of the path of the directory where we have saved our file.

o Open the command line prompt and navigate to the directory.


o We need to type the python keyword, followed by the file name and hit enter to run the
Python file.

ARROW COMPUTER ACADEMY PWP Unit 1 Prof. Somwanshi A.A.(8788335443)


Features of Python
Q1: What are the key features of Python? [4 M]
Features of Python
 Python is Interpreted − Python is processed at runtime by the interpreter. Interpreted in simple
terms means running code line by line. It also means that the instruction is executed without
earlier compiling the whole program into machine language.
 Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
 Python is Object-Oriented − Python supports Object-Oriented style or technique of programming
that encapsulates code within objects.
 Python is a Beginner's Language − Python is a great language for the beginner-level programmers
and supports the development of a wide range of applications from simple text processing to WWW
browsers to games.
 Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This
allows the student to pick up the language quickly.
 Easy-to-read − Python code is more clearly defined and visible to the eyes. Indentation used
instead of curly braces in Python makes it very easy to read Python code.
 Easy-to-maintain − Python's source code is fairly easy-to-maintain.
 A broad standard library − Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
 Portable − Python can run on a wide variety of hardware platforms and has the same interface on
all platforms.
 Extendable − You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
 Databases − Python provides interfaces to all major commercial databases.
 GUI Programming − Python has plenty of frameworks for developing GUIs that deliver a high-
quality user experience

 Python building blocks


1. Python Identifiers
Variable name is known as identifier.
The rules to name an identifier are given below.
 The first character of the variable must be an alphabet or underscore ( _ ).
 All the characters except the first character may be an alphabet of lower-case(a-z), upper-case
(A-Z), underscore or digit (0-9).

 Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &, *).
 Identifier name must not be similar to any keyword defined in the language.
 Identifier names are case sensitive for example myname, and MyName is not the same.
 Examples of valid identifiers : a123, _n, n_9, etc.
 Examples of invalid identifiers: 1a, n%4, n 9, etc.

ARROW COMPUTER ACADEMY PWP Unit 1 Prof. Somwanshi A.A.(8788335443)


2. Variables
Variables are used to store data, they take memory space based on the type of value we assigning to
them.
Creating variables in Python is simple, you just have write the variable name on the left side of = and
the value on the right side.

 Python Variable Example


num=10
name='Arrow'
print(num)
print(name)

 Multiple Assignment Examples

You can assign values to multiple variables on one line.

 Assign the same value to multiple variables

x = y = z = 99
print(x)
print(y)
print(z)

 Assign multiple values to multiple variables


a, b, c = 5, 6, 7
print(a)
print(b)
print(c)

It is also possible to assign multiple values to multiple variables of different types


num, name , marks = 10, 'Arrow' , 20.5
print(num)
print(name)
print(marks)

If there is one variable on the left side, it is assigned as a tuple.


num = 10, 20, 30
print(num)
print(type(num))

Output: (10, 20, 30)


<class 'tuple'>
If the number of variables on the left and the number of values on the right do not match,
a ValueError will occur.

ARROW COMPUTER ACADEMY PWP Unit 1 Prof. Somwanshi A.A.(8788335443)


Example 1:
a,b = 10, 20, 30
print(a)
Output: ValueError: too many values to unpack (expected 2)

Example 2:
a,b,c = 10, 20
print(a)
Output: ValueError: not enough values to unpack (expected 3, got 2)

Plus and concatenation operation on the variables


x = 10
y = 20
print(x + y)
p = "Hello"
q = "World"
print(p + " " + q)

output:
30
Hello World

Comments
Use the hash (#) symbol to start writing a comment.
1. #This is a comment
2. #print out Hello
3. print('Hello')

Multi-line comments

use triple quotes, either ''' or """.


eg:
1. """This is also a
2. perfect example of
3. multi-line comments""”

3. Reserved Words
The following list shows the Python keywords. These are reserved words and cannot use them as
constant or variable or any other identifier names.

The True and False Keywords


The True keyword is used as the Boolean true value in Python code. The Python keyword False is
similar to the True keyword, but with the opposite Boolean value of false. In other programming
languages, you’ll see these keywords written in lowercase (true and false), but in Python they are
always written in uppercase.

ARROW COMPUTER ACADEMY PWP Unit 1 Prof. Somwanshi A.A.(8788335443)


False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not

4. Indentation
Python provides no braces to indicate blocks of code for class and function definitions or flow
control.
Blocks of code are denoted by line indentation, which is compulsory.
The number of spaces in the indentation is variable, but all statements within the block must be
indented the same amount.

Exampl 1: −
if True:
print "True"
print “Hello”
else:
print "False"
Thus, in Python all the continuous lines indented with same number of spaces would form
a block.

Exampl 2: −
a=20
b=40
if a>b:
print("if Block");
print("A is greater than b");
else:
print("Else Block")
print("A is less than b")

ARROW COMPUTER ACADEMY PWP Unit 1 Prof. Somwanshi A.A.(8788335443)


Python Data Types
Python considers everything to be an object. A unique id is assigned to it when we instantiate an
object. We cannot modify the type of object, but we may change its value.
For example, if we set variable a to be a list, we can't change it to a tuple/dictionary, but we may
modify the entries in that list.
In Python, there are two kinds of objects

Immutable Objects in Python


Immutable datatypes are objects that cannot be modified or altered after they have been created
(for example, by adding new elements, removing elements, or replacing elements).
When you make changes to immutable objects, the memory where they were stored during
initialization is updated.
1. Numeric
2. String
3. Tuple

1. Numeric:
Numeric Data-types are the data-type which represent the numeric values.
It can be any number from the -infinity to +infinity.
Numeric data-types are subdivided into three types:
1. Integer
2. Float
3. Complex Number

Integers – This value is represented by int class.


It contains positive or negative whole numbers (without fraction or decimal).
In Python3 is no limit to how long an integer value can be.

Float – This value is represented by float class.


It is a real number with floating point representation.
It is specified by a decimal point.
A trailing decimal point is used to ensure that a variable is a float rather than an integer, even if it is a
whole number.

# printing the type of input numbers


number_1 = 10
print("Type of 10:", type(number_1))
number_2 = 8.
print("Type of 8. :", type(number_2))
Output
On executing, the above program will generate the following output –
Type of 10: <class 'int'>
Type of 8. : <class 'float'>

ARROW COMPUTER ACADEMY PWP Unit 1 Prof. Somwanshi A.A.(8788335443)


Complex Numbers –
Complex number is represented by complex class.
It is specified as (real part) + (imaginary part)j.
For example – 2+3j
Python uses A+Bj notation to represent complex number meaning python will recognize 3+4j as a
valid number but 3+4i is not valid.

Note – type() function is used to determine the type of data type.

# Python program to demonstrate numeric value


#create a variable with integer value.
a=100
print("The type of variable having value", a, " is ", type(a))

#create a variable with float value.


b=10.2345
print("The type of variable having value", b, " is ", type(b))

#create a variable with complex value.


c=100+3j
print("The type of variable having value", c, " is ", type(c))

Output:
The type of variable having value 100 is <class 'int'>
The type of variable having value 10.2345 is <class 'float'>
The type of variable having value (100+3j) is <class 'complex'>

Creating Complex Data Type Using complex()


We can create complex number from two real numbers.
Syntax for doing this is:
c = complex(a,b)
Where, a & b are of real data types and c will be of complex data types.

a=5
b=7
c=complex(a,b)
print(c)

Output:
(5+7j)
After creating complex data type, we can access real and imaginary part using built-in data
descriptors real and imag.
a = 5+6j
print ([Link])
print ([Link])

ARROW COMPUTER ACADEMY PWP Unit 1 Prof. Somwanshi A.A.(8788335443)


Why int data type is immutable ?
Since the int data type is immutable, we cannot modify or update it.
As previously stated, immutable objects change their memory address when they are updated.
We can get an address of particular object using the id() function.

Example
num = 5
print('Before updating, memory address = ', id(num))
num = 10
print('After updating, memory address = ', id(num))

Output:
Before updating, memory address = 140707680281512
After updating, memory address = 140707680281672

string
A string is a data structure in Python that represents a sequence of characters.
It is an immutable data type, meaning that once you have created a string, you cannot change
it.
Strings are used widely in many different applications, such as storing and manipulating text data,
representing names, addresses, and other types of data that can be represented as text.
We use single quotes or double quotes to represent a string in Python.
For example,
# create a string using double quotes
string1 = "Python programming"
# create a string using single quotes
string1 = 'Python programming'

Here, we have created a string variable named string1. The variable is initialized with the
string Python Programming.
Python does not have a character data type, a single character is simply a string with a length of
1.
Example: Python String
# create string type variables
name = "Python"
print(name)
message = "I love Python."
print(message)

ARROW COMPUTER ACADEMY PWP Unit 1 Prof. Somwanshi A.A.(8788335443)


Access String Characters in Python
We can access the characters in a string in three ways.

 Indexing: One way is to treat strings as a list and use index values.

For example,
greet = 'hello'
# access 1st index element
print(greet[1]) # "e"
Run Code
Negative Indexing: Similar to a list, Python allows negative indexing for its strings.
For example,
greet = 'hello'
# access 4th last element
print(greet[-4]) # "e"

Slicing: Access a range of characters in a string by using the slicing operator colon :. For example,
greet = 'Hello'
str = 'Hello World!'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string

Note: If we try to access an index out of the range or use numbers other than an integer, we will get
errors.

Python Strings are immutable


In Python, strings are immutable. That means the characters of a string cannot be changed.
For example,
message = 'Arrow Academy'
message[0] = 'H'
print(message)

Output

TypeError: 'str' object does not support item assignment

ARROW COMPUTER ACADEMY PWP Unit 1 Prof. Somwanshi A.A.(8788335443)


However, we can assign the variable name to a new string. For example,
message = 'Hello Arrow'
# assign new string to message variable
message = 'Hello Friends'
print (message); # prints "Hello Friends"

Python Multiline String


We can also create a multiline string in Python. For this, we use triple double quotes """ or triple
single quotes '''. For example,
# multiline string
message = """
Never gonna give you up
Never gonna let you down
"""
print(message)

Python String Operations


There are many operations that can be performed with strings which makes it one of the most
used data types in Python.

1. Compare Two Strings


We use the == operator to compare two strings. If two strings are equal, the operator returns True.
Otherwise, it returns False. For example,
str1 = "Hello, world!"
str2 = "I love Python."
str3 = "Hello, world!"

# compare str1 and str2


print(str1 == str2)

# compare str1 and str3


print(str1 == str3)

Output
False
True
In the above example,
str1 and str2 are not equal. Hence, the result is False.
str1 and str3 are equal. Hence, the result is True.

2. Join Two or More Strings


In Python, we can join (concatenate) two or more strings using the + operator.
greet = "Hello, "
name = "Jack"

ARROW COMPUTER ACADEMY PWP Unit 1 Prof. Somwanshi A.A.(8788335443)


# using + operator
result = greet + name
print(result)

# Output: Hello, Jack

In the above example, we have used the + operator to join two strings: greet and name.

Iterate Through a Python String


We can iterate through a string using a for loop. For example,
greet = 'Hello'

# iterating through greet string


for letter in greet:
print(letter)

Output
H
e
l
l
o

Python String Length


In Python, we use the len() method to find the length of a string. For example,
greet = 'Hello'
# count length of greet string
print(len(greet))
# Output: 5

String Membership Test


We can test if a substring exists within a string or not, using the keyword in.

print('a' in 'program') # True


print('at' not in 'battle')#False

Mutable Objects in Python


Objects that can change their internal state (the data/content inside the objects), i.e. they can be
changed using predefined functions or methods,
1. List
2. Dictionary
3. Set

ARROW COMPUTER ACADEMY PWP Unit 1 Prof. Somwanshi A.A.(8788335443)

You might also like