Py 11
Py 11
Py 11
Basics -
Imagine you're building a robot friend using Lego bricks! Python code is like a set of instructions
for building cool things with words and numbers. To understand these instructions, we need to
know about two types of special building blocks: tokens and punctuators.
Keywords: These are special words with unique meanings, like "for" to repeat actions or "if" to
make choices. Think of them as the big, colorful bricks with pictures that guide the main steps.
Identifiers: These are names you give to things like your robot friend or its special tools. They're
like regular bricks you label "arm" or "sensor."
Literals: These are the numbers, words, and true/false values your robot understands. Imagine
they're the small bricks in different colors and shapes – numbers are red squares, words are blue
rectangles, and true/false are green and yellow circles.
Operators: These are symbols that tell your robot how to do things with the bricks. Think of them
as special tools: "+" to connect bricks, "-" to move them apart, "*" to repeat patterns. (basic maths)
Punctuators are like the little helper pieces that connect the bricks:
-Parentheses: These are like round brackets "()" that hold groups of bricks together, like a
robot's hand or leg.
-Brackets: These are like square brackets "[]" that tell you the order of bricks in a line, like
fingers or toes.
-Curly braces: These are like big squiggly braces "{}" that group many bricks together, like
the whole robot body.
-Quotes: These are like single or double quotes '' or "" that hold onto words and special
messages for your robot.
-Semicolon: This is like a dot ";" that tells your robot to finish one instruction before starting
the next.
-Comma: This is like a comma "," that separates things in a list, like different tools your
robot has.
Print Function
name = "apex"
print(name) #apex
print('name') #name
print('apex') #apex
print(10 + 20) #30
List
A List in Python represents a list of comma-separated values of any data type between square
brackets.
Returns the index of the first element with the specified value
list.index(element)
append method
list.append(element)
extend method
Add the elements of a list (or any iterable) to the end of the current list
list.extend(iterable)
insert method
list.insert(position, element)
pop method
list.pop(position)
remove method
The remove( ) method removes the first occurrence of a given item from the list
list.remove(element)
clear method
list.clear()
count method
reverse method
list.reverse()
sort method
list.sort(reverse=True|False)
Tuples
Tuples are represented as a list of comma-separated values of any data type within parentheses.
Tuple Creation
tuple.count(value)
index method
It searches the tuple for a specified value and returns the position.
tuple.index(value)
Dictionaries
The dictionary is an unordered set of comma-separated key: value pairs, within {}, with the
requirement that within a dictionary, no two keys can be the same.
Dictionary
<dictionary>[<key>] = <value>
If the specified key already exists, then its value will get updated
<dictionary>[<key>] = <value>
del let to delete specified key: value pair from the dictionary
del <dictionary>[<key>]
It returns the length of the dictionary, i.e., the count of elements (key: value pairs) in the
dictionary
len(dictionary)
clear() method
dictionary.clear()
get() method
dictionary.get(keyname)
items() method
dictionary.items()
keys() method
dictionary.keys()
values() method
dictionary.values()
update() method
dictionary.update(iterable)
Escape Sequence
An escape sequence is a sequence of characters; it doesn't represent itself when used inside
string literal or character.
Newline
Newline Character
\n
Backslash
It adds a backslash
\\
Single Quote
\'
Tab
\t
Backspace
It adds a backspace
\b
Octal value
\ooo
Hex value
\xhh
Carriage Return
Carriage return or \r is a unique feature of Python. \r will just work as you have shifted your
cursor to the beginning of the string or line.
\r
Strings
Python string is a sequence of characters, and each character can be individually accessed. Using
its index.
String
You can create Strings by enclosing text in both forms of quotes - single quotes or double-
quotes.
Slicing
Slicing refers to obtaining a sub-string from the given string.
var_name[n : m]
isalpha() method
isdecimal() method
isdigit() method
islower() method
isspace() method
lower() method
upper() method
strip() method
Conditional Statements
The if statements are the conditional statements in Python, and these implement selection
constructs (decision constructs).
if Statement
if (condition):
Statement or any expressions
if-else Statement
if (condition):
Statement or any expressions
else:
Statement or any expressions
if-elif Statement
if (condition 1):
Statement or any expressions
elif (condition 2):
Statement or any expressions
…... (as many elif)
else:
Statement or any expressions
Iterative Statements
An iteration statement, or loop, repeatedly executes a statement, known as the loop body, until
the controlling expression is false (0).
For Loop
The for loop of Python is designed to process the items of any sequence, such as a list or a
string, one by one.
While Loop
A while loop is a conditional loop that will repeat the instructions within itself as long as a
conditional remains true.
while <logical-expression> :
loop-body
If you want to loop until a condition ( age start - 5, looping until it reaches 10)
while <logical-expression> :
loop-body
Increment expression
Break Statement
The break statement enables a program to skip over a part of the code. A break statement
terminates the very loop it lies within.
Continue Statement
The continue statement skips the rest of the loop statements and causes the next iteration to
occur.
Pass satement
This will ignore the current loop and move on to the next one.
Functions
A function is a block of code that performs a specific task. You can pass parameters into a
function. It helps us to make our code more organized and manageable.
Function Definition
Exception Handling
An exception is an unusual condition that results in an interruption in the flow of the program.
A basic try-catch block in python. When the try block throws an error, the control goes to the
except block.
try:
[Statement body
block]
except Exception as e:
Print(e )
a) Print 1 - 10
r = range(1, 11)
For agent in r:
Print(agent, end = “ “ )
C) Type casting
# Converting to integers
x = int(10.5) # 10 (truncates decimal part)
y = int("42") # 42 (from string)
# Converting to floats
a = float(25) # 25.0
b = float("3.14159") # 3.14159 (from string)
# Converting to strings
name = str(45) # "45"
pi_str = str(3.14) # "3.14"
To take input in form of other datatype we need to typecast (convert a datatype into
other Datatype) them as follows:-
-->
temperature = 25
if temperature >= 30:
print("It's a hot day!")
else:
print("It's not too hot.")
-->
grade = int(input(“enter your mark - ”))
if grade >= 90:
print("Excellent!")
elif grade >= 80:
print("Very good!")
elif grade >= 70:
print("Good job!")
else:
print("You need to study more.")
-->
age = 25
has_license = True # see you can use boolean val.
if age >= 18:
if has_license:
print("You can drive a car!")
else:
print("You're old enough, but you need a license.")
else:
print("You're too young to drive.")
F) Range Function
range function returns a sequence of numbers, eg, numbers starting from 0 to n-1
for range(0, n)
range(int_start_value,int_stop_value,int_step_value)
Key concepts:
Indentation: Similarly to if statements, for loops use indentation to define the loop's
body.
Iterables: Loops can iterate over various iterables like lists, strings, ranges, and
dictionaries.
Break and continue: You can use break to exit the loop prematurely and continue to
skip to the next iteration.
1. Basically, if you want to loop into the elements in the list or tuple or dict. You can
for loop.
Eg.
This ‘I’ will be the variable and it store the elements as values.
Or
-->
for i in range(5):
print(i)
-->
numbers = [1, 5, 8, 3, 7]
for number in numbers:
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")
-->
count = 0
while count < 5:
print(count)
count += 1
->
guess = 0
secret_number = 7
while guess != secret_number:
guess = int(input("Guess the secret number: "))
if guess == secret_number:
print("You guessed it!")
else:
if guess > secret_number:
print("Your guess is too high.")
else:
print("Your guess is too low.")
-->
-->
password = ""
while password != "secret":
password = input("Enter your password: ")
if password == "secret":
print("Welcome!")
else:
print("Incorrect password. Try again.")
-->
Loops simple --
# For loop
for i in range(5):
print(i + 1)
# While loop
count = 0
while count < 3:
print("Count:", count)
count += 1
1 - basic addition
2 - odd or even
import random
if user_choice == computer_choice:
print("Tie!")
elif user_choice == "rock" and computer_choice == "scissors":
print("You win!")
elif user_choice == "paper" and computer_choice == "rock":
print("You win!")
elif user_choice == "scissors" and computer_choice == "paper":
print("You win!")
else:
print("Gaali !")
6 - Celsius-Fahrenheit Converter
7 - Calculator
if operation == "+":
result = num1 + num2
elif operation == "-":
result = num1 - num2
elif operation == "*":
result = num1 * num2
elif operation == "/":
if num2 != 0:
result = num1 / num2
else:
print("Error: Division by zero")
else:
print("Invalid operation")
import math
angle_degrees = float(input("Enter angle in degrees: "))
angle_radians = math.radians(angle_degrees) # Convert degrees to radians
sine = math.sin(angle_radians)
cosine = math.cos(angle_radians)
tangent = math.tan(angle_radians)
print("Sine:", sine)
print("Cosine:", cosine)
print("Tangent:", tangent)
import math
print("Power:", power)
print("Logarithm:", logarithm)
-->
-->
def calculate_area(length, width):
area = length * width
return area # Return the calculated area
result = calculate_area(4, 5)
print("The area is:", result)