DEV Community

Louie Aroy
Louie Aroy

Posted on • Updated on

Python Cheatsheet

Basic syntax examples for programmers who are starting to learn python.

Comments

# This is a single line comment
Enter fullscreen mode Exit fullscreen mode

Numbers

# declare int
day = 18

# declare float
amount = 2.5



brothers_age = 30
my_age = 25

# math equation
age_gap = brothers_age - my_age

# output to console
print(age_gap)

"""
Result:
5
"""
Enter fullscreen mode Exit fullscreen mode

Strings

# declare strings
first_name = "Louie"
last_name = "Aroy"
age = 25


print(first_name, last_name, age)

# concatenate
print(first_name + " " + last_name + " " + age)

"""
Result:
Louie Aroy 25
Louie Aroy 25
"""
Enter fullscreen mode Exit fullscreen mode

List


# declare list
players = [25, 58, 66, 71, 87]

print (players[2])

"""
Result: 
66
"""


# update list value
players[2] = 68

print (players)
Result:
[29, 58, 68, 71, 87]

# add variables to list
players.append(120)

print (players)

"""
Result:
[29, 58, 68, 71, 87, 120]
"""

# add multiple variable to list
players + [122, 123, 124]

print (players)

"""
Result:
[29, 58, 68, 71, 87, 120, 122, 123, 124]
"""
Enter fullscreen mode Exit fullscreen mode

If Else

name = "Tommy"

if name is "Bucky":
    print("Hey there Bucky")
elif name is "Lucy":
    print("What up Lucy?")
elif name is "Sammy":
    print("What up Slammy?")
else:
    print("Please sign up for the site!")


"""
Result:
Please sign up for the site!
"""
Enter fullscreen mode Exit fullscreen mode

For Loop

foods = ['bacon', 'tuna', 'ham', 'snausages', 'beef']

for food in foods:
    print(food)
    print(len(food))


"""
Result:
bacon
5
tuna
4
ham
3
snausages
9
beef
4
"""
Enter fullscreen mode Exit fullscreen mode

Loop with Range


# loop 5 times
for x in range(5):
    print("I'm awesome!")


# loop in 8 inclusive upto 12 exclusive
for x in range(8, 12):
    print(x)

"""
Result:
I'm awesome!
I'm awesome!
I'm awesome!
I'm awesome!
I'm awesome!


8
9
10
11
"""
Enter fullscreen mode Exit fullscreen mode

While loop

pimples = 5

while pimples < 10:
    print(pimples)
    pimples += 1
Enter fullscreen mode Exit fullscreen mode

Functions

# declare a function
def bitcoin_to_usd(btc):
    amount = btc * 527
    print(amount)

# call a function
bitcoin_to_usd(3.85)
bitcoin_to_usd(1)
bitcoin_to_usd(13)

"""
Result:
2028.95
527
6851
"""
Enter fullscreen mode Exit fullscreen mode

Return Values

def allowed_dating_age(my_age):
    girls_age = my_age/2 + 7
    return girls_age

buckys_limit = allowed_dating_age(27)
print("Bucky can date girls", buckys_limit, "or older")

creepy_joe_limit = allowed_dating_age(49)
print("Creepy Joe can date girls", creepy_joe_limit, "or older")

"""
Result:
Bucky can date girls 20.5 or older
Creepy Joe can date girls 31.5 or older
"""
Enter fullscreen mode Exit fullscreen mode

Default Values for Arguments

def get_gender(sex='Unknown'):
    if sex is 'm':
        sex = "Male"
    elif sex is 'f':
        sex = 'Female'
    print(sex)

get_gender('m')
get_gender('f')
get_gender()

"""
Result:
Male
Female
Unknown
"""
Enter fullscreen mode Exit fullscreen mode

Keyword Arguments

def dumb_sentence(name='Bucky', action='ate', item='tuna'):
    print(name, action, item)

dumb_sentence()
dumb_sentence("Sally", "laughs", "hard")
dumb_sentence(item="awesome", action="is")

"""
Result:
Bucky ate tuna
Sally laughs hard
Bucky is awesome
"""
Enter fullscreen mode Exit fullscreen mode

Dictionary

# declare a dictionary
classmates = {
    'Tony': 'cool but smells', 
    'Emma': 'sits behind me', 
    'Lucy': 'asks too many questions'
}

# loop through the dictionary
for k, v, in classmates.items():
    print(k, v)

# output one dictionary value
print(classmates['Tony'])


"""
Result:
Lucy asks too many question
Tony cool but smells
Emma sits behind me

cool but smells
"""
Enter fullscreen mode Exit fullscreen mode

Class

# create a class
class Person:
  # on initialize
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def introduce(self):
    print("Hello my name is " + self.name + ", " + self.age + " years old.")

p1 = Person("John", 36)
p1.introduce()

"""
Result:
Hello my name is John, 36 years old.
"""
Enter fullscreen mode Exit fullscreen mode

Inheritance

# inherit from above class
class Student(Person):

  def studentIntro(self):
      print("Hi classmates, my name is " + self.name + ", " + self.age + " years old.")


s1 = Student("Luigi", 15)
s1.introduce()
s1.studentIntro()

"""
Result:
Hello my name is Luigi, 15 years old.
Hi classmates, my name is Luigi, 15 years old.
"""
Enter fullscreen mode Exit fullscreen mode

Modules

tuna.py
def fish()
    print("I am a tuna feesh!")


main.py
import tuna

tuna.fish()

"""
Result:
I am a tuna feesh!
"""
Enter fullscreen mode Exit fullscreen mode

Reference:
TheNewboston Python Tutorial
https://www.youtube.com/watch?v=HBxCHonP6Ro&list=PL6gx4Cwl9DGAcbMi1sH6oAMk4JHw91mC_

Syntax
https://www.w3schools.com/python/

Challenges
https://edabit.com/challenges/python3

Oldest comments (1)

Collapse
 
molecula451 profile image
Paul

Good post. Good stuff to always keep in mind when using Python.