Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

Python Cheet Sheet

Uploaded by

rashikumari561
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Python Cheet Sheet

Uploaded by

rashikumari561
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Package/Method Description Syntax and Code Example

Syntax:

statement1 and statement2


Copied!
Example:

marks = 90

1. attendance_percentage = 87
2.
Returns `True` if both statement1
AND and statement2 are `True`. 3. if marks >= 80 and
Otherwise, returns `False`. attendance_percentage >= 85:

4. print("qualify for honors")

5. else:
6. print("Not qualified for

honors")

7.

8. # Output = qualify for honors


Copied!

Syntax:

1. class ClassName: # Class


attributes and methods
Copied!
Example:
Defines a blueprint for creating
Class Definition objects and defining their
1. class Person:
attributes and behaviors.
2. def __init__(self, name,

age):

3. self.name = name

4. self.age = age
Copied!

Syntax:

1. def function_name(parameters): #
Function body
A `function` is a reusable block of
Copied!
Define Function code that performs a specific task Example:
or set of tasks when called.
1. def greet(name): print("Hello,",
name)
Copied!

Equal(==) Checks if two values are equal. Syntax:


1. variable1 == variable2
Copied!
Example 1:

1. 5 == 5
Copied!
returns True

Example 2:

1. age = 25 age == 30
Copied!
returns False

Syntax:

1. for variable in sequence: # Code


to repeat
Copied!
Example 1:

A `for` loop repeatedly executes a


1. for num in range(1, 10):
block of code for a specified
For Loop number of iterations or over a 2. print(num)
Copied!
sequence of elements (list, range, Example 2:
string, etc.).

1. fruits = ["apple", "banana",


"orange", "grape", "kiwi"]

2. for fruit in fruits:


3. print(fruit)
Copied!

Syntax:
A function call is the act of 1. function_name(arguments)
executing the code within the Copied!
Function Call Example:
function using the provided
arguments.
1. greet("Alice")
Copied!

Syntax:

1. variable1 >= variable2


Copied!

Greater Than or Equal Checks if the value of variable1 is Example 1:


To(>=) greater than or equal to variable2.
1. 5 >= 5 and 9 >= 5
Copied!
returns True
Example 2:

1. quantity = 105
2. minimum = 100
3. quantity >= minimum
Copied!
returns True

Syntax:

1. variable1 > variable2


Copied!
Example 1: 9 > 6

returns True

Checks if the value of variable1 is


Greater Than(>) Example 2:
greater than variable2.

1. age = 20
2. max_age = 25
3. age > max_age
Copied!
returns False

Syntax:

1. if condition: #code block for if


statement
Executes code block `if` the Copied!
If Statement Example:
condition is `True`.

1. if temperature > 30:


2. print("It's a hot day!")
Copied!

Syntax:

1. if condition1:
2. # Code if condition1 is True
Executes the first code block if
3.
condition1 is `True`, otherwise
If-Elif-Else checks condition2, and so on. If 4. elif condition2:
no condition is `True`, the else 5. # Code if condition2 is True
block is executed. 6.
7. else:
8. # Code if no condition is True
Copied!
Example:

1. score = 85 # Example score

2. if score >= 90:


3. print("You got an A!")

4. elif score >= 80:


5. print("You got a B.")

6. else:
7. print("You need to work

harder.")

8.

9. # Output = You got a B.


Copied!

Syntax:

1. if condition: # Code, if
condition is True

2. else: # Code, if condition is


False
Copied!
Executes the first code block if
Example:
If-Else Statement the condition is `True`, otherwise
the second block.
1. if age >= 18:
2. print("You're an adult.")

3. else:
4. print("You're not an adult

yet.")
Copied!

Syntax:

1. variable1 <= variable2

Copied!
Example 1:

Less Than or Equal Checks if the value of variable1 is


1. 5 <= 5 and 3 <= 5
To(<=) less than or equal to variable2. Copied!
returns True

Example 2:

1. size = 38
2. max_size = 40
3. size <= max_size
Copied!
returns True

Syntax:

1. variable1 < variable2


Copied!
Example 1:

1. 4 < 6
Copied!
returns True
Checks if the value of variable1 is
Less Than(<)
less than variable2. Example 2:

1. score = 60
2. passing_score = 65
3. score < passing_score
Copied!
returns True

Syntax:

1. for: # Code to repeat


2. if # boolean statement

3. break

4.

5. for: # Code to repeat


6. if # boolean statement

7. continue
Copied!
`break` exits the loop Example 1:
prematurely. `continue` skips the
Loop Controls
rest of the current iteration and 1. for num in range(1, 6):
moves to the next iteration.
2. if num == 3:

3. break

4. print(num)
Copied!
Example 2:

1. for num in range(1, 6):


2. if num == 3:

3. continue

4. print(num)
Copied!

Syntax:

1. !variable
Copied!
Example:
Returns `True` if variable is `False`,
NOT
and vice versa. 1. !isLocked
Copied!
returns True if the variable is False (i.e.,
unlocked).

Syntax:

1. variable1 != variable2
Copied!
Example:

1. a = 10
2. b = 20

Checks if two values are not 3. a != b


Not Equal(!=) Copied!
equal.
returns True

Example 2:

1. count=0
2. count != 0
Copied!
returns False

Syntax:

1. object_name =
Creates an instance of a class ClassName(arguments)
Object Creation (object) using the class Copied!

constructor. Example:

1. person1 = Person("Alice", 25)


Copied!

Syntax:

Returns `True` if either statement1 1. statement1 || statement2


Copied!
OR or statement2 (or both) are `True`.
Example:
Otherwise, returns `False`.

1. "Farewell Party Invitation"


1. Grade = 12 grade == 11 or grade
== 12
Copied!
returns True

Syntax:

1. range(stop)
2. range(start, stop)
3. range(start, stop, step)
Copied!
Example:
Generates a sequence of numbers
range()
within a specified range. 1. range(5) #generates a sequence of
integers from 0 to 4.

1. range(2, 10) #generates a


sequence of integers from 2 to 9.

2. range(1, 11, 2) #generates odd


integers from 1 to 9.
Copied!

Syntax:

1. return value
Copied!
`Return` is a keyword used to
Example:
Return Statement send a value back from a function
to its caller. def add(a, b): return a + b

1. result = add(3, 5)
Copied!

Syntax:

1. try: # Code that might raise an


exception except

2. ExceptionType: # Code to handle


Tries to execute the code in the
the exception
try block. If an exception of the Copied!
Try-Except Block
specified type occurs, the code in Example:
the except block is executed.
try:

1. num = int(input("Enter a

number: "))

2. except ValueError:
3. print("Invalid input. Please

enter a valid number.")


Copied!

Syntax:

1. try: # Code that might raise an


exception except

2. ExceptionType: # Code to handle


the exception

3. else: # Code to execute if no


exception occurs
Copied!
Code in the `else` block is Example:
Try-Except with Else
executed if no exception occurs in
Block
the try block. 1. try:
2. num = int(input("Enter a

number: "))

3. except ValueError:
4. print("Invalid input. Please

enter a valid number")

5. else:
6. print("You entered:", num)
Copied!

Syntax:

1. try: # Code that might raise an


exception except

2. ExceptionType: # Code to handle


the exception

3. finally: # Code that always


executes
Code in the `finally` block always Copied!
Try-Except with Finally
executes, regardless of whether Example:
Block
an exception occurred.
1. try:
2. file = open("data.txt", "r")

3. data = file.read()

4. except FileNotFoundError:
5. print("File not found.")

6. finally:
7. file.close()
Copied!

Syntax:

A `while` loop repeatedly 1. while condition: # Code to repeat


Copied!
executes a block of code as long
While Loop Example:
as a specified condition remains
`True`.
1. count = 0 while count < 5:
2. print(count) count += 1

You might also like