0% found this document useful (0 votes)
12 views4 pages

Course Ra

This cheat sheet provides a concise overview of fundamental Python programming concepts, including syntax and examples for logical operations, class definitions, function definitions, control flow statements, and exception handling. Key topics covered include AND, OR, loops, conditionals, and error handling mechanisms. Each concept is presented with its syntax and practical code examples to illustrate usage.

Uploaded by

GIRITHAR
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)
12 views4 pages

Course Ra

This cheat sheet provides a concise overview of fundamental Python programming concepts, including syntax and examples for logical operations, class definitions, function definitions, control flow statements, and exception handling. Key topics covered include AND, OR, loops, conditionals, and error handling mechanisms. Each concept is presented with its syntax and practical code examples to illustrate usage.

Uploaded by

GIRITHAR
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/ 4

Python Programming Fundamentals Cheat Sheet

Package/Method Description Syntax and Code Example

Syntax:
statement1 and statement2

Example:
Returns `True` if both statement1 and statement2 are `True`. Otherwise, returns
AND marks = 90
`False`. attendance_percentage = 87
if marks >= 80 and attendance_percentage >= 85:
print("qualify for honors")
else:
print("Not qualified for honors")
# Output = qualify for honors

Syntax:
class ClassName: # Class attributes and methods

Defines a blueprint for creating objects and defining their attributes and Example:
Class Definition
behaviors.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

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

Syntax:
variable1 == variable2

Example 1:
5 == 5
Equal(==) Checks if two values are equal.
returns True

Example 2:
age = 25 age == 30

returns False

Syntax:
for variable in sequence: # Code to repeat

Example 1:

A `for` loop repeatedly executes a block of code for a specified number of for num in range(1, 10):
For Loop print(num)
iterations or over a sequence of elements (list, range, string, etc.).
Example 2:
fruits = ["apple", "banana", "orange", "grape", "kiwi"]
for fruit in fruits:
print(fruit)

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

Syntax:
variable1 >= variable2

Example 1:
5 >= 5 and 9 >= 5

Greater Than or
Checks if the value of variable1 is greater than or equal to variable2. returns True
Equal To(>=)
Example 2:
quantity = 105
minimum = 100
quantity >= minimum
returns True

Syntax:
variable1 > variable2

Example 1: 9 > 6

returns True
Greater Than(>) Checks if the value of variable1 is greater than variable2.
Example 2:
age = 20
max_age = 25
age > max_age

returns False

Syntax:
if condition: #code block for if statement

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


if temperature > 30:
print("It's a hot day!")

Syntax:
if condition1:
# Code if condition1 is True
elif condition2:
# Code if condition2 is True
else:
# Code if no condition is True

Executes the first code block if condition1 is `True`, otherwise checks Example:
If-Elif-Else
condition2, and so on. If no condition is `True`, the else block is executed.
score = 85 # Example score
if score >= 90:
print("You got an A!")
elif score >= 80:
print("You got a B.")
else:
print("You need to work harder.")
# Output = You got a B.

Syntax:
if condition: # Code, if condition is True
else: # Code, if condition is False

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

Syntax:
variable1 <= variable2

Example 1:
5 <= 5 and 3 <= 5
Less Than or Equal
Checks if the value of variable1 is less than or equal to variable2. returns True
To(<=)
Example 2:
size = 38
max_size = 40
size <= max_size

returns True

Syntax:
variable1 < variable2

Example 1:
4 < 6

Less Than(<) Checks if the value of variable1 is less than variable2. returns True

Example 2:
score = 60
passing_score = 65
score < passing_score

returns True

Syntax:
for: # Code to repeat
if # boolean statement
break
for: # Code to repeat
if # boolean statement
continue

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

Example 2:
for num in range(1, 6):
if num == 3:
continue
print(num)

Syntax:
!variable

NOT Returns `True` if variable is `False`, and vice versa. Example:


!isLocked

returns True if the variable is False (i.e., unlocked).

Syntax:
variable1 != variable2

Example:
a = 10
b = 20
a != b
Not Equal(!=) Checks if two values are not equal.
returns True

Example 2:
count=0
count != 0

returns False

Syntax:
object_name = ClassName(arguments)
Object Creation Creates an instance of a class (object) using the class constructor.
Example:
person1 = Person("Alice", 25)

Syntax:
statement1 || statement2

Returns `True` if either statement1 or statement2 (or both) are `True`. Otherwise, Example:
OR
returns `False`.
"Farewell Party Invitation"
Grade = 12 grade == 11 or grade == 12

returns True

Syntax:
range(stop)
range(start, stop)
range(start, stop, step)
range() Generates a sequence of numbers within a specified range.
Example:
range(5) #generates a sequence of integers from 0 to 4.
range(2, 10) #generates a sequence of integers from 2 to 9.
range(1, 11, 2) #generates odd integers from 1 to 9.

Syntax:
return value

Return Statement `Return` is a keyword used to send a value back from a function to its caller. Example:
def add(a, b): return a + b
result = add(3, 5)

Syntax:
try: # Code that might raise an exception except
ExceptionType: # Code to handle the exception

Tries to execute the code in the try block. If an exception of the specified type
Try-Except Block occurs, the code in the except block is executed. Example:
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input. Please enter a valid number.")

Syntax:
try: # Code that might raise an exception except
ExceptionType: # Code to handle the exception
else: # Code to execute if no exception occurs

Try-Except with Example:


Code in the `else` block is executed if no exception occurs in the try block.
Else Block
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input. Please enter a valid number")
else:
print("You entered:", num)

Syntax:
try: # Code that might raise an exception except
ExceptionType: # Code to handle the exception
finally: # Code that always executes

Example:
Try-Except with Code in the `finally` block always executes, regardless of whether an exception
Finally Block occurred. try:
file = open("data.txt", "r")
data = file.read()
except FileNotFoundError:
print("File not found.")
finally:
file.close()

Syntax:
while condition: # Code to repeat
A `while` loop repeatedly executes a block of code as long as a specified
While Loop Example:
condition remains `True`.
count = 0 while count < 5:
print(count) count += 1

© IBM Corporation. All rights reserved.

You might also like