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

Python Unit1 Notes

This document provides an overview of Python fundamentals, including its characteristics, structure, variables, data types, and functions. It highlights Python's interpreted nature, ease of learning, and dynamic typing, along with examples of variable creation and function definitions. Key concepts such as indentation, comments, and type conversion are also discussed to aid understanding of Python programming.

Uploaded by

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

Python Unit1 Notes

This document provides an overview of Python fundamentals, including its characteristics, structure, variables, data types, and functions. It highlights Python's interpreted nature, ease of learning, and dynamic typing, along with examples of variable creation and function definitions. Key concepts such as indentation, comments, and type conversion are also discussed to aid understanding of Python programming.

Uploaded by

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

Unit -1 Python Fundamentals

Created By: Prof. Priti Dhimmar


Concepts of Interpreter based
programming language
• Python is an interpreted, interactive, object-oriented, and high-level
programming language. It was created by Guido van Rossum during
1985-1990. Python is designed to be highly readable. It is used in web
development, data science, software prototypes, and so on. Python
has a simple, easy-to-use syntax. This makes Python an excellent
programming language to learn for beginners. Python can be used for
web development, back-end development, software development,
data science, and general-purpose programming.
Characteristics of Python
• Python is Interpreted: Python is processed at runtime by the
interpreter. You do not need to compile your program before
executing it. This is similar to PERL and PHP.
• Python is Interactive: Users can open the Python prompt and interact
with the interpreter directly to write programs.
• Python is Object-Oriented: Python supports object-oriented
methodology.
• Easy to Learn: Python has a straightforward syntax, making it easy for
beginners.
• Versatile: Can be used as a scripting language or compiled to byte-
code for building large applications.
• Dynamic Typing: Provides high-level dynamic data types and supports
runtime type checking.
• Automatic Garbage Collection: Python handles memory management
automatically.
• Integration: Can be easily integrated with C, C++, COM, ActiveX,
CORBA, and Java.
Structure of Python
Programming Language:
• Many programming languages have a special function , usually called
main(). Which is executed automatically when a program starts.
However python does not require a main() function. Instead the
interpreter executes the scripts starting at the top of the file.
• Python File Types:
• File: Any Python file containing code, typically with a .py extension.
• Script : A Python file intended to be executed from the command line
to accomplish a task.
• Module: A Python file intended to be imported into another script or
interactive interpreter.
Example of Python File
Structure:
• A common approach is to create a main python file (main.py), which
acts as the entry point, and import other python files(modules)
containing different function as needed.
• Example File Structure:
• top_module.py ---> module1.py, module2.py ---> Standard Library
Modules
Python Fundamentals

• top_module.py is treated as the main module. It imports other modules:


module1.py and module2. These modules can call functions defined in each
other to use function within.
• There are many standard library modules available in python, which can be
imported into any module to use finction defined within them.
• Although there is no defined structure for writing a Python program, the most
commonly used structure is shown below:
• Import Section: Here we can import standard library modules
• (eg. Math) or user- created modules.
• import math # system module
• import main1 # user-created module
• Function Definition Section: This section provides different function
definitions. These functions can be used in the same file or in another
file after importing it.
• Function Call Section: Here, we can call different functions that are
either defined in this file or imported from other files/modules.
Example:

