[go: up one dir, main page]

0% found this document useful (0 votes)
33 views19 pages

Unit 1 Notes

This document provides an overview of the Python programming language. It discusses that Python is an interpreted, object-oriented programming language created by Guido van Rossum in 1991. It can be used for web development, software development, mathematics, and system scripting. The document then covers what Python can do, why Python is a good language to use, important details about Python versions, and compares Python syntax to other languages. It also includes examples of basic Python code and concepts like variables, data types, comments, and functions.

Uploaded by

arjun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views19 pages

Unit 1 Notes

This document provides an overview of the Python programming language. It discusses that Python is an interpreted, object-oriented programming language created by Guido van Rossum in 1991. It can be used for web development, software development, mathematics, and system scripting. The document then covers what Python can do, why Python is a good language to use, important details about Python versions, and compares Python syntax to other languages. It also includes examples of basic Python code and concepts like variables, data types, comments, and functions.

Uploaded by

arjun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

What is Python?

Python is a popular programming language. It was created by Guido van Rossum, and released in
1991.
It is used for:
 web development (server-side),
 software development,
 mathematics,
 system scripting.
What can Python do?
 Python can be used on a server to create web applications.
 Python can be used alongside software to create workflows.
 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.
Why Python?
 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.
 Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
 Python can be treated in a procedural way, an object-oriented way or a functional way.
Good to know
 The most recent major version of Python is Python 3, which we shall be using in this tutorial.
However, Python 2, although not being updated with anything other than security updates, is
still quite popular.
 In this tutorial Python will be written in a text editor. It is possible to write Python in an
Integrated Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which
are particularly useful when managing larger collections of Python files.
Python Syntax compared to other programming languages
 Python was designed for readability, and has some similarities to the English language with
influence from 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.
Example
print("Hello, World!")

Python Indentation
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.
Example
if 5 > 2:
print("Five is greater than two!")
Python will give you an error if you skip the indentation:
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
The number of spaces is up to you as a programmer, the most common use is four, but it has to be at
least one.
Example
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
You have to use the same number of spaces in the same block of code, otherwise Python will give you
an error:
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Python Variables
In Python, variables are created when you assign a value to it:
Example
Variables in Python:
x=5
y = "Hello, World!"
Python has no command for declaring a variable.
Comments
Creating a Comment
Comments starts with a #, and Python will ignore them:
Example
#This is a comment
print("Hello, World!")
Comments can be placed at the end of a line, and Python will ignore the rest of the line:
A comment does not have to be text that explains the code, it can also be used to prevent Python from
executing code:
Multiline Comments
Python does not really have a syntax for multiline comments.
To add a multiline comment you could insert a # for each line:
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Or, not quite as intended, you can use a multiline string.
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:
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
As long as the string is not assigned to a variable, Python will read the code, but then ignore it, and
you have made a multiline comment.
Python Variables
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.
ExampleGet your own Python Server
x=5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type, and can even change type after they
have been set.
Example
x=4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Get the Type
You can get the data type of a variable with the type() function.
Example
x=5
y = "John"
print(type(x))
print(type(y))
Single or Double Quotes?
String variables can be declared either by using single or double quotes:
Example
x = "John"
# is the same as
x = 'John'
Case-Sensitive
Variable names are case-sensitive.
Example
This will create two variables:
a=4
A = "Sally"
#A will not overwrite a
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.
ExampleGet your own Python Server
Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Example
Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"
Multi Words Variable Names
Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:
Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "John"

Pascal Case
Each word starts with a capital letter:
MyVariableName = "John"

Snake Case
Each word is separated by an underscore character:
my_variable_name = "John"

Many Values to Multiple Variables


Python allows you to assign values to multiple variables in one line:
ExampleGet your own Python Server
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
One Value to Multiple Variables
And you can assign the same value to multiple variables in one line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the values into
variables. This is called unpacking.
Example
Unpack a list:
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
Output Variables
The Python print() function is often used to output variables.
ExampleGet your own Python Server
x = "Python is awesome"
print(x)
In the print() function, you output multiple variables, separated by a comma:
Example
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
output: Python is awesome
You can also use the + operator to output multiple variables:
Example
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
output: Python is awesome

For numbers, the + character works as a mathematical operator:


Example
x=5
y = 10
print(x + y)
output: 15
In the print() function, when you try to combine a string and a number with the + operator, Python
will give you an error:
Example
x=5
y = "John"
print(x + y)

