0% found this document useful (0 votes)
2 views

Python Cheatsheet Extracted

Uploaded by

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

Python Cheatsheet Extracted

Uploaded by

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

<

background 2.PNG

& Designer Design1 @

Text

cA)

Visuals

Image editing

Quick actions

Crop & rotate

Crop to object

Very hot weather


Now

Adjustments

Auto enhance

Checking for equality


A single equal ogn assigns @ vakat fom vanabin A cout equal
whether two values sre equ,
>>> car = thea?
cr

True
>>> Car = Sautit
>>> Car == thew”
False

Ignonng case when making a comparison


>>> Car = "Audi*

>>> car.doner(} <= ‘audi’


Irue

Checking [or inequality

>>> toppling = “aushroces”


>>> topping != ‘anchovies’
True

Sample boolean values


gaee_active = True

can ecit + False


Simpic if statement

ore - 15

if aye o> 18:


print (*¥au're ald enough te vote!)

if-else statements
ome - 27

tf age > IR:


print (°¥au" re ald enough to votel")
else:
print(“You can*t vote yet.~)
The if-elf-else chain
ope - 12

Sf age < 4:
orice - @
elif ope < 28:

price - 5
else:
price = 18

print(“Your cost is $" + striprice) + “.*)


Testing if a value is in a list

>>> players = [‘al', ‘bea’, ‘cyn", ‘cale']

>>> Tal’ in players

True

>>> ‘eric’ in players

False

Testing if a value is notin a list


bannec_users = (‘ann', ‘chad’, “dee*)
user = ‘erin®

Af user not in banned.


print("¥ou can pla:

Checking if a list is empty


players = [)

Af playe
for player in players:
print(*Player: * » player.title(})
else:
print("ne nave no players yet!”)

209% -~

Simple input

naae = input({"What's your nage? ")


print(“Hello, “+ nave + *.~)
Accepting numerical input

age = input("Hew old are you? ~)


age = int(age)

Sf age >= 1
print("\aYou can vete!")

else:

print("\aYou can't vote yet.")

Accepting input in Python 2.7

Use raw_input() in Python 2.7. This function interprets all Input as a

Sing. just as Mput() does in Python 3

nase = faw_ingut("What's your name? “)


print(“Hella, “+ nane + °.")

Caunting to §
current_nuaber = 1
while current_nunber <= 5:

print(current_ausber)
current_nurber += 1

Letting the user choose when to quit

promot + “\nTell we something, anc Ill “


prompt +> “repeat it back to you.”

proapt +- “\nfater ‘quit’ to end the program. *

message - ~
while message !- ‘quit’:
message - input (prorpt)

if message !+ ‘quit’;
print (nessoge)
Using a flag

prompt = “\nlell me sorething, ond I'll *


protat += "repeat it back ta you.”

prompt += “\nEnter ‘quit’ to end the prograr. ~

active + True
while active:
message = input(prenpt)

if message == ‘quit’:
active » False
else:
print (nessage)

Using break to exit a loop


protat = “\nahat cities have you visited?”
promt r= “\nEnter ‘quit’ when you're done.

wnile True:
city = input(orospt)

if city == ‘quit’:
break

else:

print(“I've been to“ + city # “I")


An infinite cop

while True:
name = input("\rWo are you? “)
orint(“Nice to meet vou. ~ + name + “!*)
Making a dictionary

alien @ = {*calor’; “green’, ‘points’; St

Removing all cats from a list of pets

pets = ['dog’, “cat', ‘dog’, fish’, ‘cat’,


‘rabbit’, ‘cat']

print( ners)

whale ‘cat’ in pets:


pets. remove, cat’)

print(pets)
Making 2 function

lef yreet_user():
**isplay a sieple preeting.*"*
prant(“Kello!")

greet_user()
Passing a single argument

det yreet_user(usernane) =
“““Dasplay 2 simple greeting.
prant("Hello, " + usernare +

greet_user(' jesse")
greet_user("diana")
Rreet_user('beeedon’ )

Using positional arquments

def describe petiarinal, ranc}:


"Display information about # pet
print(*hal have a * 4 anisal
print(tIts mare + onan +

deseribe get('narster’, ‘hecry"}


Hescrite pet ('dog’, ‘willie’)
Using keyword arguments
ef describe_petian inal, rane}:
“'"Di splay Lnfornat len about a pet
print(*inl have 2 * + eninsl + *
print(*Its nare iy“ + none +
descrine_pet(antral-"narster’, nare
Gescrine got(naro

‘You can provide @ defeutt value for a parameter. When


function cal's omit th’s arqumment the default valve wit be
used. Parameters mith default
“parameters without

valves mus! be listed after


An the function’s definition

Using a defauk value


det deseride pet(nane, enw
’''Display Lofartat ine: abaut a pet
nt(TkaT hawe a" = anival +
Ot(TTTS name iS 7 + naw eo
descrite pet('harry’, ‘rsmeter’)
descr ibe_pet (‘wl llie')

Using None to make an argument optional

scrape pet(ormal, nowe-here):


""*Display Lnfartation abaul a pet.***
print(*\al have a" + anlval + *.")
if none
peant( "Ets nave is * + rene > 2")

describe _pet('hanstor’, “narry")


describe _pet('snace’}
Making a list

users - [‘val’, ‘bob’, ‘ria’, ‘ron’, ‘ned”]

Passing a list as an argument

def greet_users(names):
“““Brint a simple greeting ta everyone.
for name in names:
asp - “Hello,
print(rsg)
usernames = ["hannah ", “margot’)
greet_users(usernanes

Allowing a function to modify a list


The following example sends a list of mode's to 2 function for
painting. The origina’ ist is emptied, and the second list is

def print_madels(urgrinted, printed}:


"""3d print 3 set of models.-°*
while unprinted:
current_nocel = unprinted.pop()
print(“Printing * + current node?)
printed. append( current model)
F Store some unprinted designs,

# snd print each of then.

unprinted ~ [phone case’, ‘pendant’, ‘ring’)


printed = []

orint_models(unprintes, grintec)

ungrintec)
printed)

orint("\nunprintec
print( “Printed:

Preventing a function from modifying a list


The folowing exampie i the same as the previous one. excep! ine
ongina! kst is unchanged after caling pnnt_ models)

def print_models(urgrintec, printed


“""3d print a set of nodels.~-~
while unprinted:
current_socel = unprinted. pap()
print("Printing * + current_nodel)
printed.append( current_model)

* Store some unprinted designs,

® and print each of then.

original = (“phone case’, ‘pendant’, ‘ring*)


printes = []

print_madels(criginal[:], printed)
print("\nOriginal:", original)
print("Printed:", printed)

Collecting an arbitrary number of arguments

def make_pizza(size, *toppings):


“"*Make a pazza."""
print("\nMaking a ~ + size + ~ pizza.7)
prant( “Toppings:
for topping in toppings:
print(7- " + topping)

© Make three pizzas with different toppings.

make pizza(‘small', ‘pepperani*}

make_pizza(' large ‘bacon bits’, ‘pineapple')

make _pizza('mediua’, “mushrooms”, ‘peppers’,


‘ontons’, ‘extra cheese’)

Collecting an arbitrary number of keyword arguments

det build profile(first, last, *tuser_info


"guild a user's profile dict ianary
* Guile a dict with the required keys.
profile = ("first’: first, ‘last’: last}

# Add any other keys and values.

for key, value in user_info.items():


profile[key] - value

return profile

# Create two users with different kinds

OQ Save &

Using a colormap
A colormap varies the point colors from one shade to another,
based on a certain value for each point. The value used to
determine the color of each point is passed to the c argument, and
the cmap argument specifies which colormap to use.

The edgecolor='none' argument removes the black outline


from each point.

plt.scatter(x_values, squares, c=squares,


cmap=plt.cm.Blues, edgecolor='none’,
s=10)

Filling the area under a data series

Pygal allows you to fill the area under or over each series of data.
The default is to fill from the x-axis up, but you can fill from any
horizontal line using the zero argument.

t = pygal.Line(fill=True, zero=0@)

chart.y title = ‘Stars’


chart.add('Python Repos’, repos)
chart. render_to_file('python_repos.svg')

ENG Ady O

5:36 PM
6/8/2025

You might also like