Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Python Introduction

This document provides an overview of the basics of Python programming, including its history, features, data types, variables, and control statements. It covers various operators such as arithmetic, assignment, comparison, logical, and bitwise operators, as well as the concept of literals and identifiers. The content is structured into units that facilitate understanding of Python's programming fundamentals.

Uploaded by

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

Python Introduction

This document provides an overview of the basics of Python programming, including its history, features, data types, variables, and control statements. It covers various operators such as arithmetic, assignment, comparison, logical, and bitwise operators, as well as the concept of literals and identifiers. The content is structured into units that facilitate understanding of Python's programming fundamentals.

Uploaded by

dk23mer1r12
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Unit -I

BASICS OF PYTHON PROGRAMMING AND CONTROL


STATEMENTS

Presented by Sri D Kishore babu, M.Tech, MISTE.,

DEPARTMENT OF MECHANICAL ENGINEERING


Contents

01 Features and History of python

02 Literal Constant, Data types, Variables. Operators and input operation

03 Conditional and un conditional branching, Iterative statements

04 Nesting of decision control statements and loops

Programs
05

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


1.
Features and History of python

Python was developed (1990)by Guido Van


Rossum, at National Research Institute for
Mathematics and Computer Science in
Netherlands.

Python was conceived in the late 1980s and its implementation was started in December
1989 by Guido van Rossum at CWI in the Netherlands as a successor to the ABC
programming language capable of exception handling and interfacing with the Amoeba
operating system.

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


1.
Features and History of python

01 High level language 02


Dynamic
programmers don’t need to
With Python, the type of remember the system
the variable can be architecture, nor manage the Dynamic
decided during runtime. memory. This makes it super
This makes Python a programmer-friendly.
dynamically typed Vast
High level
language. support
Interpreted 04 libraries
language
Free Open source 03
Here the source code is
Python is developed executed line by line, and
under an OSI-approved not all at once. There is no
open source license. need to compile Python
because it is processed at
Supports
OOPs
Features Free Open
source
runtime by the interpreter.

Supports OOPs 05 Vast support libraries 06 Interpreted


One of the critical Python has an extensive
Python features is that standard library available
for anyone to use
it supports both object-
oriented and procedure-
oriented programming.
BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS
2.
Literal Constant

Literals in python are nothing but a succinct way of representing the data types. In simpler
words, it is the way to represent a fixed value in our source code.
Ex:
Literals are numbers (or) strings (or)
78 # Integer literal
characters that appears directly in a
21.98 # Floating point literal
program. A list of some literals in
“Q” # Character literal
python is as follows.
“Hello” # String literal
 Numeric Literal: (c): Complex >> a= 7+8j
(b):Float >> print(78.256)
(a): Integer >> x=2586 >> b= 5j
Output: 78.256
>> y= -9856 print(a)
print(x,y) (d):long >> x = 037467 Print(b)
Output: 2586,-9856 print(x) Output: (7+8j)
Output: 5j
BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS
2.
Literal Constant

 String Literals
i. Single-line string ii. Multi-line string

String literals that are enclosed within single A collection of characters (or) a string that goes on
quotes (‘ ‘) are knows as single line string for multiple lines is a multi line string.
This kind of string can be done in two ways
Ex:
(a) Adding backslash at the end of every line
# string literals
# single line literals (b) Using triple quotes
Ex:
Single_quotes_string = ‘ Scaler Academy ’
# string literals
Double_quotes_string = “ Hello world “ Output:
# multi line literals
Prinf(string_quotes_string) Welcome
Str = ”””
Print(double_quotes_string) to
Welcome
Output: scaler
to
scaler Academy Academy
scaler
Hello world
Academy ”””

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


2.
Literal Constant
Ex:
# string literals
Output:
# multi line literals
WelcometoscalerAcademy
Str = “
Welcome \
to \
scaler \
Academy \ ”
print (str)

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


2.
Operator

Operators are symbols, such as +, –, =, >, and < that perform certain mathematical or logical operation
to manipulate data values and produce a result based on some rules. An operator manipulates the
data values called operands

