0% found this document useful (0 votes)
34 views74 pages

Python Intro - New

Uploaded by

subodh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
34 views74 pages

Python Intro - New

Uploaded by

subodh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 74

What is Python….. ?

 Python is a general purpose programming language


that is often applied in scripting roles.
 So, Python is programming language as well as
scripting language.
 Python is also called as Interpreted
language(executes the code line by line at a time.)
 Python is also an Integrated language because we
can easily integrated python with other languages
like C, C++, etc.
 Python is case sensitive as it treats upper and lower
case characters differently.
What can we do with Python….. ?

 System Programming
 Graphical User Interface Programming (PyQt5 is the
most popular option for creating graphical apps with
Python.)
 Database Programming
 Game development
Why do people use Python….. ?
The following primary factors cited by Python users seem to be these:
 Python is object-oriented(concepts of classes, abstraction,
etc.) with very simple syntax rules.
 It’s free (open source) that is available for everyone to
use.
 Because of its human-friendly syntax, it's easy to write,
read, and debug
 It’s powerful
 It’s portable(works on variety of platforms – Windows,
linux, Mac).
 Its completeness(need not to install additional libraries).
Installing Python

https://www.python.org/downloads/
- Download the latest version of python IDLE and install, recent
version is 3.12.0
Running Python

Once you’re inside the Python interpreter, type in


commands .
 Examples:
>>> print (‘Hello World’)
Hello World
Math (Operator ) In Python
Try this :

>>> print (3 + 12)


15
>>> print (12 – 3)
9
>>> print (9 + 5 – 15 + 12)
11
Operators:
Add: +
Subtract: -
More Operators:
Multiply: *
Divide: /

>>> print (3 * 12) 36


>>> print 12 / 3 4
>>> print 12.0 //3.0 4(Integer Division)
>>> print 11.0 / 3.0 3.66

Relational operators:
>>> print (2 < 3 ) True
>>> print (2 != 3) True
>>> print (False < True ) True
Variable In Python
What is a Variable in Python?
 A Python variable is a reserved memory location to store values. In other words, a
variable in a python program gives data to the computer for processing.
Python Variable Types
 Every value in Python has a datatype. Different data types in Python are
Numbers, List, Tuple, Strings, Dictionary, set, etc. Variables in Python can be
declared by any name or even alphabets like a, aa, abc, etc.
Variable
Create a Variable:
>>> x = 10
>>> x
10
Assigning a new value:
>>> x = 20
>>> x
20
Multiple assignments
Variable Definition
 In Python, a variable is created when you first assign a value to it. It also means
that a variable is not created until some value is assigned to it.
 Example:
print(x)
x=20
print(x)
When you run the above code, it will produce an error for the first statement only –
name ‘x’ is not defined.
So, to correct the above code-
x=0 #variable x created now
print(x)
x=20
print(x)
** A variable is defined only when you assign some value to it. Using an undefined
variable in an expression/statement causes an error called Name Error.
Dynamic Typing
 A variable pointing to a value of a certain type, can be made to point
to a value/object of different type. This is called Dynamic Typing.
 Example:
x = 10
We can say that variable x is referring to a value of integer type.
Later in your program, if you reassign a value of some other type to
variable x, Python will not raise any error, i.e.,
x =10
print(x)
x=‘Hello World’
print(x)
 Caution with Dynamic Typing
Although Python is comfortable with changing types of a variable, the
programmer is responsible for ensuring right types for certain type of operations.
For example,
Python String Concatenation
and Variable

 Once the integer is declared as string, it can concatenate both “Code" +


str("99")= “Code99" in the output.
Delete a variable
 You can also delete Python variables using the command del "variable
name".
Augmented Assignment operators
 Example1: if you want to add value of b to value of a and assign the result to a,
then instead of writing
a=0, b=5 a = a + b = 0+5 =5
you may write
a+=b
 Example2: to add value of a to value of b and assign the result to b, you may write
b+=a # instead of b= b + a

x+=y x= x+y
x - =y x=x-y
x *=y x=x*y
x/=y x=x/y
x//=y x=x//y
x**=y x=x**y
 Examples:
f=‘god’, g=‘God’, h=‘god’, j=‘God’, k=“Godhouse”
f==h will return True
“God”==“Godhouse” will return True
g== j will return True
“god” < “Godhouse” will return False (based on ASCII value of g &
G)

 Python Logical Operators


Logical operators are used to combine conditional statements:

Operator Description Example


and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x
<4
not Reverse the result, returns False if not(x<5 and x<10)
the result is true
Type Conversion
 In a mixed-mode expression , different types of variables/constants are
converted to one same type. This process is called type conversion (also
known as coercion).
 Type conversion can take place in two forms: implicit( that is performed by
compiler without programmer’s intervention) and explicit (also known as
type casting) (that is defined by the user).
 Implicit type conversion(Coercion):
ch=5 #integer
i=2 #integer
fl = 4 #integer
db = 5.0 #floating point number
fd = 36.0 #floating point number
A= (ch + i)/db # expression1
B = fd/db* ch/2 #expression2
print(A)
print(B)
 Explicit type conversion(Type Casting):
example: if we have (a=3 and b= 5.0), then
int(b) – will give 5
will cast the data type of the expression as int.
Similarly,
d = float(a)
will assign value 3.0 to d because float(a) cast the expression’s
value to float and then assigned it to d.

str(a) – will give ‘3’


str(5.78) – will give ‘5.78’
str(True) – will give ‘True’
float(‘34’) – will give 34.0
 What would be the output of the following code:
a = 3+5/8
b = int(3+5/8)
c = 3+ float(5/8)
d = 3+ float(5)/8
e = 3+ 5.0/8
f = int(3+5/8.0)
print(a, b, c, d, e, f)
Addition of string and integer Using Explicit Conversion
 Python Identifiers
1. An identifier is a name given to entities like class, functions, variables, etc.
It helps to differentiate one entity from another.
2. An identifier cannot start with a digit.
3. Identifiers can be a combination of letters in lowercase (a to z) or
uppercase (A to Z) or digits (0 to 9).
4. We cannot use special symbols like !, @, #, $, % etc. in our identifier.
5. An identifier can be of any length.
6. Always give the identifiers a name that makes sense. While c=10 is a valid
name, writing count=10 would make more sense, and it would be easier to
figure out what it represents when you look at your code after a long gap.
 Expressions
An expression is any legal combination of symbols that represents a
value. An expression represents something, which Python evaluates
and which then produces a value.
Example: 15, 2.9, a+5, (3+5)/4
Data Types In Python
Data Type:
Python has many data types. Here are the important ones:

• Numbers can be integers (two types of integers - signed and


Booleans), floats (1.1 and 1.2), fractions, or even complex numbers.

• Strings are sequences of characters represented in the quotation


marks. Python allows for either pairs of single or double quotes.
Subsets of strings can be taken using the slice operator ([ ] and [:] )
with indexes starting at 0 in the beginning of the string and working
their way from -1 at the end.

• Lists are ordered sequence of values.

• Tuples are ordered, immutable sequence of values.

• Dictionary
• Set
 Numbers
Number data types are used to store numeric values in Python. The numbers in
Python have following core data types:
a) Integers - are whole numbers such as 5,39,1917,0 etc. They have no
fractional parts. Integers can be positive or negative.
b) Booleans – represent the truth values False and True. False and True behave
like the values 0 and 1, respectively. To get the Boolean equivalent of 0 or 1,
you can type bool(0) and bool(1), Python will return False or True
respectively.
String: Data Type
Strings:

A string is a sequence of characters and each character can be individually


accessed using its index.

Try typing without quotes: >>>”It’s a beautiful day !”


What’s the result ? >>> a= “Good Morning”
>>> a
‘Good Morning’
>>> a= ‘Good Morning’
>>>a
‘Good Morning’
Strings Operations:
Concatenation , Replication :
Strings Operations:
Slicing : refers to a part of the string.
Specify the start index and the end index, separated by a colon.
Syntax: string[start:end:step]
Example:
a) print(str[3:6])
b) print(str[4:10])
c) print(str[ : ]
d) print(str[7: ])
e) print(str[-7: ])
f) print(str[-9:-3])
g) print(str[2:10:2])
h) print(str[-1:-1:-1])
i) print(str[-11:-4])
j) print(str[-14::-3])
 str=“Welcome to my blog”
