0% found this document useful (0 votes)
10 views43 pages

Unit 1 Basics of Python

This document discusses the basics of Python programming including features of Python, data types, operators, variables, control flow statements, functions and more. It provides an introduction and overview of the Python programming language.

Uploaded by

sp0707420
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
10 views43 pages

Unit 1 Basics of Python

This document discusses the basics of Python programming including features of Python, data types, operators, variables, control flow statements, functions and more. It provides an introduction and overview of the Python programming language.

Uploaded by

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

Unit-1

Basics of
Python Programming

Mr. Manan Thakkar


Assistant Professor, Dept. of Computer Engg.
UVPCE, Ganpat University, Mehsana
Outline
• Compiler vs Interpreter, Dynamic vs Static types,
strongly vs weakly typed,

• Procedural vs Object-Oriented Programming,

• Comparing Programming Languages: C, C++, JAVA, C#


and Python,

• Why Python? Python: features & applications, Python


execution process,

• Installation, Execution of Program, Various IDEs,


Python Interactive and script mode,
Outline
• Variables, Keywords, Literals, Data types, Operators and
its precedence, Expressions,

• Comments, print function with parameters, Getting


Input, String: formatting, comparison,

• slicing, splitting, stripping, negative indexing and


built-in functions,

• conditional statement: if-else, Indentation, Iterative


statements: while & for, break, continue and pass
statements
Python Programming

It is a high level, interactive, interpreted, object


oriented, structured and open source
programming language

Inventor: Guido Van Rossum

He named it based on BBC channel’s comedy


series: Monty python’s flying circus.
Features of Python
• Python is object-oriented
• Free and open source
• Portable
• Provides dynamic typing
• Extensible & Embeddable
• Python can be linked to components written in
other languages easily
• Python/C integration is quite common
• Large number of built-in libraries
• Simple syntax and easy to learn
Applications of Python
• Creating web, desktop and cross-platform
applications
• Game development
• Creating software prototypes
• Scientific & Numeric computing
• Artificial Intelligence and Machine learning
• Data Science
Python Execution Process

Compiler Python Virtual


Machine (PVM)
How python differs from other
languages
• Declaration of variable is not required, due to
implicit and dynamic typing
• Indentation is most important. Indentation in
branching statement (if-else), loops (for, while),
class and function is must
• End of statement is not mandatory (;)
• Syntax is simple. So, programmer can focus on task
instead of coding difficulty.
Binding of variable name with
object
In C language In Python language
Initially int x=2 ; Initially x=2
After sometime x=10; After sometime x=10

X 2 10 2

X
label

10

Memory Memory
Python versions
❖ Python 0.9 was published in 1991
❖ Python 1.0 was released on January, 1994
❖ Python 2.0 was released on October, 2000
❖ Python version 2.x means 2.0 to 2.7
❖ Python 3.0 was released on December, 2008
❖ Python3 version 3.x means 3.0 to 3.12.1
❖ We are going to use python 3.12.1
Python Data types
Data types

Scalar Non-scalar

List
Bool Numeric None
Tuple

String
int float Complex Octal Hex Binary
Dictionary

Set

Frozen set
Data types
A) Numeric types
Integers
•Examples: 0, 1, 1234, -56

Floating point numbers


•Examples: 0., 1.0, 1e10, 3.14e-2, 6.99E4
•Operations involving both floats and integers will yield
floats: 6.4 – 2 = 4.4

Complex numbers
•Examples: 3+4j, 3.0+4.0j, 2J
•Must end in j or J
Contd…
• Binary constants
• Examples: 0b1011, -0b101
• Must start with a leading ‘0b’ or ‘0B’
• Octal constants
• Examples: 0o177, -0o1234
• Must start with a leading ‘0o’ or ‘0O’
• Hex constants
• Examples: 0x9ff, -0X7AE
• Must start with a leading ‘0x’ or ‘0X’
Contd…
B) Bool:
•It is used to represent Boolean values: True OR False
•Word ‘TRUE’ or ‘true’ is not valid. Use- True
•Python is case sensitive language
C) None:
•Its value is ‘None’. It shows ‘empty’ or ‘no value’

•It has some specific use like when a python function returns

nothing, return statement should be: return None


•‘None’ is equal to ‘False’, when written inside ‘if’ condition.

• Note: Datatype of a variable can be checked by type()

function. For example, c=10


type (c)
Type casting (Type conversion)
• int() - constructs an integer number from an integer literal, a float
literal (by rounding down to the previous whole number), or a string
literal (providing the string represents a whole number)
• float() - constructs a float number from an integer literal, a float literal
or a string literal (providing the string represents a float or an integer)
• str() - constructs a string from a wide variety of data types, including
strings, integer literals and float literals
• dec(), bin(), oct(), hex() functions are also used for type conversion.
• Example: x= int(2.8)
• y=float(“4”)
• z= str(3.1)
• m= int(“7”)
• n=float(1)
• p= int(“6.5”) # Value Error
Python operators
Basic arithmetic operators
•Four arithmetic operations: a+b, a-b, a*b, a/b
•Exponentiation: a**b and Floor division: a//b
Comparison (Relational) operators
•Greater than, less than, etc.: a < b, a > b, a <= b, a >= b
•Identity tests: a == b, a != b
Logical operators:
•logical operators are: and, or , not
Assignment operators:
•It includes operators like: =, +=, -=, *=, /=, %=, //=,
**=, &=, |=, ^=, >>=, <<=
Contd…
• Bitwise operators
• Bitwise or: a | b, Bitwise and: a & b
• Bitwise not: ~x
• Bitwise exclusive or: a ^ b # Don't confuse this with
exponentiation
• Shift a left or right by b bits: a << b, a >> b