Python language supports a wide range of operators. They are


1 Arithmetic Operators

Consider the expression,


>>> 4 + 6 2 Assignment Operators

where 4 and 6 are operands


3 Comparison Operators
and + is the operator.

4 Logical Operators

5 Bitwise Operators

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


2.
Operator
1 Arithmetic Operators
Arithmetic operators are used to execute arithmetic operations such as addition, subtraction,
division, multiplication etc.
Operator Operator Name Description Example
+ Addition operator Adds two operands, producing their sum. p+q=5
arithmetic operators

− Subtraction operator Subtracts the two operands, producing their difference. p – q = −1


TABLE shows all the

Multiplication
The following

* Produces the product of the operands p*q=6


operator
Produces the quotient of its operands where the left
/ Division operator q / p = 1.5
operand is the dividend and the right operand is the divisor.
Divides left hand operand by right hand operand and
% Modulus operator q%p=1
returns a remainder
** Exponent operator Performs exponential (power) calculation on operators p**q = 8
Floor division 9//2 = 4 and
// Returns the integral part of the quotient.
operator 9.0//2.0 = 4.0
Note: The value of p is 2 and q is 3.

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


2.
Operator
2 Assignment Operators
Assignment operators are used for assigning the values generated after evaluating the right operand to the
left operand. Assignment operation always works from right to left.

Assignment operators are either Simple assignment is done with the equal sign (=) and simply
 simple assignment operator or assigns the value of its right operand to the variable on the left.
 compound assignment operators. For example,

Ex:
1 >>> x = 5 In ➀ you assign an integer value of 5 to variable x.

2 In ➁ an integer value of 1 is added to the variable x on the right side and the
>>> x = x + 1
value 6 after the evaluation is assigned to the variable x.

3 >>> x 6 The latest value stored in variable x is displayed in ➂.

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


2.
Operator
2 Assignment Operators

Compound assignment

Compound assignment operators support shorthand notation for avoiding the repetition of the left-side
variable on the right side. Compound assignment operators combine assignment operator with another
operator with = being placed at the end of the original operator.
For example, the statement
>>> x = x + 1
can be written in a compactly form as shown below.
>>> x += 1

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


2. Table: List of Assignment Operators

Operator Operator Name Description Example


Assigns values from right side operands to left side z = p + q assigns value
= Assignment
operand. of p + q to z
Subtracts the two operands, producing their z += p is equivalent to
+= Addition Assignment
difference. z=z+p
Subtraction Subtracts the value of right operand from the left z −= p is equivalent to
−=
Assignment operand and assigns the result to left operand. z=z–p
Multiplication Multiplies the value of right operand with the left z *= p is equivalent to
*=
Assignment operand and assigns the result to left operand. z=z*p
Divides the value of right operand with the left z /= p is equivalent to
/= Division Assignment
operand and assigns the result to left operand z=z/p
Exponentiation Evaluates to the result of raising the first operand z**= p is equivalent to
**=
Assignment to the power of the second operand. z = z ** p
Produces the integral part of the quotient of its
Floor Division z //= p is equivalent to
//= operands where the left operand is the dividend
Assignment z = z // p
and the right operand is the divisor.
Remainder Computes the remainder after division and assigns z %= p is equivalent to
%=
Assignment the value to the left operand. z=z%p

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


2.

2 Assignment Operators
Ex:
>>> p = 10
>>> q = 12 >>> q **= p
>>> q += p >>> q 1024.0
>>> q 22 >>> q //= p
>>> q *= p >>> q 102.0
>>> q 220
>>> q /= p
>>> q 22.0
>>> q %= p
>>> q 2.0

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


2. 3 Comparison Operators
When the values of two operands are to be compared then comparison operators are used. The output of these comparison operators is
always a Boolean value, either True or False. The operands can be Numbers or Strings or Boolean values. Strings are compared letter by
letter using their ASCII values, thus, “P” is less than “Q”

Operator Operator Name Description Example


Table: List of Comparision Operators

Equal to If the values of two operands are equal,


Note: The value of p is 10 and q is 20

== Equal to (p == q) is not True.


