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

Python Unit 1

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)
11 views

Python Unit 1

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
You are on page 1/ 110

Python basics

Uzma Sulthana, Dept. of CSE, MSRIT


Run
with some input

Write/Edit
OK?
NO
YES

YES
NO More
Inputs?
2 Programming 1/7/23
Basics
⚫ Type into the interactive shell, also called the
REPL (Read-Evaluate-Print Loop), which lets
you run (or execute)
Basics
⚫ Python instructions one at a time and
instantly shows you the results.
⚫ Expression
⚫ Values
⚫ operators
Basics
⚫ Error

⚫ A crash just means the program stopped


running unexpectedly.
Operators in python
expressions
Order of operations

⚫ Whitespace in between the operators and


values doesn’t matter for Python (except for
the indentation at the beginning of the line),
but a single space is convention.
Order of operations
Order of operations
Order of operations
Example
More Examples
A= 1 0 B=-5 C=2 D=5

1. (A+B)*(C-D)
2. A//C%3
3. D*(B+A)
4 . C + (B - C)/D
S y n t a x Error
Questions
⚫ Which of the following are operators, and
which are values?

⚫ What is an expression made up of?


The Integer, Floating - Point, a n d
String D a t a Types
⚫ A data type is a category for values, and
every value belongs to exactly one data
type
The Integer, Floating - Point, a n d
String D a t a Types
⚫ Python programs can also have text values
called strings
⚫ Always surround your string in single quote ( ‘ )
⚫ Eg 'Hello‘
⚫ You can even have a string with no characters in
it, ‘ ', called a blank string or an empty string.
String Concatenation and Replication
⚫ The meaning of an operator may change based on
the data types of the values next to it.
⚫ Eg 2+3, 3.2 + 5.6
⚫ However, when + is used on two string values, it
joins the strings as the string concatenation
operator
> > > 'Alice' + ' B o b '
'AliceBob‘

⚫ However, if you try to use the + operator on a string


and an integer value, Python will not know how to
handle this, and it will display an error m e s s a g e .
String Concatenation and Replication
⚫ The * operator multiplies two integer or
floating-point values.
⚫ But when the * operator is used on one string
value and one integer value, it becomes the
string replication operator.
> > > 'Alice' * 5
'AliceAliceAliceAliceAlice‘

> > > 'Alice' * 'Bob‘


Storing Values in Variables
W h a t is variable ?
A variable is a quantity that may be changed
according to the mathematical problem.
Eg : x+1

⚫ A variable is like a box in the computer’s


memory where you can store a single value.

X
A s s i g n m e n t Statements
⚫ An assignment statement consists of a
variable name, an equal sign (called the
assignment operator), and the value to be
stored.
⚫ Eg spam = 42,
A s s i g n m e n t Statements
variable initialization
Variable N a m e s
⚫ A good variable name describes the data it contains
⚫ Example?

⚫ Naming restrictions
1. It can be only one word with no spaces.
2. It can use only letters, numbers, and the underscore (_)
character.
3. It can’t begin with a number.
4. Variable names are case-sensitive, meaning that spam,
SPAM, Spam, and sPaM are four different variables.
5. Python convention to start your variables with a
lowercase letter.
Variable N a m e s
Comments
Comments

⚫ The following line is called a comment.

⚫ Python ignores comments, and you can use


them to write notes or remind yourself
what the code is trying to do.
The print() Function

⚫ The print() function displays the string value


inside its parentheses on the screen.
⚫ A value that is passed to a function call is an
argument.
⚫ Notice that the quotes are not printed to the
screen.
⚫ They just mark where the string begins and
ends; they are not part of the string value.

⚫ print( )?
The input() Function

⚫ The input() function waits for the user to type


some text on the keyboard and press enter.

⚫ Whatever you enter as input, the input


function converts it into a string.
⚫ If you enter an integer value still input()
function convert it into a string.
Printing the U s e r ’ s N a m e
The len() Function
⚫ You can pass the len() function a string
value (or a variable containing a string),
and the function evaluates to the integer
value of the number of characters in that
string.
The len() Function
The len() Function

