Python_UNIT1_Finalversion
Python_UNIT1_Finalversion
UNIT-I
Python was first released in 1991, and its initial purpose was to serve as a scripting language
for UNIX/C programmers. The language quickly gained popularity due to its simplicity, ease of
use, and readability, and it was adopted by many programmers and organizations around the
world.
Today, Python is widely used in a variety of applications, including web development, scientific
computing, data analysis, artificial intelligence and machine learning, and more. Its popularity
continues to grow, and it is considered to be one of the most popular programming languages
in the world.
1. Easy-to-learn syntax: Python has a simple and easy-to-learn syntax that makes it an
excellent language for beginners to learn programming.
2. Object-oriented programming: Python supports object-oriented programming, which
allows developers to write code that is modular, reusable, and easy to maintain.
3. Easy to learn and Read
Python code looks like simple English words. There is no use of semicolons or brackets, and
the indentations define the code block. You can tell what the code is supposed to do simply
by looking at it.
4. Easy to maintain: Python’s source code is fairly easy to maintain
5. Python is interpreted: When a programming language is interpreted, it means that the
source code is executed line by line, and not all at once. Programming languages such as
C++ or Java are not interpreted, and hence need to be compiled first to run them. There is
no need to compile Python because it is processed at runtime by the interpreter.
6. Interactive Mode: In the interactive mode as we enter a command and press enter, the
very next step we get the output. Interactive mode is very convenient for writing very
short lines of code. [FYI: The other mode is Script mode a python program can be written
in a file. This file can then be saved and executed using the command prompt.]
7. A broad standard library: Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
8. Python is Interactive: One can enter through python prompt with the interpreter directly
to write programs
9. Portable: Python can run on various hardware/software platforms and has same interface
on all platforms.
10. Extendable: One can add low level-modules to the python interpreter. These modules
enable programmers to add or customize their tools more efficiently.
Sahana patil | |VHD college
3
1.1.5 identifiers
A Python identifier is a name used to identify a variable, function, class, module orother object.
Rules of identifiers:
1. An identifier starts with a letter A to Z or a to z or an underscore(_)
2. If the identifier name is more than one character, the first character may be followed by zero
or more letters, underscores and digits (0 to 9).
3. Keyword cannot be used as identifier names
4. Python does not allow punctuation characters such as @, $, and % within identifiers.
5. Python is a case sensitive programming language.
Thus, Manpowerand manpower are two different identifiers in Python.
1.1.6. Keywords
• A python keyword is a reserved word which you can’t use as a name of your variable,
class, function etc.
• These keywords have a special meaning and theyare used for special purposes in
Python programming language. For example– Python keyword “while” is used for
while loop thus you can’t name a variable withthe name “while” else it may cause
compilation error.
• All the keywords contain lower case letters only except True, False and None.
• The following code can retrieve the keywords in python at the prompt:
>> import keyword
>>print(keyword. kwlist)
[FYI]
Here's what each line of the code does:
1. import keyword - This line imports the keyword module into the current Python session.
The keyword module provides a list of all the keywords in the Python language.
2. print(keyword.kwlist) - This line prints out the list of Python keywords using the kwlist
attribute of the keyword module. The kwlist attribute contains a list of all the keywords
in Python.
When you run this code, you should see a list of the following keywords printed out to the
console:
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del',
'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal',
'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
For example, the following code creates a list of numbers on a single line:
numbers = [1, 2, 3, 4, 5]
The same list can also be created over multiple lines using parentheses:
numbers = (
1,
2,
3,
4,
5
)
Indentation: Unlike many other programming languages that use curly braces or other symbols
to delimit blocks of code, Python uses indentation.
• Indentation is used to indicate the scope of statements within a block of code.
• For example, the following code defines a function called multiply that takes two
arguments:
def multiply(x, y):
result = x * y
return result
• Here the result variable and the return statement are indented under the def
statement. This indentation tells Python that these statements are part of the
function's code block.
• Indentation must be consistent throughout a Python program. Typically, four spaces
are used for each level of indentation. Mixing tabs and spaces for indentation is not
allowed and can lead to errors in your code.
1.1.8 Statements
• Python allows the line continuation character(\) to denote that the line should
continue.
For example:
>>>> a=1+2+3+\
4+5+6
>>>>print(a)
Statements contained within the [] ,(),{} brackets do not need to use the line continuation
character.
>>>>a=(1+2+
3+4)
>>>>colors=[‘red’,’blue’,
‘green’]
• Comments in python describes what the source code has done. They are for
programmers to have better understanding of a program.
• It explains the basic logic behind why a particular line of code was written. Comments
can be used to prevent execution when testing code.
• Comments in Python are identified with a hash symbol, #, and extend to the end of the
line. Hash characters in a string are not considered comments, however. There are
three ways to write a comment - as a separate line, beside the corresponding statement
of code, or as a multi-line comment block.
Single-Line Comments
• Single-line comments begin with the “#” character. Anything that is written in a single
line after ‘#’ is considered as a comment.
• The syntax for writing single-line comments is:
# comments here
Multi-Line Comments
• Multiline comments can also be given as triple quoted string.
• It can also be used for long comments in code.
• As the name suggests its syntax consists of three consecutive single or double-quotes.
1.1.11 Variables
1. Variable is a name which is used to refer memory location.
2. Python variable is also known as an identifier and used to hold value.
3. Python has no command for declaring a variable.
4. A variable is created the moment the value has been assigned to it.
5. In Python, we don't need to specify the type of variable because Python is a infer language
and smart enough to get variable type.
6. Variable names can be a group of both the letters and digits, but they have to begin with a
letter or an underscore.
7. It is recommended to use lowercase letters for the variable name. Rahul and rahul both are
two different variables.
Variable assignment
variables do not need to be declared with any particular type, and can even change type after
they have been set.
x=4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Multiple assignment: Python allows you to assign values to multiple variables in one line:
Example 1:
>>>x, y, z = "Orange", "Banana", 10
print(x)
print(y)
print(z)
Example2:
>>>x=y=z=10
print(x)
print(y)
print(z)
• Python print() function prints the message to the screen or any other standard
output device.
• The Syntax of print function is:
print(EXPRESSION)
Here EXPRESSION is the variable of any data type or string value that we
want to display.
• print() automatically inserts a new line character at the end.
• String values:
print(“welcome to python”) // pair of double quotes
print(‘welcome to python’) // pair of single quotes
• Numeric values :
print(10) //Integer
print(2.55) //float value
Sahana patil | |VHD college
8
• Python provides built-in functions to read a line of text from standard input, which by
default comes from the keyboard. These functions are raw_input function is not
support by python3.
• The syntax for input() is: Input([prompt])
• Example:
Number=input(“Enter a number:”);
Print(“The number is:”,number)
Output:
Enter a number :20
The number is:20
Import statement
“Segments of code” frequently used are stored in a module. The module contains python
definitions and statements with the extension .py. These definition’s inside a module can be
imported to another module with the help of the ‘import’ keyword.
Example:
>> import math
>> print(math.pi)
1.1.13 Operators
Operators are used to perform operations on variables and values.
sum=b+c here b and c are called the operands and + = are called operators
Python contains the following set of operators
1.Airthmetic operators
2.comparison operators
3.Logical operators
4.Bitwise operators
5.Assignment operators
6.Identity operators
7.Membership operators
1.Airthmetic operators: Arithmetic operators are used with numeric values to perform
common mathematical operations:
<= Less than or x <= y True if the left operand is less than
equal to or equal to the right
3.Logical Operators: A logical operator are used to connect two or more conditional statements
or expressions. They return Boolean result either True or False.
4.Bitwise Operators: bitwise operators are used to perform bitwise calculations on integers.
The integers are first converted into binary and then operations are performed on each bit or
corresponding pair of bits, hence the name bitwise operators. The result is then returned in
decimal format.
& Bitwise AND Result bit 1, if both operand bits are 1; otherwise, results
bit 0.
| Bitwise OR Result bit 1, if any of the operand bit is 1; otherwise,
results bit 0.
^ Bitwise XOR Results bit 1, if any of the operand bit is 1 but not both,
otherwise results bit 0.
~ Bitwise NOT inverts individual bits ~x
<< Zero fill left The left operand’s value is moved toward left by the
shift or Bitwise number of bits
left shift
>> Signed right The left operand’s value is moved toward right by the
shift or Bitwise number of bits specified by the right operand.
right shift
= Simple Assignment
+= Addition assignment
-= Subtraction assignment
*= Multiplication
assignment
/= Division assignment
%= Modulus assignment
**= Exponentiation
assignment
6.Identity Operators: We use identity operators to compare the memory location of two
objects.
is not x is not y This returns True if both variables are not the same object
7.Membership Operators:
Operator Description
in Returns True if a sequence with the specified value is present in the object
not in Returns True if a sequence with the specified value is not present in the object
x not in y
Operators Meaning
() Parentheses
** Exponent
+, - Addition, Subtraction
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not Comparisons, Identity, Membership operators
in
or Logical OR
Ex:122.3 +12j,34.3j+1
Random numbers: Python has a built-in module called random that can be used to generate
random numbers. For example, refer python lab manual
2. String:
•A tuple is an ordered sequence of items same as list. The difference here is that tuples
are immutable.i.e. e once created, cannot be modified. We use () to create a tuple in
python.
Ex: colors =(“blue”,12)
5. Dictionary:
• It is an unordered collection of items.It stores elements in key/value pairs.
• Keys are unique identifiers that are associated with each value.
• Ex: create a dictionary named capital_city
City={‘karnataka’:‘bangalore’,’nepal’:’kathmandu’}
Here the keys are Karnataka and Nepal .values are bangalore and Kathmandu.
6. Set:
• It is an unordered collection of unique items .
• Ex: emp_id={411,122,123,124,122}
• And as mentioned earlier, the variable assignment never comes with a type definition
since the type is stored with objects and not with variables/names.
• Every time a variable is identified, it automatically gets replaced with the object in
memory it references.
Statement Description
If Statement The if statement is used to test a specific condition. If the condition is true, a
block of code (if-block) will be executed.
If-else statement The if-else statement is similar to if statement except the fact that, it also
provides the block of the code for the false case of the condition to be
checked. If the condition provided in the if statement is false, then the else
statement will be executed.
Syntax
if number==10:
elif expression 2:
# block of statements print("number is equals to 10")
else:
Flow charts:
If statement if else statement
1.2.2 Looping
Python For Loops
• For loop is used to repeat the execution of a block of code for a fixed number of times.
• A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary,
a set, or a string).
• With the for loop we can execute a set of statements, once for each item in a list, tuple,
set etc.
Synatx1:
for variable in range (val1,val2,inr):
#block of statements
In the above statement val1 and val2 represents the minimum and maximum number of the
specified range. The inr represents the increment value
Example:
a=int(input(“Enter the number:”))
for i in range(a):
Print(i)
Output:
0
1
2
Synatx2:
for item in sequence:
#body of for loop
• Item is the variable that takes the value of the item inside the sequence of each iteration.
The sequence can be a list, tuple, string, set etc.
• Loop continues until we reach the last item in the sequence.
1. Example
Print i as long as i is less than 6:
i=1
while i < 6:
print(i)
i += 1
The while loop requires relevant variables to be ready, in this example we need to define an
indexing variable, i, which we set to 1.
Example
Exit the loop when i is 3:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
Break Statements
The break statement in Python is used to terminate or abandon the loop containing the
statement and brings the control out of the loop. It is used with both the while and the for loops,
especially with nested loops (loop within a loop) to quit the loop. It terminates the inner loop
and control shifts to the statement in the outer loop.
Code:
age = “\n Please enter your age: ”
while True:
age = input
if age >= 18:
break
else:
print (“You’re not eligible to vote”)
Output:
Please enter your age: 17 You’re not eligible to vote
Please enter your age: 18
In the above example, if the age entered is equal to or more than 18, it breaks out of the loop.
Continue Statements:
When a program encounters a continue statement in Python, it skips the execution of the current
iteration when the condition is met and lets the loop continue to move to the next iteration. It
is used to continue running the program even after the program encounters a break during
execution.
Code
for letter in 'Flexi ple':
if letter == ' ':
continue
print ('Letters: ', letter)
Output:
Letters: F
Letters: l
Letters: e
Letters: x
Letters: i
Letters: p
Letters: l
Letters: e
In this example, the program will skip the space ‘ ‘ in the word and continue with the rest of the
iteration.
Pass Statements
The null statement is another name for the pass statement.
We can use the pass statement as a placeholder when unsure what code to provide. So, we only
have to place the pass on that line. Pass may be used when we don't wish any code to be
executed.
We can simply insert a pass in places where empty code is prohibited, such as loops, functions,
class definitions, or if-else statements.
Example of the Pass Statement
Code
Question Bank
1. Python is an interpreted language-Justify.
2. What are the key features of python?
3. What is the role of indentation in python? Explain with an example.
4. List few applications of python.
5. How do you write comments in python?
6. What is the difference between intermediate mode and script mode?
7. What are the rules of naming a variable?
8. What are keywords?
9. What are the rules for writing an identifier?
10. List the standard data types in Python.
11. What are the mutable and immutable data types? Give examples.
12. What are the python strings?
13. Write a short note on IDLE.
14. Explain Operator precedence and associativity.
15. Explain conditional statements.
16. Explain python looping statements.
17. Illustrate interpreter and interactive mode in python with an example.