then the condition becomes True.
Not Equal If values of two operands are not equal, then
!= (p != q) is True
to the condition becomes True.

Greater If the value of left operand is greater than the value


> (p > q) is not True.
than of right operand, then condition becomes True.
Lesser If the value of left operand is less than the value
< of right operand, then condition becomes True (p <= q) is True.
than
Greater than If the value of left operand is greater than or
>= equal to the value of right operand, then (p >= q) is not True.
or equal to
condition becomes True
Lesser than or If the value of left operand is less than or equal
<= (p <= q) is True.
equal to to the value of right operand, then condition
becomes True

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


2. 3 Comparison Operators

For example,
1. >>>10 == 12
False
6. >>>10 >= 12
2. >>>10 != 12
False
True
7. >>> "P" < "Q“
3. >>>10 < 12
True
True
8. >>> "Aston" > "Asher"
4. >>>10 > 12
True
False
9. >>> True == True
5. >>>10 <= 12
True
True

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


2.
Operator

4 Logical Operators
The logical operators are used for comparing or negating the logical values of their operands and to return the
resulting logical value. The values of the operands on which the logical operators operate evaluate to either True or
False. The result of the logical operator is always a Boolean value, True or False.

Operator Operator Name Description Example


Table: List of Logical

Logical AND Performs AND operation and the result is True p and q results in False
and
when both operands are True
Operators

Logical OR Performs OR operation and the result is True p or q results in True


or
when any one of both operand is True

not Logical NOT Reverses the operand state not p results in False

Note: The Boolean value of p is True and q is False.

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


2.
Operator

5 Bitwise Operators

Bitwise operators treat their


operands as a sequence of
bits (zeroes and ones) and
perform bit by bit operation.
Bitwise operators perform
their operations on such
binary representations, but
they return standard Python
numerical values.

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


2.
Data Types

Variables can hold values of different types called data types, thus it need different data types to store
different types of values in the variables.
For example:
A person’s age is stored is a number,
His name is made of only characters and
His address is a mixture of numbers and characters.

Basic data types of Python are


None is another special data type in Python.
1. Numbers
None is frequently used to represent the absence of a value.
2. Boolean
For example,
3. Strings
1. >>> money = None
4. None
2. None value is assigned to variable money ➀.

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


2.
Variables
Variable is a named placeholder to hold any type of data which the program can use to assign and modify
during the course of execution.
 In Python, there is no need to declare a variable explicitly by specifying whether the variable is an integer
or a float or any other type.
 To define a new variable in Python, we simply assign a value to a name. I

Follow the below-mentioned rules for creating legal variable names in Python.
 Variable names can consist of any number of letters, underscores and digits.
 Variable should not start with a number.
 In Python Keywords are not allowed as variable names.
 Variable names are case-sensitive.
For example, computer and Computer are different variables.

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


2.
Assigning Values to Variable

The general format for assigning values to variables is as follows:

variable_name = expression

For example:
>>> number =100
>>> number
100
>>> century = 100
>>> century
100

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


2.
Identifiers;

An identifier is a name given to a variable, function, class or module. Identifiers may be one or more
characters in the following format:

1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to


9) or an underscore (_). Names like myCountry, other_1 and good_ morning, all are valid examples.
A Python identifier can begin with an alphabet (A – Z and a – z and _).
2. An identifier cannot start with a digit but is allowed everywhere else. 1plus is invalid, but plus1 is
perfectly fine.
3. Keywords cannot be used as identifiers.
4. One cannot use spaces and special symbols like!, @, #, $, % etc. as identifiers.
5. Identifier can be of any length.

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


2.
Keywords

Keywords are a list of reserved words that have predefined meaning. Keywords are special vocabulary
and cannot be used by programmers as identifiers for variables, functions, constants or with any
identifier name. Attempting to use a keyword as an identifier name will cause an error.

The following, shows the Python keywords.


List of Keywords on Python
and as not
assert finally or
break for pass
class from nonlocal
continue global Raise
def if return
del import try
elif in while
else is with
except lambda yield
Flase True None

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