Python gives an error because the +


operator can only be used to add two
integers together or concatenate two
strings.
Questions
⚫ Name three data types.
⚫ Which of the following is a variable, and which is a
string?

⚫ What does the variable bacon contain after the


following code runs?

⚫ What should the following two expressions evaluate


to?

⚫ Why is eggs a valid variable name while 100 is invalid?


First Program
Second Program
The str(), int(), a n d float()
Functions
⚫ If you want to concatenate an integer such
as 29 with a string to pass to print(), you’ll
need to get the value '29', which is the
string form of 29.
⚫ The str() function can be passed an integer
value and will evaluate to a string value
version of the integer, as follows:
The str(), int(), and float()
Functions
The str(), int(), and float()
Functions
Questions 1
Question
⚫ Why does this expression cause an error?
How can you fix it?
TEXT A N D N U M B E R
EQUIVALENCE
⚫= = Equivalence operator
FLOW CONTROL
⚫ Program is just a series of instructions.
⚫ Flow control statements can decide which Python
instructions to execute under which conditions.
FLOW CHART S Y M B O L
FLOW CONTROL
B o o l e a n Va l u e s
They always start with a capital T or F, with
the rest of the word in lowercase.
Boolean Values
Boolean Values
B o o l e a n Va l u e s
The < , > , < = , and > = operators, on the
other hand, work properly only with
integer and floating-point values.
Question
Q THE D I F F E R E N C E B E T W E E N THE
= = A N D = O P E RAT O R S ?
Boolean Operators
The three Boolean operators
 and
 or
 not
Boolean Operators
The three Boolean operators
 and
 or
 not
Boolean Operators
The three Boolean operators
 and
 or
 not
only one Boolean value- unary
operator
Mixing Boolean and Comparison
Operators
PLC142
INdentation
Elements of Flow Control
 Conditions
Conditions always evaluate down to a Boolean value,
True or False.
A flow control statement decides what to do based on
whether its condition is True or False, and almost every
flow control statement uses a condition.

 Blocks of Code
There are three rules for blocks.
•Blocks begin when the indentation
increases.
• Blocks can contain other blocks.
• Blocks end when the indentation
Flow Control S t a t e m e n t s
 if Statements
• The if keyword
•A condition that is, an expression that
evaluates to True or False
• A colon
•Starting on the next line, an indented block
of code (called the if clause)
Flow Control S t a t e m e n t s
Flow Control S t a t e m e n t s
else S t at em ents
“If this condition is true, execute this
code. Or else, execute that code.”
An else statement doesn’t have a
condition, consists of the following:
• The else keyword
• A colon
•Starting on the next line, an indented
block of code (called the else clause)
PLC142
Conditional Statements
Flow Control S t a t e m e n t s
else S t at em ents
Flow Control S t a t e m e n t s
PLC142
Conditional Statements
Flow Control S t a t e m e n t s
elif Statements
you may have a case where you
want one of many possible clauses to
execute.
elif statement always consists of the
following:
• The elif keyword
•A condition (that is, an expression that
evaluates to True or False)
• A colon
•Starting on the next line, an indented
block of code (called the elif)
PLC142
Conditional Statements – elif
Flow Control S t a t e m e n t s
PLC142
PLC142
while L o o p S t a t e m e n t s
You can make a block of code execute over and
over again using a while statement.
• The while keyword
• A condition
• A colon
•Starting on the next line, an indented block of
code (called the while clause)
At the end of a while clause, the program
execution jumps back to the start of the while
statement.
The while clause is often called the while loop or
just the loop.
while L o o p S t a t e m e n t s
Composition
break Statements
If the execution reaches a break statement,
it immediately exits the while loop’s clause.
continue Statements
When the program execution reaches a
continue statement, the program execution
immediately jumps back to the start of the
loop and revaluates the loop’s condition.
List of Program using while loop

1. Program to print numbers 1 to 10


