0% found this document useful (0 votes)
2 views13 pages

Python.notes

The document provides an overview of Python programming, covering topics such as variables, data types, comments, operators, control structures (if statements, loops), functions, and file handling. It explains how to define and use variables, perform type casting, handle user input, and utilize various operators. Additionally, it includes examples and practice problems to reinforce the concepts discussed.

Uploaded by

jfullel
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
2 views13 pages

Python.notes

The document provides an overview of Python programming, covering topics such as variables, data types, comments, operators, control structures (if statements, loops), functions, and file handling. It explains how to define and use variables, perform type casting, handle user input, and utilize various operators. Additionally, it includes examples and practice problems to reinforce the concepts discussed.

Uploaded by

jfullel
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 13

Variables in Python -

Variables in Python are used to store information . Variables are containers that are used to store
data.

You just assign a value to a variable using the = operator.

Example

name = “Bigya Panta”


address = “USA”
print(name)
print(address)

Legal Variable Names


myvar = "Avany"
my_var = "John"
_my_var = "John"
myVar = "John" (You can use this too)
MYVAR = "John"
myvar2 = "John"
numb1 = 5

Illegal Variable Names

2myvar = "Miraj" (This is illegal)


my-var = "Miraj" (This is illegal)
my var = "Miraj" ( This is illegal)

Comments in Python

In Python, comments are used to explain code and make it more readable. Comments are
ignored during execution.

# This is a comment in Python.

Data Types in Python

In Python, data types are used to define the type of a value stored in a variable.

In Python, data types are a classification that dictates what type of value a variable can hold and
what operations can be performed on it
String - Bigya , Kathmandu , Nepal, coding king - It in enclosed in “ ”.
int - 5 , 6 , 7 , 8 , 9
float - 3.4 , 4.5 , 6.6

Boolean , list , tuple , set , dict - Dictionary

type function in Python is used to return the data type of the object / variable.

name = “Bigya Pant”


age = 10
address = “Tokha”
print(type(name))
print(type(age))
print(type(address))

Type Casting in Python / Type conversion


Type casting in Python refers to converting a variable from one data type to another. This can be
useful when you need to perform operations that require a specific type of data.

int( ): Converts a value to an integer.


float( ): Converts a value to a floating-point number.
str( ): Converts a value to a string.

a = 10
b = 3.8
converted_a = float(a)
converted_b = int(b)
print(converted_a)
print(converted_b)

a = int(3.8)
b = float(3)
print(a)
print(b)
print(type(a))
print(type(b))

Boolean
In general, a Boolean variable can have only two values - True or False
In Python, the Boolean data type is used to represent two values, and it has two possible values:
True and False Boolean in Python.
print(3>2) - True
print(5==5) - True
print(5>7) - False
print(3>11) - False
print(4==5) - False

if statement
In computer programming, the if statement is a conditional
statement. It is used to execute a block of code only when a specific
condition is met.

In Python, if statements are used to execute a block of code only if


a specified condition is true.

Syntax
if condition:
# code to execute if the condition is true

if else
An if statement can have an optional else clause. The else
statement executes if the condition in the if statement evaluates to
False.

if (3>2):
print(“This gets executed if condition is true”)

else:
print(“I am executed if the above condition is false”)

elif in Python
‘elif’ stands for ‘else if’ and is used in Python programming to test
multiple conditions. It is written following an if statement in Python
to check an alternative condition if the first condition is false. The
code block under the elif statement will be executed only if its
condition is true.
if condition1:
statement to execute if condition1 is true
elif condition2:
statement to execute if condition2 is true
else :
statement to execute if both conditions are false

User Input -
User Input. Python allows for user input. That means we are able to ask the user for input. For
String use . input( )
For integer use: int(input( ))

name = input("Enter your name:")


print("hello",name,"Welcome to our coding class")

age = int(input("Enter your age:"))


print("Ohhh so your age is",age)

Operators
In Python, operators are special symbols or keywords used to perform operations on variables
and values.

Arithmetic Operators Python arithmetic operators perform basic mathematical operations on


numeric data, such as addition, subtraction, multiplication, division, modulus .

-, + , * , / , % ,

print(5+3)
print(5-3)
print(3*2)
print(10%2)
print(10/2)

Comparison operators in Python are used to compare two values, variables, or expressions. The
result of a comparison operation is always a Boolean value

Equal to (==): Checks if the values of two operands are equal.


Not equal to (!=): Checks if the values of two operands are not equal.
Greater than (>): Checks if the left operand is greater than the right operand.
Less than (<): Checks if the left operand is less than the right operand
Greater than or equal to (>=): Checks if the left operand is greater than or equal to the right
operand.
Less than or equal to (<=): Checks if the left operand is less than or equal to the right operand.

