Py 11

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 19

PY-thon Cheatsheet

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.

Tokens are like the Lego bricks themselves:

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

print(10, 20, 40) #10 20 40


print(10, 20, 40, sep = “ , ”) #10,20, 40 <-- see how it separates using ,

List
A List in Python represents a list of comma-separated values of any data type between square
brackets.

var_name = [element1, element2, and so on]

List Methods index method

Returns the index of the first element with the specified value

list.index(element)

append method

Adds an element at the end of the list

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

Adds an element at the specified position

list.insert(position, element)

pop method

Removes the element at the specified position and returns it

list.pop(position)

remove method

The remove( ) method removes the first occurrence of a given item from the list
list.remove(element)

clear method

Removes all the elements from the list

list.clear()

count method

Returns the number of elements with the specified value


list.count(value)

reverse method

Reverse the order of the list

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

variable_name = (element1, element2, ...)

Tuple Methods count method

It returns the number of times a specified value occurs in a tuple

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-name> = {<key>: value, <key>: value ...}

Adding Element to a dictionary

By this method, one can add new elements to the dictionary

<dictionary>[<key>] = <value>

Updating Element in a dictionary

If the specified key already exists, then its value will get updated

<dictionary>[<key>] = <value>

Deleting Element from a dictionary

del let to delete specified key: value pair from the dictionary

del <dictionary>[<key>]

Dictionary Functions & Methods len() method

It returns the length of the dictionary, i.e., the count of elements (key: value pairs) in the
dictionary

len(dictionary)

clear() method

Removes all the elements from the dictionary

dictionary.clear()
get() method

Returns the value of the specified key

dictionary.get(keyname)

items() method

Returns a list containing a tuple for each key-value pair

dictionary.items()

keys() method

Returns a list containing the dictionary's keys

dictionary.keys()
values() method

Returns a list of all the values in the dictionary

dictionary.values()

update() method

Updates the dictionary with the specified key-value pairs

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

It adds a single quotation mark

\'

Tab

It gives a tab space

\t
Backspace

It adds a backspace

\b

Octal value

It represents the value of an octal number

\ooo

Hex value

It represents the value of a hex number

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

variable_name = "String Data"

Slicing
Slicing refers to obtaining a sub-string from the given string.

var_name[n : m]

String Methods isalnum() method

Returns True if all characters in the string are alphanumeric


string_variable.isalnum()

isalpha() method

Returns True if all characters in the string are alphabet


string_variable.isalpha()

isdecimal() method

Returns True if all characters in the string are decimals


string_variable.isdecimal()

isdigit() method

Returns True if all characters in the string are digits


string_variable.isdigit()

islower() method

Returns True if all characters in the string are lower case


string_variable.islower()

isspace() method

Returns True if all characters in the string are whitespaces


string_variable.isspace()
isupper() method

Returns True if all characters in the string are upper case


string_variable.isupper()

lower() method

Converts a string into lower case


string_variable.lower()

upper() method

Converts a string into upper case


string_variable.upper()

strip() method

It removes leading and trailing spaces in the string


string_variable.strip()

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

Nested if-else Statement


if (condition 1):
Statement or any expressions
If (condition 1a):
Statement or expressions
else:
Staements or expressions
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.

for <variable> in <sequence>:


statements_to_repeat

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

def my_function(parameters or Arguments):


# Statements

My_function(arguments) --> calling the Fucntion.

Just like the Print() function or any other function.

Exception Handling
An exception is an unusual condition that results in an interruption in the flow of the program.

try and except

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 = “ “ )

B) Reverse a list and string.

# reverse a list using function.


x = [10, 20, 90, 75]
x.sort() -----> This will sort in big to small.
x.reverse() ------> This will reverse the list.
print(x)

# reverse a string and list using slicing


y = “apex”
Print(y[::-1])
y1 = [90, “apex”, 27 ]
Print(y1[::-1])

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"

# Other casting functions just for knowing.


