You are on page 1of 51

WHAT IS PYTHON?

MACHINE LANGUAGE
 Comp – Collection of electronic circuits
 Binary no system for inputs and interpreting outputs
 Instruction to microprocessor – Series of 0s and 1s
 Decimal can be converted to binary
 Instruction Formats
 Complete set of instruction for CPU : machine language code
 Pros:
 No translation
 Execution is quick
 Cons:
 Difficult to write and locate bugs
 For same process, instn code for processors made by diff
manufacturers are diff.
 Therefore, program written in one machine
lang for one type of CPU will work on comp
having same type of CPU.
 No portability
 Difficult conversion
ASSEMBLY LANGUAGE
 Instruction code are more user friendly
 Instructions include short words called
mnemonics
 MOV, SUB, ADD
 Needs ASSEMBLER
 Lack of portability
 Difficult to learn
 Laborious
 Difficult to debug
HIGH LEVEL LANGUAGE
 Human friendly
 Consists of words : Keywords and other text
 Easily understandable
 Appropriate words are chosen.
 Words : A set of comp instns
 Reduces lines of code for programmer
 Compilers or Interpreters are req
DIFFERENT GENERATIONS
 Machine level lang : 1st generation lang
 Assembly level lang : 2nd generation lang
 High level lang : 3rd generation lang
 With dev of multicore processors lang can
carry out parallel prog, concurrent prog : 4th
generation lang
BYTECODE V/S MACHINE CODE
PYTHON
 Popular programming lang
 Invented by : Guido van Rossum
 Released in 1991 at CWI (Centrum Wiskunde &
Informatica) Netherland.
 General purpose lang : can be used in any domain
 High level language
 Dynamic programming language
 Procedural prog lang : Organizing code into
procedures or functions that can be called to
perform specific tasks. Code is organized around
procedures that manipulate data, and the flow of
execution is controlled using control structures
 Object oriented programming lang : you can
define classes to create objects that
represent real-world entities and define their
attributes (data) and methods (functions).
Python supports OOP principles such as
encapsulation, inheritance, and
polymorphism.
WHY PYTHON?
 Simple and easy to learn
 Platform Independent : can run in windows,
linux, mac os etc
 Free and open source
 Interpreted : code is executed line by line by
an interpreter at runtime.
 The Python interpreter compiles the source
code into bytecode at runtime. It is different
from traditional compilation where source
code is compiled into m/c code before
execution
 Portable
 Rich library support : need not write code
from scratch
Libraries related to math, data science , m/c
learning etc are available.
 Embedded and extensible
 Robust : error handling, proper memory
management
APPLICATIONS OF PYTHON
 Python can be used on a server to create
web applications.
 Python can connect to database systems. It
can also read and modify files.
 Python can be used to handle big data and
perform complex mathematics.
 Python can be used for rapid prototyping, or
for production-ready software
development.
CONTD…
 Python works on different platforms
(Windows, Mac, Linux, Raspberry Pi, etc).
 Python has a simple syntax similar to the
English language.
 Python has syntax that allows developers to
write programs with fewer lines than some
other programming languages.
 Designed for readability, and has some similarities
to the English language with influence from
COMPARISON OF PYTHON WITH OTHER PROGRAMMING LANGUAGES

mathematics.

 Python uses new lines to complete a command, as


opposed to other programming languages which
often use semicolons or parentheses.

 Python relies on indentation, using whitespace, to


define scope; such as the scope of loops,
functions and classes. Other programming
languages often use curly-brackets for this
purpose.
FOR EXAMPLE:
 print("Hello, World!")
IDENTIFIER
 An Identifier is a name used to identify a
variable, function, class, module or object.

 In Python, identifier is like a noun in English.

 user-defined names that you give to various


elements in your program

 Identifier helps in differentiating and


recognizing.

 For example: name and age which speak of


two different aspects are called IDENTIFIERS.
RULES FOR WRITING IDENTIFIERS
 Identifier can be a combination of lowercase letters (a
to z) or uppercase letters (A-Z) or digits (0-9) or an
underscore (_).

 An Identifier can start with an alphabet or an


underscore(_), but not with a digit.

 Keywords can not be used as identifiers. Keywords are


reserved words in Python which have a special
meaning.

 Few examples of Keywords: def, and, not, for, while,


if, else and so on.

 Special symbols are not allowed in Identifiers. Only one


special symbol Underscore (_) is allowed.
 Python is a case-sensitive programming
language. Means, Age and age are two
different Identifiers.
IDENTIFY VALID AND INVALID
IDENTIFIERS
 my_variable = 10
 2numbers = 42
 for = 10
 user_name = "Alice"
 _total_count = 100
 MAX_VALUE = 500
 My-variable = 5
 Total$count = 100
PYTHON VARIABLE
 A variable is a specific type of identifier that
refers to a memory location used to store
data.
 Containers for storing data values.
 In Python a variable is created the moment
you first assign a value to it.
 Example:
 x=5
y = "John"
print(x)
print(y)
TWO TYPES OF ERRORS

 Syntax errors
 Runtime errors