print(3==3)
print(2!=3)
print(5<3)
print(5>5)
print(5>=5)

Assignment Operators

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3
Python Membership Operators

Membership operators are used to test if a data is

presented in a sequence or not:

in Returns True if a data is present in a sequence such as List.

not in Returns True if a data is not in the sequence

Python Logical Operators

Operator Description

and Returns True if both statements are true

or Returns True if one of the statements is true


not Reverse the result, returns False if the result is true

print(3>2 and 3>21)


print(3>2 or 3>21)

List

List are used to store multiple data items in a single variable.


List is ordered , List can be changed , list index starts from 0

fruits = [“apple”,”litchi”,”mango”,”orange”]
print(fruits)

To add an item to the end of the list, use the append( ) method:

pop method is used to remove a data from a list.

remove method is used to delete a data from the list.

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


thislist.append("orange")
print(thislist)

For Loops
In computer programming, a loop is a sequence of instruction that is continually repeated until a
certain condition is reached.

A loop in programming is a control structure that repeatedly executes a block of code as long as a
specified condition remains true.

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

The range( ) Function


To loop through a set of code a specified number of times, we can use the range( ) function,
The range( ) function returns a sequence of numbers, starting from 0 by default, and increments
by 1 (by default), and ends at a specified number.

for i in range(0,5):
print(“this is python class”)

break statement in python - The break statement in python is used to forcefully end a loop. We
use break statement to end the loop.

for i in range(10):
print(i)
if i == 2:
break

While Loops

In most computer programming languages, a while loop is a control flow statement that allows
code to be executed repeatedly based on a given Boolean condition

i=1
while i < 5:
print(i)
i += 1

Infinite Loop

An infinite loop in Python is a loop that continues to execute indefinitely because its condition
always evaluates to True or there is no condition that stops it.

running = True

while(running):
print(“I am a example of infinite loop”)

Python Functions
A function is a block of code which execute only when it gets called.
To define a function in python we use def keyword.

Advantages of functions

Code Reusability: Write code once and reuse it multiple times.


Modularity: Break complex problems into smaller, manageable tasks.
Easier Debugging: functions makes easier for testing, making debugging easier.
Improved Readability: Functions make the code more organized and easier to read.

Example

def myfunction( ):
print(“Hello this is my function”)

myfunction( )

Practise problem

print("|-----------------------------------|")
print("|Welcome to our Airplane game|")
print("| Press g to land the plane |")
print("| Press l to go left |")
print("| Press r to go right |")
print("|-----------------------------------|")

def land_plane( ):
print("Airbus A380 ready to land")
print("Plane is landing.........")

def go_left( ):
print("Airbus A380 ready to turn left")
print("Plane is turning left.........")

def go_right( ):
print("Airbus A380 ready to turn right")
print("Plane is turning right.........")
choice = input("Enter your choice captain:")

if(choice == "g"):
land_plane()

elif(choice == "l"):
go_left()

elif(choice == "r"):
go_right()

else:
print("Invalid choice! Please enter 'g', 'l', or 'r'.")

Practise problems:

def calculate_volume():
l = int(input("Enter length:"))
b = int(input("Enter breadth:"))
h = int(input("Enter height:"))
volume = l*b*h
print(volume)

def calculate_area():
l = int(input("Enter length:"))
b = int(input("Enter breadth:"))
area = l*b
print(area)

choice = int(input("Enter a choice:"))

if(choice == 1):
calculate_volume()

elif(choice == 2):
calculate_area()

else:
print("Invalid")

return statement in Python

The return statement in Python is used with function and is used to send a value back to the
caller.

Example
def addition( ):
a=5
b = 10
return a+b

print(addition( ))

#File Handling in Python

Python file handling refers to the process of working with files on the filesystem.
File handling in Python allows you to read from and write to files on
your filesystem.

open( ) function to open a file.


The close( ) function in Python is used to close resources such as
files,

Creating a file:

file = open("info.txt","w")
file.write("Hello world ")
file.close()
Reading from a File

file = open("example.txt","r")
content = file.read()
print(content)
file.close()

Practise problem List

books = ["Science","Maths","Social","Grammar"]

def display_books( ):
print(books)

def add_books( ):
b = input("Which book you want to add:")
books.append(b)
print(books)

def remove_books( ):
b = input("Which book you want to delete:")
books.remove(b)
print(books)

choice = int(input("Enter a choice:"))

if(choice == 1):
display_books()

elif(choice == 2):
add_books()

elif(choice == 3):
remove_books()

else:
print("Invalid choice...")
© 2024 codingguruba. All Right Reserved

www.codingguruba.com | Nepal’s #1 live online coding classes

You might also like