Python Cheatsheet

Python Syntax#

Files

All Python files & programs have the .py ending. ex: main1.py

Comments

Comments are used to help understand a piece of code. Comments are ignored by the compiler and are human-readable words intended to make the code more readable.

# this is an example comment

Indentation & Colons

While most programming languages use brackets { } to define blocks of code, Python uses indentation and colons : instead. Lastly, unlike other languages like Java, Python does not require semicolons ; at the end of each line.

Check out this article for more on comments and indentation in Python.

print()#

The print() function print outs something in the console. ex: Hello World

print('Hello World')

To print multiple things, use a comma , if you want a space; or use + for no space.

print('Bob', 'Joe')
# prints Bob Joe
print('Bob' + 'Joe')
# prints BobJoe

Check out this article for more on print statements in Python.

Variables#

Variables are containers for storing data values. Unlike other programming languages, Python does not require variable declaration. A variable is created the moment you first assign a value to it.

Integer

An Integer is a whole number with no decimal points. Examples of integers are: 22, -14, 39

x = 5
print(x)

In this example, the integer variable x has been assigned the value of 5 and the program will print out 5 when run.

String

A String is a sequence of characters that typically represents text. Examples of Strings are: Hello, Python, the brown fox jumps over the lazy dog

y = "John"
print(y)

In this example, the String variable y has been assigned the value of John and the program will print John when run.

Boolean

A Boolean represents either True or False and is used in logic computing.

z = True
print(z)

In this example, the Boolean variable z has been assigned the value of True and the program will print True when run.

Check out this article for more on variables in Python.

input()#

the input() function gets the the users input

x = input('Enter your name:')
print('Hello', x)

Input/Output:

Enter your name: Bobby Joe  # user inputs "Bobby Joe"
Hello Bobby Joe             # program outputs "Hello Bobby Joe"

Note the print() function automatically added a 'space' in between the Hello and Bobby Joe

Taking multiple inputs: To take multiple inputs at once, simply use the split() as shown below

x, y = input("Enter two values: ").split()
# allows the user to input two values, one for x and one for y

Check out this article for more on the Python input() function.

If Statements#

Logical Statements

Python supports the usual logical conditions from mathematics:

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in “if statements” and loops.

An “if statement” is written by using the if keyword.

x = 75
y = 100
if y > x:
  print("y is greater than x")

Output:

y is greater than x

Else Statements

Will execute if the “if statement” is not satisfied (true)

x = 100
y = 75
if y > x:
  print("y is greater than x")
else:
  print("y is less than x")

Output:

y is less than x

Elif Statements

The elif keyword, also knows as “else if”, is pythons way of saying “if the previous conditions were not true, then try this condition”.

x = 100
y = 100
if y > x:
  print("y is greater than x")
elif y == x:
  print("y is equal to x")
else:
  print("y is less than x")

Output:

y is equal to x

Calculator Activity

Using everything we’ve learned so far, create a simple calculator with the following requirements

Input:

  • First Line: a number 1-4 to specify a mathematical function
    • 1: addition
    • 2: subtraction
    • 3: multiplication
    • 4: division
  • Second Line: num_1
  • Next Line: num_2

Constraints:

  • num_1 & num_2 are integers
  • -100 < num_1 < 100
  • -100 < num_2 < 100

Output:

The result from carrying out the function on the two numbers

Solution Code:

operation = int(input())
num_1 = int(input())
num_2 = int(input())
if operation == 1:
  print(num_1 + num_2)
elif operation == 2:
  print(num_1 - num_2)
elif operation == 3:
  print(num_1 * num_2)
else:
  print(num_1 / num_2)

Here is the solution code to the bonus problem we talked about in class.

operation = int(input("Enter 1 for addition, 2 for subtraction, 3 for multiplication, and 4 for division: "))

if operation != 1 and operation != 2 and operation != 3 and operation != 4:
    print("The number you entered does not match an operation")
    
num_1 = int(input("Enter first number: "))
num_2 = int(input("Enter second number: "))

if operation == 1:
    print("The sum is", num_1 + num_2)

elif operation == 2:
    print("The difference is", num_1 - num_2)

elif operation == 3:
    print("The product is", num_1 * num_2)

else:
    print("The quotient is", num_1 / num_2)

Check out this article for more on if statements in Python.

Loops#

For Loops#

A “For Loop” is useful when you know the amount of iterations to loop over

Syntax Example:

for i in range(3):
  print("Hello")

Output:

Hello
Hello
Hello

Loops 3 times and prints ‘Hello’ each time


Syntax Example 2:

for i in range(3):
  print(i)

Output:

0
1
2

Loops 3 times, i starting at 0 and ending at 2. Prints i each time

While Loops#

Syntax:

while condition:
    # statements to be executed

A while loop will iterate as long as the boolean condition is true. Useful when unsure about the number of iterations

Example:

i = 0
while i < 4:
    print(i)
    i += 1

Output:

0
1
2
3

During each iteration, the loop will print out the value of i which starts at 0 and increments by 1 via i+=1 and ends at 3.

Check out this article for more on loops in Python.

Arrays#

An array is a collection of elements of the same data type. Arrays are used to store collections of data.

Declaring/Initializing#

There are many various ways to declare an Array, below is a common declaration method.

Fruits = ["apples", "bananas", "pears"]

The first line creates an String Array of size 3 with the name Fruits, containing elements apples, bananas, pears.

Accessing Elements of an Array#

Fruits = ["apples", "bananas", "pears"]
print(Fruits[0])
Fruits[0] = "lemon"
print(Fruits[0])

Output:

apples
lemon

Python Arrays are zero-indexed (starts counting from 0). The first element of an array can be accessed using the name of the Array then [0] as shown by line 2.

In line 3, Fruits[0] has the value bananas, but was reassigned to lemon. In line 4, when we print the value of Fruits[0], the program prints lemon.

You can treat each element of an Array as a variable and all specific properties of the corresponding data type still applies to Array elements.

Looping through an Array#

We can loop through an Array using a for loop.

Syntax:

Fruits = ["apples", "bananas", "pears"]
for i in Fruits:
  print(i)

Output:

apples
bananas
pears

Check out this article and this article for more on Arrays in Python.

This is still a work in progress
Created By: WHS Comp Sci Club Officers

CC-BY-NC-SA 4.0 | WHS CSC 2021