TypeError: unsupported operand type(s) for +: 'int' and 'str'

The best way to output multiple variables in the print() function is to separate them with commas,
which even support different data types:
Example
x=5
y = "John"
print(x, y)
Global Variables
Variables that are created outside of a function (as in all of the examples above) are known as global
variables.
Global variables can be used by everyone, both inside of functions and outside.
Example
Create a variable outside of a function, and use it inside the function
x = "awesome"

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

myfunc()
output: Python is awesome
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.
Example
Create a variable inside a function, with the same name as the global variable
x = "awesome"

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

myfunc()

print("Python is " + x)
output Python is fantastic
Python is awesome
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.
Example
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = "fantastic"

myfunc()

print("Python is " + x)
output Python is fantastic
Also, use the global keyword if you want to change a global variable inside a function.
Example
To change the value of a 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)
output Python is fantastic

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

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

None Type: NoneType


Python Numbers
There are three numeric types in Python:
 int
 float
 complex
Variables of numeric types are created when you assign a value to them:
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex

To verify the type of any object in Python, use the type() function:
Example
print(type(x))
print(type(y))
print(type(z))

Int
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
Example Integers:
x=1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))

Float
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.
Example Floats:
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Float can also be scientific numbers with an "e" to indicate the power of 10.
Example Floats:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))

Complex: Complex numbers are written with a "j" as the imaginary part:
Example Complex:
x = 3+5j
y = 5j
z = -5j
print(type(x))print(type(y))print(type(z))
Random Number
Python does not have a random() function to make a random number, but Python has a built-
in module called random that can be used to make random numbers:
Example
Import the random module, and display a random number between 1 and 9:
import random
print(random.randrange(1, 10))

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
 Arithmetic Operators

 Comparison Operators

 Logical Operators

 Bitwise Operators
# Examples of Bitwise operators
a = 10
b=4

# Print bitwise AND operation


print(a & b)

# Print bitwise OR operation


print(a | b)

# Print bitwise NOT operation


print(~a)

# print bitwise XOR operation


print(a ^ b)

# print bitwise right shift operation


print(a >> 2)

# print bitwise left shift operation


print(a << 2)
 Assignment Operators

 Identity Operators

Identity operators are used to compare the objects, not if they are equal, but
if they are actually the same object, with the same memory location:

Example
a = 10
b = 20
c=a
print(a is not b)
print(a is c)

 Membership Operators

Membership operators are used to test if a sequence is presented in an


object:

x = 24
y = 20
list = [10, 20, 30, 40, 50]
if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")
if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
Operator Precedence
Operator precedence describes the order in which operations are performed
If two operators have the same precedence, the expression is evaluated from left to right.

Input from User in Python


Sometimes a developer might want to take user input at some point in the program. To do
this Python provides an input() function.
Syntax:
input('prompt')
where prompt is an optional string that is displayed on the string at the time of taking input.
# Taking input from the user
name = input("Enter your name: ")

# Output
print("Hello, " + name)
print(type(name))

Multiple Inputs in Python :


we can take multiple inputs of the same data type at a time in python, using map() method
in python.
a, b, c = map(int, input("Enter the Numbers : ").split())
print("The Numbers are : ",end = " ")
print(a, b, c)

output
Enter the Numbers : 2 3 4
The Numbers are : 2 3 4

Display Output in Python


Python provides the print() function to display output to the standard output devices.
Syntax: print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)
Parameters:
value(s) : Any value, and as many as you like. Will be converted to string before printed
sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than
one.Default :’ ‘
end=’end’: (Optional) Specify what to print at the end.Default : ‘\n’
file : (Optional) An object with a write method. Default :sys.stdout
flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False).
Default: False
Returns: It returns output to the screen.

# Python program to demonstrate


# print() method
print("GFG")

# code for disabling the softspace feature


print('G', 'F', 'G')

output
GFG
GFG

# Python program to demonstrate


# print() method
print("GFG", end = "@")

# code for disabling the softspace feature


print('G', 'F', 'G', sep="#")
Output
GFG@G#F#G

Using formatted string literals

We can use formatted string literals, by starting a string with f or F before opening
quotation marks or triple quotation marks. In this string, we can write Python expressions
between { and } that can refer to a variable or any literal value.
Example: Python String formatting using F string
# Declaring a variable
name = "Gfg"
print(f'Hello {name}! How are you?')
Output:
Hello Gfg! How are you?

Using format()

