0% found this document useful (0 votes)
2 views6 pages

Python basics cheat sheet

This document is a Python Basics Cheat Sheet that covers fundamental concepts such as functions, data types, loops, and file handling. It includes code examples for various operations like string manipulation, list commands, and defining classes. The cheat sheet serves as a quick reference guide for beginners learning Python programming.

Uploaded by

rakshitpande2012
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)
2 views6 pages

Python basics cheat sheet

This document is a Python Basics Cheat Sheet that covers fundamental concepts such as functions, data types, loops, and file handling. It includes code examples for various operations like string manipulation, list commands, and defining classes. The cheat sheet serves as a quick reference guide for beginners learning Python programming.

Uploaded by

rakshitpande2012
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/ 6

Python Basics Cheat Sheet

Getting Started with Basics

Hello world: Functions: Lists:

- Prints a message to the screen. - Defines reusable blocks of code. - Stores an ordered collection of items.

Python
Python Python
def greet(name):
print("Hello, World!") fruits = ["apple", "banana", "cherry"]
return f"Hello, {name}!"

Arithmetic: Strings: Variables:

- Performs basic arithmetic operations. - Manages and manipulates text data. - Stores values that can be reused and manipulated.

Python Python Python


# Addition s = "Python" age = 25
result = 2 + 3 print(s.upper())

f-Strings:
If else:
Data types:
- Implements conditional logic. - Formats strings using expressions inside curly braces.
- Defines the type of values.

Python Python
Python if x > 0: name = "Alice"
num = 10 # Integer print("Positive") print(f"Hello, {name}")
text = "Python" # String else:
print("Non-positive")

Plus-equals:
File handling:
Loops:
- Adds a value to a variable and assigns the result to that variable.
- Opens, reads, writes, and closes files. - Repeats a block of code multiple times.
Python
Python Python count = 0
with open('file.txt', 'r') as file: for i in range(5): count += 1
content = file.read() print(i)
Python Built-in Data Types Python Modules

Strings: Set: Import modules:

- Text data enclosed in single or double quotes. - Unordered collection of unique elements. - Imports a module to use its functions and attributes.

Python Python Python


s = "Hello" s = {1, 2, 3} import math
print(math.sqrt(16))

Lists: Tuple:

- Ordered and mutable sequence of elements. - Ordered and immutable sequence of elements. Shorten module:

- Uses an alias for a module.


Python Python
lst = [1, 2, 3] t = (1, 2, 3)
Python
import numpy as np

Dictionary: Numbers:

- Key-value pairs enclosed in curly braces. - Numeric data types like int, float, and complex.

From a module import all:


Python Python
d = {"one": 1, "two": 2} num = 10 # Integer
- Imports all functions and attributes from a module.
float_num = 10.5 # Float

Python
Booleans:
Casting: from math import *

- Represents True or False values.


- Converts a variable from one type to another.

Python
is_active = True Python
Functions and attributes:
x = int(3.8) # 3

- Uses specific functions and attributes from a module.

Python
from math import pow, pi
print(pow(2, 3))
print(pi)
Python Strings

Concatenates: Input: Array-like:

- Combines two or more strings. - Takes user input as a string. - Access characters using indexes.

Python Python Python


full = "Hello" + " " + "World" user_input = input("Enter something: ") s = "Python"
print(s[0]) # 'P'

Slicing string: Join:


String length:
- Extracts part of a string. - Joins elements of an iterable into a single string.
- Gets the length of a string.

Python Python
substr = "Python"[2:5] # 'tho' join_str = ", ".join(["apple", "banana", "cherry"]) Python
length = len("Python")

Multiple copies: Endswith:


Check string:
- Repeats a string multiple times. - Checks if a string ends with a specific suffix.
- Checks if a substring exists within a string.

Python Python
repeat = "Hi! " * 3 # 'Hi! Hi! Hi! ' ends = "python.org".endswit Python
if "Py" in "Python":
print("Found!")

Formatting: Looping:

- Formats strings using {} placeholders. - Iterates through characters of a string.

Python Python
s = "Hello, {}. Welcome to {}.".format(name, place) for char in "Python":
print(char)
Python Lists Commands Python Loops

