0% found this document useful (0 votes)
3 views16 pages

Pythoncheatsheet

a good handwritten revision cheat sheet for python programming language

Uploaded by

jtribiani85
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)
3 views16 pages

Pythoncheatsheet

a good handwritten revision cheat sheet for python programming language

Uploaded by

jtribiani85
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/ 16

Variables

We use variables to temporarily store data in computer’s memory.

Comments
We use comments to add notes to our code. Good comments explain the hows and whys, not what
the code does.

Receiving Input
We can receive input from the user by calling the input() function.

birth_year = int(input(‘Birth year: ‘))

The input() function always returns data as a string. So, we’re converting the result into an integer by
calling the built-in int() function.

Strings
We can define strings using single (‘ ‘) or double (“ “) quotes.

To define a multi-line string, we surround our string with tripe quotes (“””)

We can get individual characters in a string using square brackets [].

course = ‘Python for Beginners’

course[0] # returns the first character

course[1] # returns the second character

course[-1] # returns the first character from the end

course[-2] # returns the second character from the end

course[3:-2] # return a sequence from 3 to second last character

We can slice a string using a similar notation: course[1:5] The above expression returns all the
characters starting from the index position of 1 to 5 (but excluding 5). The result will be ytho

If we leave out the start index, 0 will be assumed. If we leave out the end index, the length of the
string will be assumed.

To check if a string contains a character (or a sequence of characters), we use the in operator:

for ex :- contains = ‘Python’ in course

Range Function
range function returns a sequence of numbers, eg, numbers starting from 0 to n-1 for range(0,
n)

String methods(functions)
• isalnum() method
Returns True if all the characters in the string are alphanumeric, else False

• isalpha() method
Returns True if all the characters in the string are alphabets

• isdigit() method
Returns True if all the characters in the string are digits

• islower() method
Returns True if all characters in the string are lower case

• isupper() method
Returns True if all characters in the string are upper case

message.upper() # to convert to uppercase

message.lower() # to convert to lowercase

message.title() # to capitalize the first letter of every word

message.find(‘p’) # returns the index of the first occurrence of p (or -1 if not found)

message.replace(‘p’, ‘q’)

Arithmetic Operations

/ # returns a float

// # returns an int

% # returns the remainder of division

** # exponentiation - x ** y = x to the power of y

Operator precedence:

1. parenthesis

2. exponentiation

3. multiplication / division

4. addition / subtraction

Logical operators:

if has_high_income and has_good_credit:


...

if has_high_income or has_good_credit:

...

is_day = True

is_night = not is_day

Comparison operators

a>b

a >= b (greater than or equal to)

a<b

a <= b

a == b (equals)

a != b (not equals)

While loops
i=1

while i < 5:

print(i)

i += 1

For loops
for i in range(1, 5):

print(i)

• range(5): generates 0, 1, 2, 3, 4

• range(1, 5): generates 1, 2, 3, 4

• range(1, 5, 2): generates 1, 3

List
A List in Python represents a list of comma—separated values of any data type between

square brackets.
Empty List
My_list = [] #This method allows you to create an empty list

numbers = [1, 2, 3, 4, 5]

numbers[0] # returns the first item

numbers[1] # returns the second item

numbers[-1] # returns the first item from the end

numbers[-2] # returns the second item from the end

numbers.append(6) # adds 6 to the end

numbers.index(6) # Returns the index of the first element with the specified value

numbers.insert(0, 6) # adds 6 at index position of 0

numbers.remove(6) # removes 6 &removes the first occurrence of a given item from the list

numbers.pop() # removes the last item

numbers.clear() # removes all the items

numbers.index(8) # returns the index of first occurrence of 8

numbers.sort() # sorts the list

numbers.sort(reverse=True |False) # sorts the list in ascending or descending order

numbers.reverse() # reverses the list

numbers.copy() # returns a copy of the list

numbers.extend(iterable) #Add the elements of a given list (or any iterable} to the end of the
current list

numbers.count(1) #returns the count of the element

Tuples
Tuples are represented as comma—separated values of any data type within parentheses.

They are like read-only lists. We use them to store a list of items. But once we define a tuple, we
cannot add or remove items or change the existing items.

