Python Unit1 Notes
Python Unit1 Notes
• 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
• 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)
• 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
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:
• 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