a. print(str[3:18])
b. Print(str[2:14:2])
c. Print(str[:7])
d. Print(str[8:-1:1])
e. Print(str[-9: -15])
f. Print(str[0:9:3])
g. Print(str[9:29:2])
 ‘Start’ and ‘stop’ indices and the step can have a negative value, respectively.

 Let’s say we have to fetch the substring scale.


The syntax for fetching substring using negative indices would be: S[-6 : -1]
(-6th index points to the 6th element from the end and -1 to the 1st element from the end)
 Fetching substring using negative index and negative step value
s = "Welcome to scaler"
# -x means xth element from the end.
print("indexing syntax without step:", s[-16 : -4])
# using step to fetch every 2nd character from start index until end index
print("indexing syntax with step:", s[-16 : -4 : 2])

Output:
indexing syntax without step: elcome to sc
indexing syntax with step: ecm os
 Slicing with positive and negative index

s = "Welcome to scaler"
s1 = s[3 : -7]
print("positive start index, negative end index:", s1)
# above slice operation can also be written as
s2 = s[-14 : 10]
print("negative start index, positive end index:", s2)

Output:

positive start index, negative end index: come to


negative start index, positive end index: come to
 Reversing a substring using a negative ‘step’ in a slice
The ‘Step’ parameter is considered to be less than 0 when reversing a string.
NOTE: When reversing: ‘step’ < 0, ‘start’ > ‘stop’.
Whereas when not reversing: when ‘step’ > 0, startIndex < stopIndex.

Example – Reversing a substring using a negative step


s = "welcome to scaler"
# reversing complete string
 s1 = s[ : :-1]
print("s1:", s1)
# reversing complete string by stepping to every 2nd element
 s2 = s[ : :-2]
print("s2:", s2)
# reversing from 10th index until start, 'stop' index here automatically will be
till starting of the string
 s3 = s[10: :-1]
print("s3:", s3)
# reversing from end until 10th index, 'start' index will automatically be the
first element
 s4 = s[ :10:-1]
print("s4:", s4)
# reversing from 16th index till 10th index
 s5 = s[16:10:-1]
print("s5:", s5)
# this will return empty, as we're not reversing here. But NOTE that this
'start' cannot be greater than ‘stop’ until & unless we're reversing
 s6 = s[11:2]
print("s6:", s6)
# reversing from 14th index from the end until 4th index from the end.
 s7 = s[-4:-14:-1]
print("s7:", s7)
Output:

s1: relacs ot emoclew


s2: rlc teolw
s3: ot emolew
s4: relacs
s5: relacs
s6:
s7: acs ot emo
 The slice() function returns a slice object.
A slice object is used to specify how to slice a sequence. You can specify where to
start the slicing, and where to end. You can also specify the step, which allows
you to e.g. slice only every other item.
Syntax
slice(start, end, step)

a = ("a", "b", "c", "d", "e", "f", "g", "h")


x = slice(2)
print(a[x])

Output:
('a', 'b')
Membership operators
 ‘in’ and ‘not in’ are membership operators.
 ‘in’ – returns true if a character/substring exists in a given string.
 ‘not in’ – returns true if a character/substring does not exist in the
given string.
 Syntax: <substring> in <string>
<substring> not in <string>
Built in String Methods:
 len() – returns the length of the string.
Syntax: len(str)
 capitalize() – first letter is in uppercase
Syntax: str.capitalize()
 split() – breaks up a string at the specified separator and returns a list of
substrings.
Syntax : str.split( [ separator [, maxsplit ] ] )
** Note : a) If separator is not specified, any white space string is a
separator.
b) Default value of maxsplit is 0.
c) split into n+1 strings.

 lower() – converts all the uppercase letters into lowercase


Syntax: str.lower()
 upper() - converts all the lowercase letters into uppercase