• file1.py
• print("Always executed")if __name__ == "__main__":
print("Executed when invoked directly")else: print("Executed when
imported")

• file2.py
• # Import sectionimport math # system moduleimport file1 # user-
created moduleprint("Value of pi is:", math.pi)print("Factorial of 5 is:",
math.factorial(5))
• Output:
• When file1.py is run
• Always executed
• Executed when invoked directly
• When file 2 executed :
• Always executed
Executed when imported
Value of pi is: 3.141592653589793
Factorial of 5 is: 120
Python Indentation

• In Python, indentation is used to define blocks of code. It tells the Python interpreter
that a group of statements belongs to a specific block. All statements with the same
level of indentation are considered part of the same block. Indentation is achieved
using whitespace (spaces or tabs) at the beginning of each line.
• Indentation refers to the spaces at the beginning of a code line.
• Where in other programming languages the indentation in code is for readability only,
the indentation in Python is very important.
• Python uses indentation to indicate a block of code.
• if 5 > 2:
print("Five is greater than two!")
• o/p:
• Python will give you an error if you skip the indentation:
• if 5 > 2:
print("Five is greater than two!")
• o/p:
The number of spaces is up to you
as a programmer, but it has to be at
least
• if 5 > 2:
one.
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
• if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Python Variables

• Variables are containers for storing data values.


• Creating Variables
• Python has no command for declaring a variable.
• A variable is created the moment you first assign a value to it.
• In Python, variables are created when you assign a value to it:
• Example
• Variables in Python:
• x=5
y = "Hello, World!"
• print(x)
• print(y)
• output: 5
• Hello World
Variable Names

• A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume). Rules for Python variables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
• A variable name cannot be any of the Python keywords.
• Legal variables:
• myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John“
Illegal variable names:
• 2myvar = "John"
my-var = "John"
my var = "John“
• o/p:error
• Remember that variable names are case-sensitive
• Many Values to Multiple Variables
• x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
• o/p:
One Value to Multiple Variables
• x = y = z = "Orange"
print(x)
print(y)
print(z)
• o/p:
Dynamic Declaration of Variables in
Python
• Python allows dynamic typing, meaning you do not need to declare variable types
explicitly. Variables are created when assigned a value.
• x = 10 # x is an integer
• x = "Hello" # x is now a string
• x = 3.14 # x becomes a float
• Since Python is dynamically typed, the same variable can hold different types of
data during execution. name=input("enter your name")
print("hello"+name)

• Using input() for dynamic variable Assignment print(f"hello{name}")

• name = input("Enter your name: ") # User input dynamically assigns a string
• age = int(input("Enter your age: ")) # Converts input to an integer
• print(f"Hello {name}, you are {age} years old.")
• F- strings simplify string formatting.
• {} helps dynamically insert values into strings.
• They improve readability, handle type conversion, and support
expressions efficiently.
• In Python, the f-string (formatted string literals) allows you to
insert variables directly into a string using curly braces{}.
• The f before the string tells Python to evaluate expressions inside
{} and replace them with their values.
Comments in python
• Comments can be used to explain Python code.
• Comments can be used to make the code more readable.
• Comments can be used to prevent execution when testing code.
• Creating a Comment
• comments start with # and python will ignore them.
• Eg:
• #This is a comment
print("Hello, World!")
• o/p:
• print("Hello, World!") #This is a comment
Multiline Comments
• Python does not really have a syntax for multiline comments.
• Since Python will ignore 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:
• """
This is a comment
written in
more than just one line
"""
print("Hello, World!")
• o/p:
Global Variables
• Variables that are created outside of a function (as in all of the
examples in the previous pages) are known as global variables.
• Global variables can be used by everyone, both inside of functions
and outside.
• x = "awesome"

def myfunc():
print("Python is " + x)

myfunc()
• Output:

• If you create a variable with the same name inside a function, this
variable will be local, and can only be used inside the function. The
global variable with the same name will remain as it was, global and
with the original value.
• x = "awesome"

def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
• o/p:
The global Keyword
• Normally, when you create a variable inside a function, that variable is local, and
can only be used inside that function.
• To create a global variable inside a function, you can use the global keyword.
• eg:
• If you use the global keyword the variables belongs to the global scope.
• def myfunc():
global x
x = "fantastic"

myfunc()

print("Python is " + x)
• o/p: python is fantastic.
• also use the global keyword if you want to change a global variable inside a function.
• Eg:
• to change the value of global variable inside a function refer to the variable by using the
global keyword
• x = "awesome"

def myfunc():
global x
x = "fantastic"

myfunc()

print("Python is " + x)
• o/p: Python is fantastic
Python Data Types
• Built-in Data Types
• In programming, data type is an important concept.
• Variables can store data of different types, and different types can do different
things.
• Python has the following data types built-in by default, in these categories:
• Text Type:str
• Numeric Types:int, float, complex
• Sequence Types:list, tuple, range
• Mapping Type:dict
• Boolean Type:bool
• In python, str(string) is the primary text type.
• A string is a sequence of characters enclosed in single (' .
), double ("), or triple (''' """) quotes

• # Using single or double quotes