We can also use format() function to format our output to make it look presentable. The
curly braces { } work as placeholders. We can specify the order in which variables occur in
the output.
Example: Python string formatting using format() function
# Initializing variables
a = 20
b = 10
# addition
sum = a + b

# subtraction
sub = a- b

print('The value of a is {} and b is {}'.format(a,b))


print('{2} is the sum of {0} and {1}'.format(a,b,sum))
print('{sub_value} is the subtraction of {value_a} and {value_b}'.format(value_a = a ,
value_b = b, sub_value = sub))

Output:
The value of a is 20 and b is 10
30 is the sum of 20 and 10
10 is the subtraction of 20 and 10

Control Flow Statements

Control structure Without using Control structure sequence of execution of statements in a


program is line by line and every statement is executed once .
In python we can divide the control structure into two parts
1. conditional control statement
i. If ... Else
ii. if....else
iii. if.......elif....... Else
2. looping/iterative control structure
i. While Loops
ii. For Loops

if Syntax
if (condition) :
Statement 1
Statement 2
…………
Statement n

if.......elif....... Else
While
While (condition):
statements
ex:
i = 1
while i < 6:
print(i)
i += 1

for A for loop is used for iterating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string).

for counter in sequence:


statements(s)

Example:
for i in range(5):
print(i)

for x in "banana":
print(x)

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
if x == "banana":
break
Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)
Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":

FUNCTIONS
 A function is a block of code which only runs when it is called. 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 do the function
calls to reuse code contained in it over and over again.
 Creating a Function
In Python a function is defined using the def keyword.
Example
def my_function():
print("Hello from a function")
 Calling a Function
To call a function, use the function name followed by parenthesis:
Example
 def my_function():
print("Hello from a function")
my_function()
 Return statement in Python function
The function return statement is used to exit from a function and go back to the function
caller and return the specified value or data item to the caller.
Syntax:
return [expression_list]

 The return statement can consist of a variable, an expression, or a constant which is


returned to the end of the function execution. If none of the above is present with the
return statement a None object is returned.
Example:
def square_value(num):
/ /This function returns the square value of the entered number
return num**2
print(square_value(2))
print(square_value(4))

Arguments are used to call a function and there are primarily 4 types of functions that
one can use:
 Positional (Required )arguments
 Default Arguments
 Keyword Arguments
 Variable-length arguments (Arbitrary Arguments)

 Positional Arguments (Required Arguments) are the arguments passed to a


function in correct positional order. Here, the number of arguments in the function
call should match exactly with the function definition.
Example:
def add(a,b):
sum =a+b
return sum
result=add(7,6)
print(result)

 Default Arguments - In Python the default argument is an argument that takes a


default value if no value is provided in the function call. The following example uses
default arguments, that prints default value when no argument is passed.
Example:
def add(a=10,b=20):
sum =a+b
return sum
result=add(7)
print(result)

 Keyword arguments will invoke the function after the parameters are recognized by
their parameter names. The value of the keyword argument is matched with the
parameter name and so, one can also put arguments in improper order (not in order).
Example:
def display(a,b):
print(a,b)
display(b=20,a=10)

Variable-Length Arguments -In some instances you might need to pass more arguments
than have already been specified. Going back to the function to redefine it can be a tedious
process. Variable-Length arguments can be used instead. These are not specified in the
function’s definition and an asterisk (*) is used to define such arguments.
Example:
def display(*course):
for I in course:
print(I)
display(“MCA”,”MBA”,”BCA”)

Passing a List as an Argument


You can send any data types of argument to a function (string, number, list, dictionary etc.),
and it will be treated as the same data type inside the function.
E.g. if you send a List as an argument, it will still be a List when it reaches the function:
Example
def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]


my_function(fruits)
Recursion
Python also accepts function recursion, which means a defined function can call itself.
In this example, tri_recursion() is a function that we have defined to call itself ("recurse").
We use the k variable as the data, which decrements (-1) every time we recurse. The
recursion ends when the condition is not greater than 0 (i.e. when it is 0).
Example
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result

print("\n\nRecursion Example Results")


tri_recursion(6)

Anonymous functions
In Python Function - In Python, an anonymous function means that a function is without a
name. As we already know the def keyword is used to define the normal functions and the
lambda keyword is used to create anonymous functions.
Example :
def cube(x): return x*x*x
cube_v2 = lambda x : x*x*x
print(cube(7))
print(cube_v2(7))

You might also like