Show Menu
Cheatography

Python Basics, definitions and examples

Rules

Python relies on proper indent­ation.
For example:

age = 18
if age >=18:
  print(­"Be sure to vote")
else:
  print(­"­Sorry, too young")

Naming Rules

A variable name: MUST begin with a letter or unders­core(_)
CANNOT contain spaces, punctu­ation or special characters others than the underscore
CANNOT begin with a number
CANNOT be the same as a reserved keyword in Python such as print, True, else, etc
A variable name is case sensitive

built-in functions

print()
this outputs something to the screen
input()
ask for input from the program user
str()
converts a variable to a string data type
int()
convert a variable to an int data type
float()
convert a variable to a float(­dec­imal) data type
round()
rounds a number

Comparison Operators

==
Equal to
!=
Not equal to
>
Greater than
<
Less than
>=
Greater than or equal to
<=
Less than or equal to

Basic Math Operators

+
Addition
-
Subtra­ction
*
Multip­lic­ation
/
Division
%
division remainder
**
Exponent

Data Types

str
string­(ch­ara­cteres typically words, sentences)
int
intege­r(0­,5,133)
float
decimal number­(1.2­3,­623.664)
list
a collection of variables (mango, banana, oranges)
bool
boolean value (True, False)

Special Characters

\n
new line
\t
tab

LOCAL/­GLOBAL Variables

LOCAL
Variable created within a function and only can be used by the function that defines them
GLOBAL
Variable defined outside of a function and can be accessed by any function without passing them to the function. Read-only and cannot be modified

Boolean Operators

not x
x and y
x or y

try and except

try:
  code statements
except: #for all exceptions
  code statements

try:
  code statements
except ValueE­rror: #Specific error type
  code statements
 

Concat­enate using "­+" or "­f"

combining strings

myName = "­Nam­e"
print(­"­Hello " + myName)

print(­f"Hello {myNam­e}")

string and a numeric value

age= 22
print(­"Your age: " + age)

print(­f"Your age: {age}")

Capital and lowercase letters

hello = "hello world"

print(hello.upper())
  # will print HELLO WORLD
print(hello.lower())
  # will print hello world
print(hello.capitalize())
  # will print Hello world

Control loops

break
breaks out of your loop causing the program to move to the next line after the loop
continue
while skip this round of the loop and go into the next loop iteration

Statements

If Statement
if expression:
­  Â­sta­t­ements
elif expression:
­ ­ sta­te­ments
else:
­ ­ sta­te­ments

While Loop
while expression:
­  Â­sta­te­ments

For Loop
for var in collection:
­ ­ sta­te­ments

Counting For Loop
for i in range(start, end [, step]):
­  ­Â­st­a­t­ements
(start is included; end is not)

if statements

if myAge < 18:
   print("Too young") #If TRUE prints this
elif my Age <21:
   print("Go ahead") #If TRUE prints this
else:
   print("Bye!") #if FALSE prints this

While loops

#while loops run as long as, or while, a certain condition is true

while True: 
     #do something
else:
     #do something

#Example:
current_number = 1 #set the first value
 #check the value of current_number and see if it is less than or equal to 5
while current_number <=5:

   print(current_number)  #print out the value of the variable
   current_number += 1   #add one to the variable
The loop will run again until the curren­t_value variable becomes 6 and then it will stop. Use break and continue to control loop

for loops

colors = ['red', 'green', 'blue']
#colors is a list data type

for color in colors:
    #name each individual item color within the colors list so that you can output the individual variable
    print(color)

write() method example

**Opening in append mode will add the new data to the end of the file"
with open ("filena­me.txt, "­a") as File:
  File.w­rit­e("H­ell­o\n­")

Read methods

read()
read the entire file and return its contents as a string
readli­nes()
read the entire file and return its contents as a list
readline()
read the next line in the file and returns its content as a string
read() adn readli­nes() work best for smaller files. readline() for larger files.
 

Function Definition

Function named blocks of code that are designed to do a specific task

def name(arg1, arg2, ...):
­ code statements
­ ­return expr
return: stores the variable
It can be with arguments or without it

Functions Example

Function definition with NO argume­nts­/pa­ram­eters
def helloW­orld():
 ­pri­nt(­"­Hello, world!­")

Function definition WITH argume­nts­/pa­ram­eters
def helloUser(firstName):
  print(­"­Hel­lo", firstName)

Calling a function
helloW­orld()

LISTS/­TUPLE

List [ ]
Collection of items in a particular order. List indexes start at 0
Tuple ( )
It is a list but Unable to be changed

Lists functions Example

fruits =
['apple', 'banana' , 'orange']
print(­fruits)
Output an entire list
print(­fru­its[2])
Output an element in a list: orange
fruits[0] = 'grapes'
Modifying an element in a list: apple by grapes
fruits.ap­pen­d('­pear')
Adding an element to the end of a list
fruits.in­sert(0, 'mango')
adding a list element in a specific position
fruits.re­mov­e('­ban­ana')
removing a list element
fruits.pop(0)
removing a specific list element
fruits.pop()
removing the last list element
del fruits
removing an entire list
fruits.cl­ear()
emptying a list
findApple = (fruit­s.c­oun­t("a­ppl­e"))
count for specific item
fruits. reverse()
reverse the order of list
fruits.sort()
sort the list. fruits.so­rt(­key­=st­r.l­ower) to make sure everything is in lowercase
sorted­_fruits = sorted­(fr­uits)
If you want the list to remain the same positions, you can use the sorted to create a copy of the sorted list without impacting the original list

Types of files

Text files
each line ends with a new line character (\n) or a carriage return character (\r) on Windows systems
Binary files
Are intended to be read by other programs, not humans. common types are: program files, image files, audio files, video files, database files and compressed files.

File fuctions

open(filename, mode)
mode is an optional argument that specifies how you want to open the file. r = read, a = append, w = write, b = binary.
filename.close()
close an open file object
print(filename.read())
output the content of the file
with open(filename) as newfil­ename:
automa­tically close a file if an exception happens. Also, it allows to assign a name to the file object in the same line of code and ends with a colon: creating a code block
write() method
use write mode when you are creating a new file, not when you are working with an existing file of data, Open the file in append mode ("a") if you wish to add to an existing file.
A file path must be included if the file is not in the same directory as the Python program
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          More Cheat Sheets by pao361

          C# CheatSheet Cheat Sheet