Python Cheatsheet
Python Cheatsheet
Variable assignment
Price1 = 10
Price2 = 4.9
course = ‘Python’
flag = True
Receive input
data = int(input(‘Enter value :’))
If statements
if <condition 1>:
print(“message 1”)
elif <condition 2>:
print(“message 2”)
else:
print(“message 3”)
While loops
while <condition>:
print(“inside loop”)
For loops
for i in range(1, 5):
print(i)
Functions
def my_function(x,y):
return x+y
a,b = 10,20
print(my_function(a,b))
Lists
L1 = [10,20,30,40,100]
L1.append(10),len(L1), del L1[2], max(L1),min(L1),sum(L1),
L1.insert(0,10), L1.pop(), L1.pop(3), sorted(L1),
L1.reverse(), L1.index(10), L1.count(10), L1.remove(10)
for i in range(5):
print("L1[i] = ",L1[i])
1
DATA 505 : Programming in Python (Cheat sheet for End-term Examination)
Strings
S, s1 : string variables
d : delimiter
s.count(s1), s.find(s1), s.rfind(s1), s.index(s1),
s.rindex(s1), s.lower(s1), s.replace(old,new),s.rstrip(),
s.split(d)
Turtle
import turtle
t = turtle.Turtle()
for i in range(4):
t.forward(50)
t.right(90)
Tuples
t1 = (1, ‘two, 3)
Dictionaries
dict = {key1: value1, key2: value2, ... keyN: valueN}
File Handling
f = open(“filename.txt”,’r’) Read operation
f = open(“filename.txt”,’w’) Write operation
f.close()
f.read(5)
f.readline()
f.readlines()
f.write(string)
f.writelines(string)
f.seek(0)
f.tell()
Plotting
np.arange(start,stop,step)
plt.xlabel('x values')
plt.ylabel('f(x)')
plt.title('Plots for f(x)')
fig, axes = plt.subplots(, , figsize=(,))axes[].scatter(x[:],
y[:])axes[].set_title("scatter")axes[].step(x[:], y[:])
axes[].set_title("step")axes[].bar(x[:],y[:])axes[].set_title(
"bar")
Scientific libraries
import numpy as np
from matplotlib import pyplot as plt
import pandas as pd