SYNTAX ERROR
 when the code you've written doesn't follow the
rules and structure of the programming language
you're using.
 Syntax errors are like grammatical errors in English.
 For example:
 prin("Hello World")
 The Python interpreter generates the following
syntax error as it did not find a name prin (as the
correct method name is print).
RUNTIME ERROR
 Occur due to incorrect algorithm/logic or
wrong operations like dividing by zero during
the program execution.
EXAMPLE OF RUNTIME ERROR
 Write a Program to Print:-
 Python is Easy

 Solution:-
 print(“Python is Easy”)
Interesting ways to use
Print functions
1ST: WITH COMMA AS A
SEPARATOR
2ND: WITH SPACE AS A
SEPARATOR
3RD: WITH REPEAT CHARACTER
 We can print a string n times by using repeat
character (*) as shown below:
EXAMPLE:
VARIABLES AND ASSIGNMENT
 Variable is reserved memory location used to
store values.
 For example: age = 21
 For example: city = “Tokyo”

 Usually in C,C++ and Java, we need to


declare variables along with their types
before using them.
 Python being a dynamically typed language,
there is no need to declare variables or
declare their types before using them.
CONTD…
 Python has no command for declaring a variable.

 A variable is created the moment a value is


assigned to it.

 The equal-to(=) operator is used to assign value


to a variable.

 For example: marks = 100


 Here marks is the variable and 100 is the value
assigned to it.

 Note: As a good programming practice, one


should use meaningful names for variables.
CONTD…
 Python interpreter automatically determines
the type of the data, based on the data
assigned to it.
 In Python, we can even change type of the
variable after it has been set once(or
initialized with some other type).

 This can be done by assigning a value of a


different type to the variable.

 The most commonly used data types in


Python are: Numbers, List, Tuple, Strings,
Dictionary etc.
PYTHON COMMENTS

 Comments can be placed at the end of a line

 Comments starts with a #, and Python will


ignore them

 print("Hello, World!") #This is a comment


TYPES OF COMMENTS IN
PYTHON
 1) Single-line Comment
 2) Docstring Comment
SINGLELINE COMMENT
 It starts with # (hash) and the content
following hash till the end of that line is a
comment
DOCSTRING COMMENT
 A docstring is a string literal used in Python
to document various elements such as
modules, functions, classes, and methods. It
provides a way to describe what the element
does, how it should be used, what
parameters it accepts, what it returns, and
any other relevant information.
 A docstring is typically placed as the first
non-comment statement within the
definition of a module, function, class, or
method. It acts as a form of documentation
that is easily accessible to developers who
are working with the code.
 It serves as a reference for other developers
(and sometimes even for yourself) to
understand the purpose and usage of the
element without needing to read the
implementation details.

 Two types of Docstrings:


 One-line docstring
 Multi-line docstring
When you define a docstring for an element (module, function, class, or method), Python

__doc__ attribute of that object.


automatically assigns the docstring to the
This allows you to access the docstring programmatically.
KEYWORDS
 Reserved words with special meaning and purpose
 Used only for intended purpose
 Cant use it as a function name, variable name or
any identifier name
 Python has its own set of reserved words
 Interpreter uses keywords to recognize structure of
program
 Python provides a way to print list of keywords
Import keyword
Print(keyword.kwlist)
 iskeyword() : builtin function
 Used to check whether a particular word is
keyword or not
 Returns a Boolean value
import keyword
print(keyword.iskeyword('and'))
 How to declare a variable, assign it a value
and print it?
FUNCTION
 Block of organized, reusable code
 Performs specific task
 Take inputs and can optionally return an output (return
value)
 Return is used to return value back from function to
caller
 Break down code into smaller, managable pieces
 Make code more modular, readable and maintainable
 Can have zero or more parameters
 Essential for structuring your code and encapsulating
logic
SYNTAX
 def function_name(parameters):
"""Docstring: Description of what the function does."""
# Function body: Code that defines the function's
behavior
# ...
return result # Optional: Return a value
 def add_numbers(x, y):
"""Adds two numbers and returns the result."""
result = x + y
return result

# Call the function


sum_result = add_numbers(5, 7)
print("Sum:", sum_result) # Output: Sum: 12
IF ELIF ELSE
 Used for conditional branching in python
if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition1 is False & condition2 is True
elif condition3:
# Code to execute if both condition1 and condition2 are False
and condition3 is True
else:
# Code to execute if none of the above conditions are True
 Remember: Only the code block associated with the
first “TRUE” condition encountered will be executed
and rest of the branches will be skipped.
 It is used when we have multiple mutually exclusive
statements
 Only one else block
 Can have multiple elif
 Identation is used for each of the if, elif and else
IF CONDITION
if condition:
# Statements to execute if
# condition is true
IF ELIF ELSE
USER INPUT
 input()
# Prompt the user for input
user_input = input("Enter something: ")

# Print the user's input


print("You entered:", user_input)
 isdigit(): returns True if the string only has
the numbers 0-9 in it and False otherwise

 isalpha(): returns True if the string only has


letters (no numbers or punctuation allowed)

You might also like