2.
INPUT OPERATION
Some times python need to work from users given input.

Python makes use of input() function. The input() function prompts the user to provide
some information on which program can work and give the result.

 Remember: user’s input should as string.

For example: Output:


name = input (“What’s your name?”) What’s your name? Ravi
age = input(“Enter your age:”) Enter your age:21
Print(name+”, you are “+ age +”years old”) Ravi, you are 21 years old

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


2.
Indentation:
Whitespace at the beginning of the line is called indentation. In python program, the leading whitespace
including spaced and tabs at the beginning of the logical line determines the indentation level of the
logical line.
 In python indentation is used to associates and group statements.

Block 1

Block 2

Block 3

Block 2, continuation

Block 1, continuation

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


3.
Conditional and un conditional branching

Decision Control Flow it is necessary should know the control flow statements in program that are
Statements to be executed. There are three fundamental methods for control flow in a
programming language i.e.,

Sequential control flow statements Line-by-line Execution

i. if – statements
ii. if-else statements
conditional
Selection control flow statements iii. Nested if statements branching
iv. Multi-way if-elif-else statements

i. while
ii. for Iterative
Loop control flow statements
iii. Nested Loops statements
iv. else with for and while

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


3.
i. break statement

ii. continue statement


Un Conditional Branching Un-conditional branching
iii. pass statement

iv. return statement

An if statement is a selection control statement and executes the


1 If - Statement program based on given Boolean (True or false) expression.
The if statement executes a statement if a condition is “true”.

if condition:
statement1
The Syntax for ‘if’ statement is;
………
indentation statement n
Statement x

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


3.
1 If - Statement Flowchart

Start
Program to increment a number if it is positive

x = 10 # Initialize the value of x


Test False
If(x>0): # test the value of x
condition
# increment the value of x, if it
True x = x+1
is > 0

print(x) # print the value of x


Statement Block 1

Output:
Statement x
x = 11

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


3.
1 If - Statement Example program

Program 1.1: Write a program to determine Program 1.2: Write a program to determine the
whether a person is eligible to vote. character entered by the user.

Char = input(“press any key:”)


age = int(input(“Enter the age:”))
if (char.isalpha()):
if (age>=18):
print(“The user has entered a character”)
print(“you are eligible to vote...”) if (char.isdigit()):

Output print(“The user has entered a digit”)

Enter the age: 21 if (char.isspace()):


you are eligible to vote...
print(“The user entered a white space

character”)

Output
press any key: 10
The user has entered a digit

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


2.
1 If - Statement

Remember:
(a) The statement(s) must be indented at least one space right of the if statement.

(b) In case there is more than one statement after the if condition, then each statement
must be indented using the same number of spaces to avoid indentation errors.

(c) The statement(s) within the if block are executed if the Boolean expression evaluates
to true.

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


3.
2 If –else Statement

In, if-else statement takes care of a true as well a false Flowchart


condition
Start

Syntax of if-else statement


False
Test True
If (test expression): Expression

statement block 1

else: Statement (s) for Statement (s) for


the False case the True case
statement block 2
End
Statement x

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


3.
2 If –else Statement Example Program

Program 1.3: Write a program to determine whether a person is eligible to vote or not. If he is not eligible ,
display how many years are left to be eligible.

age = int(input(“Enter the age:”))


if (age>=18):
print(“you are eligible to vote...”)
else:
yrs=18-age
print(“you have to wait for another ”+str(yrs)+”years to cast your vote”)
Output
Enter the age: 12
you have to wait for another 6 years to cast your vote

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


3.
3 Nested-If Statement
Nested if statements are used to check if more than one condition is satisfied.

Program 1.4: Write a program to print a number


between 0-30
A general syntax for nested if
statements is given as follows: num = int(input(“Enter any number,0-30:”))
if (num>=0 and num<10):
If Boolean-expression1:
print(“it is in the range 0-10”)
If Boolean-expression2:
if (num>=10 and num<20):
Statement1
print(“it is in the range 10-20”)
else:
if (num>=20 and num<30):
Statement2
else: print(“it is in the range 20-30”)