Tuples are ordered,indexing,immutable and most secured collection of elements.

coordinates = (1, 2, 3) .

We can unpack a list or a tuple into separate variables:


x, y, z = coordinates

Sets
A set is a collection of multiple values which is both unordered and unindexed. It is written in
curly brackets.

Set is unordered,immutabIe,non—indexed type of collection.Duplicate elements are not allowed in sets.

add() method

set.add(element) #Adds on element to a set

union() method
set.union(set,set2) #Returns the union of two or more sets

Dictionaries
Dictionary is ordered and mutable collection of elements.Dictionary allows duplicate values but
not duplicate keys.

We use dictionaries to store key/value pairs.

customer = {

“name”: “John Smith”,

“age”: 30,

“is_verified”: True

We can use strings or numbers to define keys. They should be unique. We can use any types for the
values.

customer[“name”] # returns “John Smith”

customer[“type”] # throws an error

customer.get(“type”, “silver”) # returns “silver”

customer[“name”] = “new name”

In Python, a dictionary is a collection of key-value pairs. Each key is unique, and it is used to access its
corresponding value. Dictionaries are defined using curly braces {} and the key-value pairs are
separated by a colon :

Syntax:

dict_name = {

key1: value1,
key2: value2,

key3: value3

Example:

student = {

"name": "Puneet",

"age": 21,

"courses": ["Math", "Science"]

Accessing Values:

Use the key inside square brackets or the .get() method.

print(student["name"]) # Output: Puneet

print(student.get("age")) # Output: 21

Adding or Updating Items:

student["age"] = 22 # Update value

student["gender"] = "Male" # Add new key-value pair

print(student)

Removing Items:

• pop(key): Removes the item with the specified key and returns its value.

• del: Deletes the item with the specified key.

• clear(): Empties the entire dictionary.

student.pop("age") # Removes age key

del student["courses"] # Deletes courses key

student.clear() # Empties the dictionary

Looping Through a Dictionary:

# Loop through keys

for key in student:

print(key)

# Loop through values

for value in student.values():


print(value)

# Loop through key-value pairs

for key, value in student.items():

print(key, value)

Dictionary Methods:

• keys(): Returns a list of keys.

• values(): Returns a list of values.

• items(): Returns a list of key-value pairs.

Example:

print(student.keys()) # Output: dict_keys(['name', 'gender'])

print(student.values()) # Output: dict_values(['Puneet', 'Male'])

print(student.items()) # Output: dict_items([('name', 'Puneet'), ('gender', 'Male')])

Why Use Dictionaries?

• Fast lookups (compared to lists).

• Useful for storing data with labeled keys, like a record or an object.

Would you like more examples or any other details about dictionaries?

Functions

We use functions to break up our code into small chunks. These chunks are easier to read,
understand and maintain. If there are bugs, it’s easier to find bugs in a small chunk than the entire
program. We can also re-use these chunks.

def greet_user(name):

print(f”Hi {name}”)

greet_user(“John”)

Parameters are placeholders for the data we can pass to functions. Arguments are the actual values
we pass. We have two types of arguments: • Positional arguments: their position (order) matters •
Keyword arguments: position doesn’t matter - we prefix them with the parameter name

# Two positional arguments

greet_user(“John”, “Smith”)

# Keyword arguments
calculate_total(order=50, shipping=5, tax=0.1)

Our functions can return values. If we don’t use the return statement, by default None is returned.
None is an object that represents the absence of a value.

def square(number):

return number * number

result = square(2)

print(result) # prints 4

Python Standard Library


Python comes with a huge library of modules for performing common tasks such as sending emails,
working with date/time, generating random values, etc.

Random Module

import random

random.random() # returns a float between 0 to 1

random.randint(1, 6) # returns an int between 1 to 6

members = [‘John’, ‘Bob’, ‘Mary’]

leader = random.choice(members) # randomly picks an item

Modules
A module is a file with some Python code. We use modules to break up our program into multiple
files. This way, our code will be better organized. We won’t have one gigantic file with a million lines
of code in it! There are 2 ways to import modules: we can import the entire module, or specific
objects in a module.

Ye part alag se:

Print(i,end="")
Questions
1. Check Even or Odd
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")
2. Check Palindrome String(give me 2 methods)
string = input("Enter a string: ")
if string == string[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
3. Swap Two Numbers
a, b = b, a
print("After swapping: a =", a, "b =", b)
4. Sum of Elements in a List(using sum function and without using it)
nums = [1, 2, 3, 4, 5]
total = sum(nums)
print("Sum:", total)

#Second method
nums = [1, 2, 3, 4, 5]
total = 0
for num in nums:
total += num
print("Sum:", total)
5. Find the Sum of Digits of a Number
num = int(input("Enter a number: "))
sum_digits = 0
while num > 0:
sum_digits += num % 10
num = num // 10
print("Sum of digits:", sum_digits)
6. Reverse a String
string = input("Enter a string: ")
reversed_string = string[::-1]
print("Reversed string:", reversed_string)
7. Check Prime Number
num = int(input("Enter a number: "))
if num > 1:
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
print("Not Prime")
break
else:
print("Prime")
else:
print("Not Prime")
8. Check Prime Number(in a range)
start = int(input("Enter start of range: "))
end = int(input("Enter end of range: "))

for num in range(start, end + 1):


if num > 1:
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
break
else:
print(num, "is Prime")
9. Factorial of a Number
def fact(t):
if t==1:
return 1
return fact(t-1)*t
n=int(input())
print(fact(n))
Second method
n=int(input())
fact=1
for i in range(n,1,-1):
fact=fact*i
print(fact)

10. Find the Largest Number in a List


nums = [10, 20, 4, 45, 99]
largest = max(nums)
print("Largest number:", largest)
11. Find the factorial of a number using recursion
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)

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


print("Factorial:", factorial(num))
12. Find the key with the maximum value in a dictionary
data = {'a': 10, 'b': 25, 'c': 7}
max_key = max(data, key=data.get)
print("Key with max value:", max_key)
13. Implement a function to find all pairs in a list that sum to a
given target
def find_pairs(nums, target):
pairs = []
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
pairs.append((nums[i], nums[j]))
return pairs

nums = [2, 4, 3, 5, 7, -1, 8, 0]


target = 7
print("Pairs:", find_pairs(nums, target))

14. Fibonacci Sequence using recursion

def fibo(n):
if n==1:
return 0
if n==2:
return 1
return fibo(n-1)+fibo(n-2)

n = int(input())
print(fibo(n))
15. Generate Fibonacci sequence up to n terms, using recursion

def fibos(n):
if n==1:
return 0
if n==2:
return 1
return fibo(n-1)+fibo(n-2)

n = int(input())
for i in range(1,n+1):
print(fibos(i),end="")

16. Find the second largest number in a list,


nums = [10, 20, 4, 45, 99, 99]
unique_nums = list(set(nums))
unique_nums.sort()
if len(unique_nums) > 1:
print("Second largest number:", unique_nums[-2])
else:
print("No second largest number found.")
17. Remove duplicates from a list,
nums = [1, 2, 2, 3, 4, 4, 5]
unique_nums = list(set(nums))
print("List without duplicates:", unique_nums)
18. Remove duplicates from a list(without using set and with
using set),
nums = [1, 2, 2, 3, 4, 4, 5]
unique_nums = []
for num in nums:
if num not in unique_nums:
unique_nums.append(num)
print("List without duplicates:", unique_nums)
19. Rotate a list to the right by k places
nums = [1, 2, 3, 4, 5]
k = int(input("Enter number of rotations: "))
k = k % len(nums)
rotated_list = nums[-k:] + nums[:-k]
print("Rotated list:", rotated_list)
20. Rotate a List to the left by k Places
nums = [1, 2, 3, 4, 5]
k = int(input("Enter number of rotations: "))
k = k % len(nums) # To handle cases when k > len(nums)
rotated_list = nums[k:] + nums[:k]
print("Rotated list:", rotated_list)
21. Check if a number is an Armstrong number
num = int(input("Enter a number: "))
sum_digits = 0
temp = num
num_digits = len(str(num))

while temp > 0:


digit = temp % 10
sum_digits += digit ** num_digits
temp = temp // 10

if num == sum_digits:
print("Armstrong number")
else:
print("Not an Armstrong number")

You might also like