Generate: Count: Basic:

- Creates a list with specified elements. - Counts occurrences of an element in a list. - Repeats a block of code for a fixed number of times.

Python Python Python


fruits = ["apple", "banana", "cherry"] count = fruits.count("apple") for i in range(3):
print(i)

List slicing: Repeating:


Break:
- Extracts parts of a list. - Repeats elements in a list.
- Exits the loop prematurely.

Python Python
sublist = fruits[1:3] # ['banana', 'cherry'] repeat_list = [0] * 5 # [0, 0, 0, 0, 0] Python
for i in range(5):
if i == 3:
break
Omitting index: Sort & reverse:
print(i)

- Omits starting or ending index for slicing. - Sorts and reverses a list.

With zip():
Python Python
sublist_from_start = fruits[:2] # ['apple', 'banana'] fruits.sort() # ['apple', 'banana', 'cherry'] - Iterates over multiple iterables in parallel.
sublist_to_end = fruits[1:] # ['banana', 'cherry'] fruits.reverse() # ['cherry', 'banana', 'apple']

Python
names = ["Alice", "Bob"]
With a stride: Access:
scores = [85, 92]
for name, score in zip(names, scores):
- Extracts elements with step size. - Accesses elements by index.
print(name, score)

Python Python
stride_slicing = fruits[::2] # ['apple first_fruit = fruits[0] # 'apple' While:

- Continues until a condition is met.


Concatenating:
Python
- Combines two or more lists.
count = 0
while count < 5:
Python print(count)
count += 1
combined = fruits + ["kiwi", "mango"]
Python Loops (continued) Python Functions

Range: Basic: Returning multiples:

- Generates a sequence of numbers. - Defines a function with a specific task. - Returns multiple values from a function.

Python Python Python


for i in range(1, 10, 2): def greet(): def get_name_age():
print(i) print("Hello, World!") return "Alice", 25
name, age = get_name_age()

Continue: Keyword arguments:


Default value:
- Skips the current iteration and proceeds to the next. - Passes arguments by name.
- Uses default values for parameters.

Python Python
for i in range(5): def introduce(name, age): Python
if i == 3: print(f"Name: {name}, Age: {age}") def greet(name="Guest"):
continue introduce(age=30, name="Alice") print(f"Hello, {name}!")
print(i)

Anonymous functions: Positional arguments:


With index:
- Uses lambda for short, unnamed functions. - Passes arguments in the order of parameters.
- Uses range and len to loop with an index.

Python Python
Python square = lambda x: x ** 2 def add(a, b):
fruits = ["apple", "banana", "cherry"] print(square(5)) print(a + b)
for i in range(len(fruits)): add(3, 5)
print(fruits[i])

Return:

for/else: - Returns a value from a function.

- Executes else block if no break occurs.


Python
def add(a, b):
Python return a + b
for i in range(5):
if i == 6:
break
else:
print("Completed")
Python Classes

User-defined exceptions: Defining: Overriding:

- Creates custom exception classes. - Defines a blueprint for objects. - Redefines methods in a subclass.

Python Python Python


class CustomError(Exception): class Dog: class Animal:
pass def __init__(self, name): def make_sound(self):
self.name = name print("Generic sound")
class Dog(Animal):
def make_sound(self):
repr() method:
print("Bark")
Class variables:
- Provides a string representation of an object.
- Variables shared among all instances.
Inheritance:
Python
class Dog: Python - Derives a new class from an existing class.
def __repr__(self): class Dog:
return f"Dog({self.name})" species = "Canine"
Python
class Animal:
def __init__(self, name):
Constructors: Polymorphism:
self.name = name
class Dog(Animal):
- Special methods to initialize new objects. - Uses a single interface for different types.
def __init__(self, name, breed):
super().__init__(name)
Python Python self.breed = breed

class Dog: class Cat:


def __init__(self, name): def sound(self):
self.name = name return "Meow"
class Dog:
def sound(self):
return "Bark"
Method:
for pet in (Cat(), Dog()):
print(pet.sound())
- Defines functions within a class.

Python
class Dog:
def bark(self):
print("Woof!")

You might also like