• Membership operators:
• It includes operators: in, not in
• Ex: x in y
• It in results in True if x is a member of sequence y
Contd...
Identity operators:
•It includes operators: is, is not

•Ex: x is y

•It is results in True if id(x) equals id(y).

Note: 1) Python follows the basic PEMDAS order of operations.


Python supports mixed-type math. The final answer will be of
the most complicated type used.
For example: (4 + 16 j) /2.2 = (1.81+ 7.27 j)
Complex number is divided by float, resultant data type is
complex number.
2) There are NO post and pre increment/decrement operators in
python i.e. a++, ++a, --b and b-- type of operators doesn’t exist.
Operator precedence & associativity
Operators Meaning

() Parentheses
** Exponent
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT
*, /, //, % Multiplication, Division, Floor division, Modulus
+, - Addition, Subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not in Comparisions, Identity, Membership operators
not Logical NOT
and Logical AND
or Logical OR
Cntd…
• Operators of same group have same precedence. When
operators of same group exist in an expression, then we need to
find out order of their evaluation means which operation will
be performed first.
• Associativity is the order in which an expression is evaluated
that has multiple operator of the same precedence. Almost all
the operators have left-to-right associativity.
• For example, multiplication and floor division have the same
precedence. Hence, if both of them are present in an
expression, left one is evaluated first.
• Exponent operator ** has right-to-left associativity in Python.
Non associative operators
• Some operators like assignment operators and
comparison operators do not have associativity in
Python. There are separate rules for sequences of this
kind of operator and cannot be expressed as
associativity.
• For example, x < y < z neither means (x < y) < z nor x
< (y < z). x < y < z is equivalent to x < y and y < z, and
is evaluates from left-to-right.
• Furthermore, while chaining of assignments like
x=y=z is perfectly valid, but x = y += z will result into
error.
• Solve this: 1) a= 4+++--2-8--+++7
2) a= ++9--+-6---3-+++5
Python syntax & Execution of program
• Ways to execute python statements/commands:
1) By writing directly in “python command prompt” or in
python IDLE:

2) Create a python file with ‘.py’ extension in any editor like


notepad / notepad++ / python IDLE / visual studio code etc.
– A) Go to location of that python file & Run it in the command line.

– B) Run that ‘.py’ file using “Run” menu option (or F5 key) in IDLE.
• Note:- Before you run ‘.py’ file in command line, add ‘path’
of ‘python.exe’ using ‘Environment Variables’.
Indentation
• Indentation refers to the spaces at the beginning of a code
line.
• In other programming languages the indentation is for
better readability only, but in Python it is mandatory.
• Python uses indentation to indicate a block of code.
• A block means group of statements like if-else, for loop,
while loop, class.
• Example:
if 5 > 2:
print ("You are inside if statement.")
print("Five is greater than two!")
Comments
• Single line comment- use ‘#’
• Multiline comment- Python doesn’t have syntax for
multiline comment option, but one can use ‘multiline
string’ concept to write multiline comments.
• Python ignores string literals that are not assigned to a
variable, you can add a multiline string (triple quotes)
in your code, and place your comment inside it.
• Example:
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Variables
• In python, variables are just label given to any data
value.
• A variable is created the moment you first assign a
value to it.

• Rules for Python variables:


1) A variable name must start with either an alphabet
(A-Z, a-z) or underscore.
2) A variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ )
3) Variable names are case-sensitive (age, Age and AGE
are three different variables)
Important points
• “” and ‘’ works in same way in python.
• Multiple variable assignment using single “=“ operator is
possible in python.
• Ex: 1) x,y,z= 1,2,3 Swapping of value:
x=2; y=5
2) a,b,c= “how” x,y=y,x
3) m,n,p= “hello” #ValueError
• Operator Overloading for ‘+’ and ‘*’:
• ‘+’= It performs addition when applied to numbers and
concatenation when applied to strings.
• ‘*’= It performs multiplication when applied to numbers,
and repetition when applied to ‘number’ and ‘string’.
Cntd…
• Overloading of ‘+’operator:
1) 3+4 =7
2) ‘at’ + ‘work’= ‘atwork’
3) 3 + ‘am’ #TypeError
• Overloading of ‘*’operator:
1) 3*4 =12
2) 3 * ‘bus’ = ‘busbusbus’
3) ‘at’ * ‘work’ #TypeError
Input function
• Input function is used to take input from the user.
• By default, it takes input in ‘string’ type. If user wants
input in other format, then type casting is required.
• Example:
1) a= input(‘Enter your name:’)
Output🡨 Enter your name: (waiting for user to input)
Enter your name: hello
Now, a= “hello’
2) A = float (input (‘Enter your age:’))
Output🡨 Enter your age: 5
A= 5.0
Print function
• It is used to display output. There are some variants of print
function:
1) print (‘Hello buddy’)
2) print(“I don’t know”) OR print(‘I don\’t know’)
3) x=3
print(“value of x:” +x) # Type Error
To solve this error:
A) Use type conversion. i.e. print(“value of x:” +str(x))
B) Take different values as different parameters
print(“value of x:”, x)
Cntd…
• Buit-in parameters of print(): sep, end
1) sep : Data items are separated using value of ‘sep’. Default
value is- ‘ ‘ (white space)
Ex: print(‘how’, ’are’, ‘you’, 10,sep=‘$’)
Output🡨 how$are$you$10