Syntax: str.upper()
 replace() – replaces all the occurrences of the old string with the new
string.
Syntax : str.replace(old,new)
Empty String

** if we wish to display the output on the next line, then the use of escape
sequence ‘\n’ becomes mandatory.
 We can also use escape sequence (\t) to tabulate the output.

 Multiline Strings
Traversing a String
 Means accessing all the elements of the string one after the other by
using the subscript or index value.
Strings are immutable

 You cannot change the values. That means, strings in Python are
immutable.
 So, still if you want to change the value, you can do one thing:
 Write a Python program to print all the words in an input string.
 Write a Python program to remove the words beginning with vowels.
 Write a program in Python to count lower, upper, numeric and special
characters in a string.
 Basic Practice Questions:
1. Write a Python program to check if the given number is greater than 5. If
the number is greater than 5, then print the cube of the number. If the
number is less than or equal to 5, then print the square of the number.
2. Write a program to check whether the given two numbers are same or not.
If they are same, then check if the first number is greater than second
number.
3. Write a program to count the number of digits in any number.
Type() function
 If we wish to determine the type of a variable i.e., what type of value
does it hold/point to, then type() function is used.
Input() function
 It is used to get data from the user while working with the script mode. It is
used us to accept an input string from the user without evaluating its value.

 Input() function always accepts input in the form strings and hence
manipulates number as strings only and does not generate the desired
result.
So, we use another function int().
Int() function converts the inputted string into numeric values and
shall store the value 30 as a number and not as string. Thus , we will
obtain the desired output as 70(sum of 30 and 40).
Decision Making
 Decision-making statements are used to control the flow of execution
of program depending upon condition.
 There are four types of decision-making statements in Python:
a) if statement
b) if-else statement
c) if-elif ladder
d) Nested if-else statement
 If statement
Syntax:
if condition:
statement(s)
 If-else statement
Syntax:
If condition:
statement(s)
else:
statement(s)
 If-elif-else statement
Syntax:
If condition:
statement(s)
elif condition:
statement(s)
elif condition:
statement(s)
else:
statement(s)
 Nested If-else statement
Syntax:
If condition:
statement(s)
if condition:
statement(s)
elif condition:
statement(s)
else:
statement(s)
elif condition:
statement(s)
else:
statement(s)
Practice Questions
 Write a python program to check the profit or loss
 Write a program to check whether the given character is an uppercase letter or
lowercase letter
 Write a program to check whether or not a given number is less than 50. if the
number is less than 50, then check if the number is greater than 25 or not. If the
number is less than 25, then check whether the number is even or odd.
Named Conditions:
 The traditional way of writing code will be :
if deposit < 2000 and time >=2:
rate = 0.05
But if you name the conditions separately and use them later in your code, it adds
to readability and understandability of your code, e.g.,
eligible_for_5_percent = deposit < 2000 and time >=2
eligible_for_7_percent = 2000 <= deposit < 6000 and time >=2

Now you can use these named conditions in the code as follows:

if eligible_for_5_percent:
rate = 0.05
elif eligible_for_7_percent:
rate = 0.075
Python supports the usual logical conditions from mathematics:

 Equals: a == b
 Not Equals: a != b
 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
Ques1. Write a program to calculate BMI (body mass index) of a person.
Body mass index is a simple calculation using a person’s height and
weight.
The formula is BMI = kg/m2 where kg is person’s weight and m2 is their
height in metres squared.

BMI = weight in kg/height in metre*height in metre

Ques2. Write a program to test divisibility of a number with another number.

Ques3. Write a program that reads two numbers and an arithmetic operator
and displays the computed result.
Ques4. Write a program to print whether a given character is an uppercase
or a lowercase character or a digit or any other character.
Arithmetic operators
 Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication, etc.
Comparison operators
 Comparison operators are used to compare values. It returns either True or False
according to the condition.
Logical operators
 Logical operators are the and, or, not operators.
Bitwise Operators
Bitwise operators are like logical operators but they work on individual bits.
For example, 2 is 10 in binary and 7 is 111.
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in
binary)

You might also like