• text1 = "Hello, World!"
• text2 = 'Python is fun!'
• print(type(text1)) # Output: <class 'str'>
• Multiline string:
• multi_line = """This is a
• multi-line string."""
• print(multi_line)
Numeric Types
• Numeric types are used to store numerical values in Python.
• # Integer (int)
• a = 10
• b = -5
• print(type(a)) # Output: <class 'int'>
• # Floating point (float)
• c = 3.14
• d = -0.5
• print(type(c)) # Output: <class 'float'>

• # Complex number (complex)


• e = 2 + 3j
• f = 1 - 1j
• print(type(e)) # Output: <class 'complex'>
Sequence Types
• Sequence types store collections of items in an ordered manner.
• # String (str)
• text = "Hello, Python!"
• print(type(text)) # Output: <class 'str'>
• # List (list) – Mutable- we can change after create the list
• fruits = ["apple", "banana", "cherry"]
• fruits.append("orange") # Modifying the list
• print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']
• print(type(fruits)) # Output: <class 'list'>
• # Tuple (tuple) – Immutable- we can not change after create no update no add
• coordinates = (10, 20, 30)
• print(type(coordinates)) # Output: <class 'tuple'>
• # Range (range)
• numbers = range(5) # Equivalent to [0, 1, 2, 3, 4]
• print(list(numbers)) # Output: [0, 1, 2, 3, 4]
• print(type(numbers)) # Output: <class 'range'>
• Range use in loops:
• for i in range(5): # Generates numbers: 0, 1, 2, 3, 4
• print(i)
• The Boolean data type represents two values only:
• True
•False
• In Python, Boolean values are case-sensitive, so always use

True and False with a capital first letter.


Eg: x = True
y = False
print(type(x)) # Output: <class 'bool'>
print(type(y)) # Output: <class 'bool'>
Python Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods: x = 1 # int
y = 2.8 # float
z = 1j # complex

#convert from int to float:


a = float(x)

#convert from float to int:


b = int(y)

#convert from int to complex:


c = complex(x)

print(a)
print(b)
print(c)

print(type(a))
print(type(b))
print(type(c))
Python Casting
• Specify a Variable Type
• There may be times when you want to specify a type on to a variable. This can be done with
casting. Python is an object-orientated language, and as such it uses classes to define data types,
including its primitive types.
• Casting in python is therefore done using constructor functions:
• int() - constructs an integer number from an integer literal, a float literal (by removing all
decimals), 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
• x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
• Float: x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
• string:
• x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
User define Function
• A function is a set of statements that take inputs, do some specific computation, and
produce output. The idea is to put some commonly or repeatedly done tasks together
and make a function so that instead of writing the same code again and again for
different inputs, we can call the function. Functions that readily come with Python are
called built-in functions. Python provides built-in functions like print(), etc. but we can
also create your own functions. These functions are known as user defines functions.
• Syntax: def function_name():
statements
# Declaring a function
Eg:
def fun():
Print("Inside function")
# Driver's code # Calling function
fun()
o/p: Inside function
Function with parameter
• The function may take arguments(s) also called parameters as input within
the opening and closing parentheses, just after the function name followed
by a colon.
Syntax: def function_name(argument1, argument2, ...):
statements
• Example:

• A simple Python function to check whether x is even or odd.


def evenOdd( x ): if (x % 2 == 0):
("even") else:
("odd") # Driver code
evenOdd(2)
evenOdd(3)
Parameter with default value
• A default argument is a parameter that assumes a default value if a
value is not provided in the function call for that argument. The
following example illustrates Default arguments.
def myFun(x, y = 50):
("x: ", x)
("y: ", y)
myFun(10)
o/p:
Function with return value
• Sometimes we might need the result of the function to be used in further processes.
Hence, a function should also return a value when it finishes its execution. This can be
achieved by a return statement.
A return statement is used to end the execution of the function call and “returns” the
result (value of the expression following the return keyword) to the caller. The
statements after the return statements are not executed. If the return statement is
without any expression, then the special value None is returned.
• Syntax:
• def fun():
• statements
.
.
return [expression]
• In Python, a function can return a value using the returnkeyword

• When a function is called, it can perform some operations and then send back a result, which can be
assigned to a variable or used directly
• # Define a function that adds two numbers
• def add_numbers(a, b):
• result = a + b
• return result # The return statement sends the result back to the caller

• # Call the function and store the returned value


• sum_result = add_numbers(3, 5)

• # Print the returned value


• print(sum_result) # Output will be 8

You might also like