2. Program to print even numbers
between 1 to 10
3. Program to print odd numbers
between 1 to 10
4. Demonstrate break statement
5. Demonstrate continue statement
for Loops and the range() Function
In code, a for statement looks something like
Eg for i in range(5):

and includes the following:


• The for keyword
• A variable name
• The in keyword
•A call to the range() method with up to three
integers passed to it
• A colon
•Starting on the next line, an indented block
of code (called the for clause)
for Loops and the range() Function
r an g e ( ) Function

Syntax
range(start, stop, step)

startOptional. An integer number


specifying at which position to start.
Default is 0
stopRequired. An integer number
specifying at which position to stop (not
included).
stepOptional. An integer number
r an g e ( ) Function
Python N ested Loops Syntax:
Python Nested Loops Syntax:
P ri n ti n g m u lti plic a tion ta ble u s i n g P y t h o n n e s t e d for l o o p s
Importing Modules
 Built-in functionsprint(), input(), and len() functions
 Python also comes with a set of modules
called the standard library.
 Each m o d u l e i s a P y t h o n program that
contains a related group of functions that
can be embedded in your programs.
 Before you can use the functions in a
module, you must import the module
with an import statement.
Importing Modules
 In code, an import statement consists of the
following:
• The import keyword
• The name of the module
•Optionally, more module names, as long as
they are separated by commas

Eg: random module


Importing Modules
from import S tatem ents
from keyword, followed by the module name, the import
keyword, and a star;

For example,
from random import *.
E n d i n g a P r o g r a m Early wit h t he s ys .exit( ) Function

How to terminate the program ?


Programs always terminate if the program
execution reaches the bottom of the instructions
you can cause the program to terminate, or exit,
before the last instruction by calling the
sys. exit() function
 Since this function is in the sys module, you
have to import sys before your program can use
it.
E n d i n g a P r o g r a m Early wit h t he s ys .exit( ) Function
Lab P r o g r a m 1 : P r o g r a m to perform
addition, subtraction, multiplication and
division on two input numbers in Python
Au g m e n t e d As s i g n m e n t

a=a+5 a+=5
b =b*2 b*=2
c = c/5 c/ = 5
d = d -6 d-= 6
Functions

• Easy
• Reuse
• Built-in functions

•The general form of a function call is as follows:


«function_name»(«argum ents»)
Functions

•Here are the rules to executing a function


call:
1. Evaluate each argument one at a time,
working from left to right.
2. Pass the resulting values into the function.
3.Execute the function. When the function
call finishes, it
produces a value.

Eg: p o w ( a b s ( - 2), round(4.3))


Functions
Functions

>>> round(3.8)
4
>>> round(3.3)
3
>>> round(3.5)
4
>>> round(-3.3)
-3
>>> round(-3.5)
-4
>>> round( 3.141592653 , 2)
3.14
Functions
Memory Addresses: How Python
Keeps Track of Values
⚫ Python keeps track of each value in a separate
object and that each object has a memory
address.
⚫ You can discover the actual memory address
of an object using built-in function id:
Memory Addresses
Function also have Memory Addresses
Defin in g O u r O w n
Functions
⚫ The general form of a function definition is
as follows:

⚫ Example
Defining Our O w n Functions

return «e x p r e s s io n»
Using Local Variables for Temporary
Storage
variable’s scope. The scope of a local
variable is from the line in which it is
defined up until the end of the function.
K eywords

Keywords are words that Python


reserves for its own use
PLC142
Collatz 3n+1 sequence
Collatz sequence
PLC142
Collatz 3n+1 sequence
L a m b d a function

 A lambda function is a small anonymous function.


• lambda function, which allows us to create a one-line
function anywhere we want without giving it a name
 A lambda function can take any number of arguments but
only have one expression.
L a m b d a function
L a m b d a function
Write a python program to find the
factorial of number using while loop.
Write a python program to add 10 numbers by
inputting each from the keyboard using for loop.
2 a] Write a python function
linearSearch() to read an array and
search for the key element. Display the
appropriate messages. Use the
recursive function.

You might also like