ord("A") # 65 (ASCII code of 'A')
hex(10) # "0xa" (hexadecimal representation)
oct(8) # "0o10" (octal representation)
# Converting to lists, tuples, and sets , when I give directly inside the
function.
my_list = list("hello") # ["h", "e", "l", "l", "o"]
my_tuple = tuple([1, 2, 3]) # (1, 2, 3)
my_set = set([4, 4, 5, 6]) # {4, 5, 6} (removes duplicates)

# Using type() to check data types


print(type(x)) # Output: <class 'int'>
print(type(b)) # Output: <class 'float'>
print(type(pi_str)) # Output: <class 'str'>

D) Creating a Dynamic List, Tuple, dictionary

x = list() #creats an empty list


y = dict() #creats an empty dictionary
z = tuple() #creates an empty typle
Apex = set() # creates an empty set
x.append(10)
print(x)

E) Taking Input From the User


The input function is used to take input as string or character from the user as
follows:

var1 = input("Enter your name: ")


print("My name is: ", var1)

To take input in form of other datatype we need to typecast (convert a datatype into
other Datatype) them as follows:-

To take input as an integer:-

var1=int(input("enter the integer value"))


print(var1)

To take input as an float:-

var1=float(input("enter the float value"))


print(var1)
IF statements - (Control statements)
-->
number = 15
if number > 10:
print("The number is greater than 10")

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

Eg. Display all even numbers between 1 - 100

for agent in range(0,101,2):


print(agent)
For loops ---

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.

room = ['apex', 'nokk', 'rex']


for i in room:
print(i)

This ‘I’ will be the variable and it store the elements as values.

--> find the value or element

c= ["apex", "nova", "cell"]


find = "cell"
for agent in c:
if agent == find:
print(agent)

Or

c= ["apex", "nova", "cell"]


find = "cell"
if find in c:
print(find)

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

-->

# This is an infinite loop, it will run forever!


# Please do not run this code without modification.
while True:
print("This will never stop!")

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

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))
sum = num1 + num2
print(f"the sum of {num1} and {num2} is {sum}")

2 - odd or even

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


if number % 2 == 0:
print(number, "is even.")
else:
print(number, "is odd.")

3 - leap year or not

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


if year % 4 == 0 # u can use tis --- >(year % 100 != 0 or year % 400 == 0):
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")

4- Area and peri of circle

side = float(input("Enter the side length of the square: "))


area = side * side
perimeter = 4 * side
print(perimeter)

5 - Rock, paper and scrissor

import random

choices = ["rock", "paper", "scissors"]


computer_choice = random.choice(choices)
user_choice = input("Choose rock, paper, or scissors: ").lower()

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

temperature = float(input("Enter temperature in Celsius: "))


fahrenheit = (temperature * 9/5) + 32
print(temperature, "Celsius is equal to", fahrenheit, "Fahrenheit")

7 - Calculator

operation = input("Enter an operation (+, -, *, / )”)


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

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

if "Error" not in result:


print(num1, operation, num2, "=", result)
8 - Trigonometry:

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)

9 - Exponents and Logarithms:

import math

base = float(input("Enter base: "))


exponent = float(input("Enter exponent: "))

power = math.pow(base, exponent)


logarithm = math.log(base, exponent) # Base-b logarithm

print("Power:", power)
print("Logarithm:", logarithm)

10 +ve or -ve Number

num = int(input("Enter a number: "))


if num > 0:
print("The number is positive.")
elif num == 0:
print("The number is zero.")
else:
print("The number is negative.")

Def method - Examples :


-->
def greet_person(name):
print("Hello,", name + "!")
greet_person("apex") # Pass "apex" as the argument

Output - Hello apex

-->

def add_numbers(num1, num2):


sum = num1 + num2
print("The sum is:", sum)

add_numbers(5, 3) # Pass 5 and 3 as arguments

-->
def calculate_area(length, width):
area = length * width
return area # Return the calculated area

result = calculate_area(4, 5)
print("The area is:", result)

 Use def to define a function.


 Close the function's code in a block with indentation.
 Use () to call the function and pass any necessary arguments.
 Use return to send a value back from the function.

You might also like