2) end: Value of this parameter is printed at last.


By default, ‘print’ uses end=‘\n’ (new line) character. That
means every ‘print’ function leave the cursor in next line.
That format can be changed by providing different value to
‘end’.
Ex: print (‘Indian culture’, end=‘’)
Cntd…
• print() is also used to provide formatted output:
1) print("Art: %5d, Price per unit: %8.2f" %(453,59.058))
Output🡨 Art: 453, Price per unit: 59.06

2) print("First argument: {0}, second one: {1}".format(47,11))


Output🡨 First argument: 47, second one: 11

3) print("First argument: {}, second one: {}".format(47,11))


Output🡨 First argument: 47, second one: 11

4) print ("Second: {1:3d}, first: {0:7.1f}".format(47.42,11))


Output🡨 Second: 11, first: 47.4
Python strings
• String is a sequence of characters i.e. array of characters.
• Python does not have a character data type, a single
character is simply a string with a length of 1
• ‘oxe’ and “oxe” both have same interpretation.
• Assigning value to a string:
• single line: x= ‘hello’
• Multiline: x= ‘’’hello how are you?
I am fine.
How is your goal?’’’
• String is ‘immutable’ data type.
String: Indexing and Slicing
•A string has indexes running from 0 to len(s)-1.
• len() is built-in python command to find length of string.
• Python also supports negative indexing. Last element of
string is indexed as (-1).
•For example: H E L L O W O R L D
-10 -9 -8 -7 -6 -5 -4 -3 -2
-1
• Consider a= ‘Ganpat University’
• print(a[3]) 🡨 output: ‘p’
• print (a[-6]) 🡨 output: ‘e’
Cntd…
• Slicing: Fetching a range of characters from string
• syntax-1: a[starting_value : end_value]
• For example, a= ‘Indian Culture’
• print ( a[2:5]) 🡨 output: ‘dia’ (it prints a[2: (5-1)] only)
• print (a [-5:-2]) 🡨 output: ‘ltu’
• Syntax-2: a[starting_value: end_value: step-size]
• Example: a= ‘computer engineering’
• print (a[0:5:2])🡨 output: 'cmu’
• print(a[-6:-1:2])🡨 output: ‘'ern’
• Print(a[1: :3]) 🡨 output: 'ournnrg'
cntd…
• print (a[-1:-3]) 🡨 Find values of all statements
• print (a[-4:-1])
• print (a[-1:-3:2])
• print (a[-1:-5:-1])
• print (a[-1:-5:-2])
• print (a[-6:-1:1])
• print (a[-6:-1:2])
• print (a[-5::2])
• print (a[-5::-2])
• print (a[:-2:1])
• print (a[:-2:-1])
• print (a[-3::2])
• print (a[-3::-2])
• print (a[::2])
• print (a[::-3])
String operations
• Read provided ms-word document named as “Python_string_methods”.
Conditional Statements (Decision making)
• Remember, python doesn’t have ‘switch’ statement.

1) Simple if…else
Syntax:
if expression:
statement(s)
else:
statement(s)
Cntd…
2) if..elif…else ladder:
Syntax:
if expression1:
statement(s)
elif expression2:
statement(s)
else:
statement(s)

3) Nested if..else:
if...elif...else statement inside another if...elif...else
statement is called nesting.
Loops
• Loop consists of three important parts:
the initialisation, the condition, and the update.
1) while loop:
Syntax:
while expression:
statement(s)

2) for loop:
Syntax:
for iterator in sequence:
statements(s)
Cntd…
Examples:
1) count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
2) for i in range(5):
print (i)
3) for i in range(1,6,2):
print (i)
4) for i in ‘computer’:
print (i)
Cntd…
• break, continue, pass statements & else clause:
• break: Terminates the loop statement and transfers
execution to the statement immediately following the
loop.
• continue: Causes the loop to skip the remainder of its
body and continue with next iteration.
• pass: The pass statement in Python is used when a
statement is required syntactically but you do not want
any command or code to execute.
Cntd…
Examples:
1) for i in range(6):
if i==3:
break
print(i)
2) for i in range(6):
if i==3:
continue
print(i)
3) while True:
pass
4) class MyEmptyClass:
pass
Cntd…
• Else: else clause runs when no break occurs.
Example:
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n//x)
break
else:
print(n, 'is a prime number')

You might also like