0% found this document useful (0 votes)
22 views35 pages

Fy Python Notes

Uploaded by

parkarnetraa
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)
22 views35 pages

Fy Python Notes

Uploaded by

parkarnetraa
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/ 35

Introduction to Programming with Python (FYCS)

 Python Comments
 Comments are lines in a Python program that are not executed by
the interpreter.
 They are used to:
o Explain code and improve readability.
o Temporarily disable lines during debugging.
o Leave reminders or notes for yourself or other developers.

Types of Comments in Python


1. Single-line Comment

 Begins with a # symbol.


 Everything after # on that line is ignored by Python.

Example:
# This is a single-line comment
print("Hello, World!") # This comment is after code

Output:
Hello, World!

2. Multi-line Comment (Using Multiple #)

 You can use multiple # symbols for several lines.


 There’s no official multi-line comment syntax, but this is
common practice.

Example:
# This is a comment
# that spans multiple
# lines
print("Welcome!")
3. Multi-line Strings as Comments (Not Recommended)

 Triple-quoted strings (''' or """) can be used to simulate block


comments.
 These are technically string literals, not real comments, but
if not assigned to a variable, they are ignored.

Example:
"""
This is a multi-line comment
written using triple quotes.
"""
print("Executed code!")

 IDLE (Integrated Development and Learning


Environment) in Python
What is IDLE?
● IDLE is Python’s built-in IDE (Integrated Development
Environment).
● It is written in Python using the Tkinter GUI toolkit.
● Installed by default with standard Python distributions.

Key Features of IDLE


● Python Shell (Interactive Interpreter):
o Opens with >>> prompt.
o Allows testing small code snippets.
o Good for debugging and quick testing.
● File Editor:
o Create and edit .py files.
o Syntax highlighting, auto-indentation.
o Run scripts with F5.
● Debugger:
o Step-through execution.
o Set breakpoints, watch variables.
● Integrated Help:
o Access Python documentation with Help Python Docs .
● Code Completion and Call Tips:
o Press Tab for code suggestions.
o Hover or use keyboard shortcuts to view function parameters.
How to Open IDLE
● Windows/macOS:
o Installed with Python. Open from Start Menu or Finder.
● Linux:
o May need to install separately: sudo apt install idle or idle3.

Running Code
● In Shell:
print("Hello, world!")
● In Editor:
1. Open new file: File New File .
2. Write code, save as .py.
3. Run with Run Run Module or press F5.
Pros and Cons
Pros:
● Lightweight and simple.
● Great for beginners.
● No installation needed if Python is installed.
Cons:
● Not ideal for large projects.
● Limited customization and extensions compared to full IDEs (like
PyCharm or VS Code).

 Python Variables
Variables:

Variables are containers for storing data values.

A variable is a name that refers to a memory location where data


is stored.

It is used to store and manipulate data in a Python program.

Python is dynamically typed, meaning you don’t need to declare


the data type of a variable beforehand
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, you simply use the assignment operator (=) to create a
variable.

Example
x=5 # Integer
name = "John" # String
price = 99.9 # Float

print(x)
print(name)
print(price)

Changing the Data Type of a Variable:

 A variable can change its data type after it's assigned.

Example:

x = 10 # x is an integer
x = "Sally" # Now x is a string

print(x)

Output:-
Sally

 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
print(x)
print(y)r
print(z)ri
Output:-
3
3
3.0

 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 int, float, complex
Types:
Sequence list, tuple, range
Types:
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
None Type: NoneType

Getting the Data Type:

You can get the data type of any object by using


the type() function:

Print the data type of the variable x:


x=5
y = "John"
print(type(x))
print(type(y))

OUTPUT:
<class 'int'>
<class 'str'

 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.

Example
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

print(myvar)
print(my_var)
print(_my_var)
print(myVar)
print(MYVAR)
print(myvar2)

Many Values to Multiple Variables:


Python allows you to assign values to multiple variables in one
line:

x, y, z = "Orange", "Banana", "Cherry"

print(x)
print(y)
print(z)

Orange
Banana
Cherry
One Value to Multiple Variables:
And you can assign the same value to multiple variables in one
line:

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
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.

x = "Python is awesome"
print(x)
Output:-
Python is awesome
In the print() function, you output multiple variables, separated
by a comma:
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
You can also use the + operator to output multiple variables:
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
Python is awesome

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


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

The best way to output multiple variables in the print() function


is to separate them with commas, which even support different
data types:
x=5
y = "John"
print(x, y)

5 John

 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))

 Type Conversion
You can convert from one type to another with the int(), float(),
and complex() methods:

Example
Convert from one type to another:
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))
Note: You cannot convert complex numbers into another number
type.

 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 from 1
to 9:
import random

print(random.randrange(1, 10))

 Strings
Strings in python are surrounded by either single quotation
marks, or double quotation marks.

'hello' is the same as "hello".


You can display a string literal with the print() function:
Example
print("Hello")
print('Hello')

Quotes Inside Quotes:


You can use quotes inside a string, as long as they don't match the
quotes surrounding the string:

Example
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')
Assign String to a Variable:
Assigning a string to a variable is done with the variable name
followed by an equal sign and the string:

Example
a = "Hello"
print(a)

Multiline Strings:
You can assign a multiline string to a variable by using three
quotes:

Example
You can use three double quotes:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

Or three single quotes:

Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)

Python - Slicing Strings


Slicing:
You can return a range of characters by using the slice syntax.

Specify the start index and the end index, separated by a colon, to
return a part of the string.

Example
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])

llo
Note: The first character has index 0.
Slice From the Start:
By leaving out the start index, the range will start at the first
character:

Example
Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])

Hello
Slice To the End:
By leaving out the end index, the range will go to the end:

Example
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])

llo, World!

Negative Indexing:
Use negative indexes to start the slice from the end of the string:
Example
Get the characters:
From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -2):
b = "Hello, World!"
print(b[-5:-2])

orl

Python - Modify Strings:


Python has a set of built-in methods that you can use on
strings.

Upper Case:
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())

HELLO, WORLD!

Lower Case:
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())

hello, world!

Remove Whitespace:
Whitespace is the space before and/or after the actual text, and
very often you want to remove this space.
The strip() method removes any whitespace from the beginning or
the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"

Hello, World!

Replace String:
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))

Jello, World!

Split String:
The split() method returns a list where the text between the
specified separator becomes the list items.

The split() method splits the string into substrings if it finds


instances of the separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

['Hello', ' World!']

String Concatenation:
To concatenate, or combine, two strings you can use the +
operator.

Merge variable a with variable b into variable c:


a = "Hello"
b = "World"
c=a+b
print(c)

To add a space between them, add a " ":


a = "Hello"
b = "World"
c=a+""+b
print(c)

 Boolean Values
In programming you often need to know if an expression is True or False.

You can evaluate any expression in Python, and get one of two
answers, True or False.

When you compare two values, the expression is evaluated and Python
returns the Boolean answer:

Example
print(10 > 9)
print(10 == 9)
print(10 < 9)

True
False
False

When you run a condition in an if statement, Python returns True or False:

Print a message based on whether the condition is True or False:

a = 200
b = 33

if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

b is not greater than a

Evaluate Values and Variables:

The bool() function allows you to evaluate any value, and give
you True or False in return,

Evaluate a string and a number:

print(bool("Hello"))
print(bool(15))

True
True

Evaluate two variables:

x = "Hello"
y = 15

print(bool(x))
print(bool(y))

True
True

Most Values are True:


Almost any value is evaluated to True if it has some sort of content.Any
string is True, except empty strings.Any number is True, except 0.Any list,
tuple, set, and dictionary are True, except empty ones.

The following will return True:

print(bool("abc"))
print(bool(123))
print(bool(["apple", "cherry", "banana"]))
True
True
True

Some Values are False:

In fact, there are not many values that evaluate to False, except empty
values, such as (), [], {}, "", the number 0, and the value None. And of course
the value False evaluates to False.

The following will return False:

bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})

Python also has many built-in functions that return a boolean value, like
the isinstance() function, which can be used to determine if an object is of a

Check if an object is an integer or not:

x = 200
print(isinstance(x, int))

 Python Sets
Sets are used to store multiple items in a single variable.

Set is one of 4 built-in data types in Python used to store collections of data,
the other 3 are List, Tuple, and Dictionary, all with different qualities and
usage.

A set is a collection which is unordered, unchangeable, unindexed and do not


allow duplicate values.

Note: Set items are unchangeable, but you can remove items and add new
items.
Sets are written with curly brackets.

Create a Set:

thisset = {"apple", "banana", "cherry"}


print(thisset)

output:

{"banana", "cherry","apple"}

Duplicates Not Allowed:

Sets cannot have two items with the same value.

Duplicate values will be ignored:

thisset = {"apple", "banana", "cherry", "apple"}


print(thisset)

output:

{"banana", "cherry","apple"}

Note: The values True and 1 are considered the same value in sets, and are
treated as duplicates:

True and 1 is considered the same value:

thisset = {"apple", "banana", "cherry", True, 1, 2}


print(thisset)
output:
{ True, 2, "apple", "banana", "cherry"}

Note: The values False and 0 are considered the same value in sets, and are
treated as duplicates:

False and 0 is considered the same value:

thisset = {"apple", "banana", "cherry", False, True, 0}

print(thisset)
output:
{ True, False, "apple", "banana", "cherry"}

Get the Length of a Set:

To determine how many items a set has, use the len() function.

Get the number of items in a set:

thisset = {"apple", "banana", "cherry"}

print(len(thisset)) #3

Set Items - Data Types

Set items can be of any data type:

String, int and boolean data types:

set1 = {"apple", "banana", "cherry"}


set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
print(set1)
print(set2)
print(set3)

A set can contain different data types:

A set with strings, integers and boolean values:

set1 = {"abc", 34, True, 40, "male"}


print(set1)
type()

From Python's perspective, sets are defined as objects with the data type
'set':

What is the data type of a set?

myset = {"apple", "banana", "cherry"}


print(type(myset))
output:
<class 'set'>

The set() Constructor:

It is also possible to use the set() constructor to make a set.

Using the set() constructor to make a set:

thisset = set(("apple", "banana", "cherry")) # note the double round-


brackets
print(thisset)
output:

{"banana", "cherry","apple"}

Access Items in SETS:

You cannot access items in a set by referring to an index or a key.

But you can loop through the set items using a for loop, or ask if a specified
value is present in a set, by using the in keyword.

Loop through the set, and print the values:

thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x)
output:

banana
cherry
apple

Check if "banana" is present in the set:


thisset = {"apple", "banana", "cherry"}

print("banana" in thisset) #True

Add Items in Sets:

Once a set is created, you cannot change its items, but you can add new
items.

To add one item to a set use the add() method.

Add an item to a set, using the add() method:

thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)

output:

{"apple", “orange”,"banana", "cherry"}

Remove Items from a Set:

Python provides several methods to remove items from a set. Here's a


clear breakdown with examples:

remove() – Removes a specified item

Raises an error if the item doesn't exist.

fruits = {"apple", "banana", "cherry"}


fruits.remove("banana")
print(fruits)

# Output: {'apple', 'cherry'}

 Input Function, Output Statements


Taking input in Python:

Python's input() function is used to take user input. By default, it returns


the user input in form of a string.

Example:
name = input("Enter your name: ")
print("Hello,", name, "! Welcome!")
Output
Enter your name: GeeksforGeeks
Hello, GeeksforGeeks ! Welcome!

Printing Output using print() in Python:

At its core, printing output in Python is straightforward, thanks to the


print() function. This function allows us to display text, variables and
expressions on the console. Let's begin with the basic usage of the print()
function:
In this example, "Hello, World!" is a string literal enclosed within double
quotes. When executed, this statement will output the text to the console.

Code:
print("Hello, World!")
Output
Hello, World!

Python Operators
In Python programming, Operators in general are used to
perform operations on values and variables. These are standard
symbols used for logical and arithmetic operations. In this
article, we will look into different types of Python operators.

 OPERATORS: These are the special symbols. Eg- + , * , /, etc.


 OPERAND: It is the value on which the operator is applied.

Types of Operators in Python

Arithmetic Operators in Python


Python Arithmetic operators are used to perform basic
mathematical operations like addition, subtraction,
multiplication and division.

Example of Arithmetic Operators in Python:


# Variables
a = 15
b = 4

# Addition
print("Addition:", a + b)

# Subtraction
print("Subtraction:", a - b)

# Multiplication
print("Multiplication:", a * b)

# Division
print("Division:", a / b)

# Floor Division
print("Floor Division:", a // b)

# Modulus
print("Modulus:", a % b)

# Exponentiation
print("Exponentiation:", a ** b)

Output
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
Floor Division: 3
Modulus: 3
Exponentiation: 50625

Comparison of Python Operators


In Python Comparison of Relational operators compares the values. It
either returns True or False according to the condition.
a = 13
b = 33

print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
Output
False
True
False
True
False
True
Logical Operators in Python:
Python Logical operators perform Logical AND, Logical OR and Logical
NOT operations. It is used to combine conditional statements.
The precedence of Logical Operators in Python is as follows:
1. Logical not
2. logical and
3. logical or
a = True
b = False
print(a and b)
print(a or b)
print(not a)

Output
False
True
False

Assignment Operators in Python


Python Assignment operators are used to assign values to the variables.
This operator is used to assign the value of the right side of the expression
to the left side operand.
Example of Assignment Operators in Python:
a = 10
b=a
print(b)
b += a
print(b)

Output
10
20
Identity Operators in Python
In Python, is and is not are the identity operators both are used to check
if two values are located on the same part of the memory. Two variables
that are equal do not imply that they are identical.
is True if the operands are identical
is not True if the operands are not identical

Example of Identity Operators in Python:


a = 10
b = 20
c=a

print(a is not b)
print(a is c)

Output
True
True

Precedence of Python Operators


This is used in an expression with more than one operator with different
precedence to determine which operation to perform first.
Example
10 + 20 * 30
10 + 20 * 30 is calculated as 10 + (20 * 30)
and not as (10 + 20) * 30

Python Code of the above Example


# Precedence of '+' & '*'
expr = 10 + 20 * 30

print(expr)
Output
610

Associativity of Python Operators:


If an expression contains two or more operators with the same
precedence then Operator Associativity is used to determine. It can either
be Left to Right or from Right to Left.
Example
In this code, '*' and '/' have the same precedence and their associativity
is Left to Right, so the expression "100 / 10 * 10" is treated as "(100 / 10)
* 10".
Code

# Left-right associativity
# 100 / 10 * 10 is calculated as
# (100 / 10) * 10 and not
# as 100 / (10 * 10)
print(100 / 10 * 10)

# Left-right associativity
# 5 - 2 + 3 is calculated as
# (5 - 2) + 3 and not
# as 5 - (2 + 3)
print(5 - 2 + 3)

# left-right associativity
print(5 - (2 + 3))

# right-left associativity
# 2 ** 3 ** 2 is calculated as
# 2 ** (3 ** 2) and not
# as (2 ** 3) ** 2
print(2 ** 3 ** 2)

Output
100
6
0
512

The if Statement

The if statement is the simplest form of decision-making in


Python.
It allows you to execute a block of code only if a specific condition
is true.
If the condition is false, the program skips the indented block and
continues with the rest of the code.

x = 10
if x > 5:
print("x is greater than 5")

The if...else Statement


Extends the if statement to provide an alternative action when
the condition is false.
Ensures one of two blocks runs: either the if block (when
condition is true) or the else block (when false).

Check if the temperature is hot or cold.

temperature = 32
if temperature > 30:
print("It's hot outside.")
else:
print("It's not hot.")

Check if a student passed or failed.


marks = int(input("Enter your marks: "))
if marks >= 40:
print("You passed!")
else:
print("You failed.")
Write a Python program to check whether a person is eligible to
vote or not.
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")

If, Else, and Else If statement


An if-statement always starts with an if.
An if-statement can contain zero or many else if, and zero or
one else.
When else is present, it has to come last, after all the else if.
The else statement ensures that one (and only one) of the code
blocks will execute.
Sometimes it is enough to just use a single if, like this:

age = 32
if age > 17:
print('You are an adult!')

But usually, we also want to handle the case when the condition is
not true, so we use an else statement for that.

age = 10
if age > 17:
print('You are an adult!')
else:
print('You are not an adult yet.')
The code block that belongs to the else will only be executed in
case the condition in the if is false.

We can also use else if to check more than one condition, so


that we get more than two outcomes.

age = 15
if age < 13:
print('You are a child')
elif age < 20:
print('You are a teenager')
else:
print('You are an adult')

You can only have one if statement, and only one else statement,
but you can have as many else if statements as you want.
Also, the if is always first, the else is always last, and the else
if statements are in between.

Task: Write a program that checks whether a number is:


Positive,Negative OR Zero
num = 0

if num > 0:
print("Positive")
elif num == 0:
print("Zero")
else:
print("Negative")

You might also like