0% found this document useful (0 votes)
7 views28 pages

Lecture 9,10,11&12 Notes

The document provides an overview of basic Python programming concepts, including variable declaration, data types (Numbers, List, Tuple, Strings, Dictionary), conditional statements, loops, and functions. It outlines the rules for naming variables and explains the characteristics of different data types, as well as how to use conditional statements and loops effectively. Examples are included to illustrate the usage of these concepts in Python programming.
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)
7 views28 pages

Lecture 9,10,11&12 Notes

The document provides an overview of basic Python programming concepts, including variable declaration, data types (Numbers, List, Tuple, Strings, Dictionary), conditional statements, loops, and functions. It outlines the rules for naming variables and explains the characteristics of different data types, as well as how to use conditional statements and loops effectively. Examples are included to illustrate the usage of these concepts in Python programming.
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/ 28

Basic Python Programming:

Variable in Python
A Python variable is a reserved memory location to store values. In other words, a
variable in a python program gives data to the computer for processing.
Every value in Python has a data type. Different data types in Python are
Numbers,List, Tuple, Strings, Dictionary, etc. Variables can be declared by any
name or even alphabets like a, aa, abc, etc
Variable Naming Rules in Python
1. Variable name should start with letter (a-zA-Z) or underscore (_).
Valid: age , _age , Age
Invalid: 1age
2. In variable name, no special characters allowed other than underscore (_).
Valid: age_ , _age
Invalid: age_*
3. Variables are case sensitive.
age and Age are different, since variable names are case sensitive.
4. Variable name can have numbers but not at the beginning.
Example: Age1
5. Variable name should not be a Python keyword. Keywords are also called as
reserved words.
Example
pass, break, continue.. etc are reserved for special meaning in Python. So, we
should
not declare keyword as a variable name.
eg.
a=100
print (a)
Data types
Python Data types are the classification or categorization of data items. It
represents the kind of value that tells what operations can be performed on a
particular data. Since everything is an object in Python programming.
Python has 5 standard data types as
1.Numbers
2.List
3.Tuple
4. Strings
5. Dictionary
1.Numbers
The numeric data type in Python represents the data that has a numeric value. A
numeric value can be an integer, a floating number, or even a complex number.
These values are defined as Python int , Python float , and Python complex classes
in Python .

Integers – This value is represented by int class. It contains positive or negative


whole numbers (without fractions or decimals). In Python, there is no limit to how
long an integer value can be.
Float – This value is represented by the float class. It is a real number with a
floating-point representation. It is specified by a decimal point. Optionally, the
character e or E followed by a positive or negative integer may be appended to
specify scientific notation.
Complex Numbers – A complex number is represented by a complex class. It is
specified as (real part) + (imaginary part)j . For example – 2+3j
2.List
Python Liat are the most versatile compound data types. A Python list contains
items separated by commas and enclosed within square brackets ([]). To some
extent, Python lists are similar to arrays in C. One difference between them is that
all the items belonging to a Python list can be of different data type where as C
array can store elements related to a particular data type.
A list in Python is an object of list class. We can check it with type() function.
As mentioned, an item in the list may be of any data type. It means that a list object
can also be an item in another list. In that case, it becomes a nested list.
A list can have items which are simple numbers, strings, tuple, dictionary, set or
object of user defined class also.
The values stored in a Python list can be accessed using the slice operator ([ ] and
[:]) with indexes starting at 0 in the beginning of the list and working their way to
end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is
the repetition operator.
Example of List
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists
This produce the following result −
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
3.Tuple
Tuple s another sequence data type that is similar to a list. A Python tuple consists
of a number of values separated by commas. Unlike lists, however, tuples are
enclosed within parentheses (...).
A tuple is also a sequence, hence each item in the tuple has an index referring to its
position in the collection. The index starts from 0.
In Python, a tuple is an object of tuple class. We can check it with the type()o form
a tuple, use of parentheses is optional. Data items separated by comma without any
enclosing symbols are treated as a tuple by default.function.
Example of Tuple data Type
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print (tuple) # Prints the complete tuple
print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) Example of Tuple data Type
Open Compiler
# Prints elements of the tuple starting from 2nd till 3rd
print (tuple[2:]) # Prints elements of the tuple starting from 3rd element
print (tinytuple * 2) # Prints the contents of the tuple twice
print (tuple + tinytuple) # Prints concatenated tuples
This produce the following result −

('abcd', 786, 2.23, 'john', 70.2)


abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
The main differences between lists and tuples are: Lists are enclosed in brackets ( [
] ) and their elements and size can be changed i.e. lists are mutable, while tuples
are enclosed in parentheses ( ( ) ) and cannot be updated (immutable). Tuples can
be thought of as read-only lists.
4. Strings
Python Strings is a sequence of one or more Unicode characters, enclosed in
single, double or triple quotation marks (also called inverted commas). Python
strings are immutable which means when you perform an operation on strings, you
always produce a new string object of the same type, rather than mutating an
existing string.
As long as the same sequence of characters is enclosed, single or double or triple
quotes don't matter. Hence, following string representations are equivalent.
A string is a non-numeric data type. Obviously, we cannot perform arithmetic
operations on it. However, operations such as slicing and concatenation can be
done. Python's str class defines a number of useful methods for string processing.
Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes
starting at 0 in the beginning of the string and working their way from -1 at the
end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator in Python.
Example of String
str = 'Hello World!'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string
This will produce the following result −
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