Statement3 Output
Enter any number, 0-30: 25
It is in the range 20-30

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


3.
4 If-elif-else Statement

If-elif-else statements are used to test additional conditions apart from the initial test expression.

A general syntax for if-elif-else Flow chart


statements is given as follows:
if (test expression 1) Test False
statement block 1
Expression
False 1
elif (test expression 2) True
statement block 2
…………………………… Statement block 1 True Test
elif (test expression N) Expression 2
False
statement block N
Statement block 2
else
Statement block X
statement block X
Statement Y Statement block Y

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


3.
4 If-elif-else Statement

Program 1.5: Write a program to test whether a number is positive, negative , or equal to zero

num = int(input(“Enter any number:”))


if (num==0):
print(“The value is equal to zero”)
elif (num>0):
print(“The number entered is positive”)
else:
print(“The number entered is negative”)
Output
Enter any number: -10
The number entered is negative

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


3.
Iterative Statements (loops)
1 While loop
The while loop provides a mechanism to repeat one (or) more statements while a particular condition is true

Note: in while loop, the condition is tested before any of statements in statement block is executed.

A general syntax for while loop statements is given as follows:

Statement x
while(condition):
statement block
Statement y

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


3.
1 While loop Flowchart

Statement X

Example program

i=0
Update the condition While(i<=10):
expression print(i,end=“ “)
Condition
i=i+1
Output:

True
Statement block False

Statement Y

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


3.
1 for loop

The for loop provides a mechanism to repeat a task until particular condition is true.

Specify the range of


sequence
A general syntax for for loop statements is given as follows:

for loop_control_var in sequence:


Is loop control variable True
statement block
in specified range

Statement block 1

False

Statement block 2

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


3.
2 for loop Range () function

The range() is a in-built function python that is used to iterate over a sequence of
numbers. The system of range () is Range( beg, end, [step])

beg
Example: Example: step
for i in range(1,5) for i in range(1,10,5)
print(i, end=“ “) print(i, end=“ “) end
Output: Output:
Print the numbers
1234 in same line 13579

Key points:
 range(10) is equal to writing range(0,10) [ with values from 0 to argument-1]
 range(0,10) is called two arguments
 range(1,10,2) is called three arguments

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


3.
3 Nested loop

Nested loop are used to place the condition inside other loops. This feature will work with
any loop like while loop as well as for loop.
for i in range(1,6):
print(“pass”,i,”- “, end=‘ ‘)
for j in range(1,6):
print(j,end=‘ ‘)
To print the following pattern
print()
Output:
pass 1- 1 2 3 4 5
pass 2- 1 2 3 4 5
pass 3- 1 2 3 4 5
pass 4- 1 2 3 4 5
pass 5- 1 2 3 4 5

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


3.
1 Unconditional branching Break statement

Break’ in Python is a loop control statement. It is used to control the sequence of the loop.

The syntax for break statement is to use keyword break


False
Loop
Control

Terminates the loop statement and


True
transfers execution to the statement
Yes Exit of
immediately following the loop. Break
loop

No

Remaining Body of
loop

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


3.
1 Break loop

Program

i =1
While i<=10:
print(i,end=” “)
if i==5:
break
i=i+1
print(“\n Done”)
Output:
1 2 3 4 5
Done

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


3.
2 Unconditional branching Continue loop

False
Loop
Control

The continue keyword is used to end the current


True
iteration in a for loop (or a while loop), and continues to

the next iteration Yes Exit of


Continue loop

No

Remaining Body of
loop

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


3.
1 Continue loop

i =0
for i in range(9):
While i<10:
i+=1 if i == 3:
if i==3: continue
continue print(i)
print(i, end=“”)
Output:
Output:
0 1 2 4 5 6 7 8 9
1 2 4 5 6 7 8 9

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


3.
3 Unconditional branching Pass loop

Pass statement is just like null operation, as nothing will


happen is it is executed. Pass statement can also be used for
writing empty loops.

for x in [0, 1, 2]:


pass

BASICS OF PYTHON PROGRAMMING AND CONTROL STATEMENTS


Thank you

You might also like