As a quick refresher, here are some of the basic programming syntax structures. For more information, check out our actual python course, our YouTube playlists. While there is a lot more to this language, this helps give you a good idea of where to start with the basics. We are not talking about built in data types, nor object oriented code in this quick review.
Comments
Comments are created by placing a hash symbol at the front of the line.
# This is a comment
This is not, and will generate an error as it's not real code.
Declaring Variables
To declare a variable, just use it. No need to declare it early, or define it’s type.
Strings are enclosed within either double quotes "
or single quotes '
.
name = "Bob"
last_name = 'Smith'
PI = 3.141592 #python doesn't really have constants like most languages, so we put the name in all caps
age = 21
Conditions
Conditions use an if for one condition, elif for multiple conditions, and else for if the condition is false. The if is required, all others are not required.
The block to be executed if true, is indented, typically 4 spaces.
if name == "bob" :
print("Your name is Bob")
elif name == "Sue" :
print("Your name is Sue")
else :
print("You are neither Bob nor Sue")
Loops
There are two basic types of loops within Python. Conditional loops and Counting Loops.
Conditional Loops
Conditional loops use a condition, just like the if statement. While the condition is true, you will keep doing the loop. This is why we used the while
keyword.
while again != 'q' : # user needs to press the letter q to quit
print("Here we go again")
again = input("Want to go again? Press 'q' to quit")
Counting Loops
The counting loop, or for
loop, in Python is different than in most languages. It most closely resembles a foreach
loop in other languages, where it goes through a group of elements, such as in a list.
employees = ["Sue", "Mark", "Lori", "Scott", "Tina", "Chuck", "Steve"]
for emp in employees :
print(emp + " is one of our employees")
Functions
Functions are like little mini-programs which you can call. To define a function you will use the def keyword, and if you need to return a value, you will use the return keyword.
def add(x, y) :
return x + y
Review of Python Syntax was originally found on Access 2 Learn
One Comment
Comments are closed.