5. Dictionary

Dictionary is kind of hash table type. A dictionary key can be almost any Python
type, but are usually numbers or strings. Values, on the other hand, can be any
arbitrary Python object.

Python dictionary is like associative arrays or hashes found in Perl and consist
of key:value pairs. The pairs are separated by comma and put inside curly brackets
{}. To establish mapping between key and value, the semicolon':' symbol is put b
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and
accessed using square braces ([]).

Example of Dictionary Data Type

Open Compiler

dict = {}

dict['one'] = "This is one"


dict[2] = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

print (dict['one']) # Prints value for 'one' key

print (dict[2]) # Prints value for 2 key

print (tinydict) # Prints complete dictionary

print (tinydict.keys()) # Prints all the keys

print (tinydict.values()) # Prints all the values

This produce the following result −

This is one

This is two

{'dept': 'sales', 'code': 6734, 'name': 'john'}

['dept', 'code', 'name']

['sales', 6734, 'john']etween the two.

Conditional Statements in Python

Conditional statements in Python are used to execute certain blocks of code based
on specific conditions. These statements help control the flow of a program,
making it behave differently in different situations.

If Conditional Statement in Python


If statement is the simplest form of a conditional statement. It executes a block of
code if the given condition is true.
Example:
age = 20
if age >= 18:
print("Eligible to vote.")
Output:
Eligible to Vote.
If else Conditional Statements in Python
It allows us to specify a block of code that will execute if the condition(s)
associated with an if or elif statement evaluates to False. Else block provides a way
to handle all other cases that don't meet the specified conditions.
Example:
age = 10
if age <= 12:
print("Travel for free.")
else:
print("Pay for ticket.")
Output:
Travel for free.
elif Statement
elif statement in Python stands for "else if." It allows us to check multiple
conditions , providing a way to execute different blocks of code based on which
condition is true. Using elif statements makes our code more readable and efficient
by eliminating the need for multiple nested if statements.
Example:
age = 25
if age <= 12:
print("Child.")
elif age <= 19:
print("Teenager.")
elif age <= 35:
print("Young adult.")
else:
print("Adult.")
Output
Young adult.
Here, the first condition x > 15 is False, so the elif condition x > 5 is checked next.
Since it is True, the corresponding block is executed.
Nested if..else Conditional Statements in Python
Nested if..else means an if-else statement inside another if statement. We can use
nested if statements to check conditions within conditions.
age = 70
is_member = True
if age >= 60:
if is_member:
print("30% senior discount!")
else:
print("20% senior discount.")
else:
print("Not eligible for a senior discount.")
Output:
30% senior discount!
Loops in Python
Loops in Python are used to repeat actions efficiently. The main types are For
loops (counting through items) and While loops (based on conditions).
Additionally, Nested Loops allow looping within loops for more complex tasks.
While all the ways provide similar basic functionality, they differ in their syntax
and condition-checking time. In this article, we will look at Python loops and
understand their working with the help of examples.
While Loop in Python
In Python, a while loop is used to execute a block of statements repeatedly until a
given condition is satisfied. When the condition becomes false, the line
immediately after the loop in the program is executed.
Python While Loop Syntax:
while expression:
statement(s)
All the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python
uses indentation as its method of grouping statements.
Example of Python While Loop:
cnt = 0
while (cnt < 3):
cnt = cnt + 1
print("Hello Geek")
Output
Hello Geek
Hello Geek
Hello Geek
Using else statement with While Loop in Python
Else clause is only executed when our while condition becomes false. If we break
out of the loop or if an exception is raised then it won’t be executed.
Syntax of While Loop with else statement:
while condition:
# execute these statements
else:
# execute these statements
Example:
The code prints “Hello Geek” three times using a ‘while’ loop and then after the
loop it prints “In Else Block” because there is an “else” block associated with the
‘while’ loop.
cnt = 0
while (cnt < 3):
cnt = cnt + 1
print("Hello Geek")
else:
print("In Else Block")

Output:
Hello Geek
Hello Geek
Hello Geek
In Else Block
Infinite While Loop in Python
If we want a block of code to execute infinite number of times then we can use the
while loop in Python to do so.
The code given below uses a ‘while’ loop with the condition (count == 0) and this
loop will only run as long as count is equal to 0. Since count is initially set to 0, the
loop will execute indefinitely because the condition is always true.
count = 0
while (count == 0):
print("Hello Geek")
For Loop in Python
For loops are used for sequential traversal. For example: traversing a list or string
or array etc. In Python, there is “for in” loop which is similar to foreach loop in
other languages. Let us learn how to use for loops in Python for sequential
traversals with examples.
For Loop Syntax:
for iterator_var in sequence:
statements(s)
n=4
for i in range(0, n):
print(i)
Output
0
1
2
3
Python Functions
Python Functions is a block of statements that return the specific task. 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.

You might also like