Python


CybHer CTF.

This module is all about python programming! We'd suggest working through modules in the order they're listed :)


Challenges

Challenge Description

How Do You Run a Python Program?

First, you write the program in a file — usually ending with .py (like my_program.py). This .py tells the computer and anyone else who looks at this file that it contains python code.

Then, you run the program using Python.

From the terminal, you can type: python my_program.py

And press Enter! The computer will follow the steps in your program and show the results.

The python in that command tells the computer what language your program is using, and how to interpret it. You can replace "my_program.py" with any python file you'd like to run.

Challenge Steps

This challenge requires you to run a python file we wrote for you!

  1. Start the challenge and open a terminal
  2. Run ls in your home directory, and you should see a python file named run_me.py
  3. Use python to run this file and receive your password
  4. Run /challenge/verify and enter the password
  5. Submit your flag!

Challenge Description

Now it's time for you to write your own python program! Just like if we were writing down the instructions to bake a cake, we need to create instructions for the computer to follow. These instructions will need to go in a python file with the .py file extension. The computer will follow all of your instructions in order from top to bottom!

Python Printing

The first thing we are going to learn is how to print information to the screen, so you can see what your program is doing. In Python, to print to the screen, we will use the print() function (we will cover functions in more detail later).

When we use the print() function, the message that you want to print must be in quotes. Later, we will show you how to print other things too! The print() function will always look something like this:

print("STRING MESSAGE TO PRINT")

For example, if we have a file named test.py, we can put the following contents in it:

print("My Output!!")

We can run this file by using python:

python test.py

And then we will see this output displayed on the screen:

My Output!!

Python Comments

In addition to printing things to the screen, you may sometimes need to add messages inside your code. This is called a comment. Comments can be useful to help explain Python code and make it more readable or to stop certain lines from executing.

# This is a comment

Comments start with a #, this is vital because it tells Python to ignore what follows. Comments can be placed on their own line, or at the end of an existing lines.

For example:

# This is a greeting print statement
print("GREETINGS USER!") # Another Comment, do you think this is a good greeting?

You don't need to use comments, but we may include them in challenge descriptions, and they can be helpful for making notes in your programs :)

Challenge Steps

Use python to print the text Hello World! to the screen. We will use the /challenge/verify to test your program and validate that it works properly.

  1. Use nano to create a new file, named whatever you want, but it must have the file extension .py (ex. my_first_program.py)
  2. Use the print() function to print the text Hello World!
  3. Test your code with python yourFile.py
  4. Verify your solution with /challenge/verify yourFile.py to get your flag!

Challenge Decription

We now need to learn how to store information and use it throughout the program: this can be accomplished with variables.

Variables allow us to store data in our programs and use it to compute results! You can imagine a variable as a box that can hold a single value at a time. All variables need a name, this is how we can access them to store/process data.

Python makes using variables super simple, as it doesn't care about defining the type of the variable. That is to say, you give python what you want to store and it just handles it, whereas some languages require you to explicitly declare what type it is beforehand.

For the sake of this challenge, we only care about Integers (whole numbers), Floats (decimal point numbers), and Strings (words/sentences). Here is how we declare each:

counter = 1000          # creates an integer numeric variable
total = 1024.67		    # creates a float numeric variable
name = "The Rizzler" 	# creates a string variable

Note the quotation marks around the string - those are required to store words/phrases!

Later we will learn how to use these variables throughout the program, but for now we are only concerned about declaring them correctly. The easiest way to verify that you created your variables correctly is to print them to the screen. Again, Python makes this super easy. We will use the same method (print()) we used in the Printing Text challenge, but this time we will pass the variables into it instead of hardcoding a string. This allows us to display the contents of our variables to the user.

Variable Syntax:

[VARIABLE_NAME] = [DATA_TO_STORE]

print([VARIABLE_NAME])

To print the variables declared above:

# Print each variable to the screen
print(counter)
print(total)
print(name)

This code will not print the variable names, but the contents of the variables - the data you stored in them. The output from the above code will look like:

1000
1024.67
The Rizzler

Try printing out your variables, and verify that they are exactly the same as what you assigned them to in your program.

Challenge Steps

Use python to create 3 variables. They can have any name, and any data stored in them. Maybe try saving your name, age, and GPA! After creating and storing data in them, print them all out!

  1. Create a new file with the file extension .py
  2. Write python to create 3 variables and print them to the screen
  3. Test your solution with python yourFile.py
  4. Verify your solution with /challenge/verify yourFile.py to receive your flag!

Challenge Description

Sometimes when we print variables, we want to include additional information to go with the value stored in a variable. This can be accomplished in a couple different ways.

Print multiple values

The first way is simply combining multiple strings and variables together. You might remember that the value stored in a variable can be printed with the variable name (print(var_name)). We can also print a string of hardcoded words (print("This is a string")) - the string must be wrapped in quotation marks. We can combine these two ways of printing information by putting them both in a single print() statement, with each part separated by commas.

Using the name variable we defined in the previous challenge, we could print a message before we print the value of name by doing something like this:

print("Name is defined as", name) #Note the comma between the string and the variable!

When run, the program will output the following:

Name is defined as The Rizzler

This is rather straightforward, but can become messy quickly if printing multiple variables and messages.

Format strings

The other way we could print additional information is by using a format string. This requires some different pieces:

  • quotation marks to contain the entire string ""
  • the variable placeholders {} (these go in the quotes)
  • the .format() function call (this goes after the quotes)
  • the variables to be printed (these go in the () of the .format())

Each placeholder {} is where a value will be printed. The order of your variables matters here - the first variable will print where the first placeholder is in your string.

If we put it all together, we can create some interactive prints. Using variables we defined previously, let's build out a format string:

print("Hello {}, Your Total is: {}".format(name, total))

When running this code, we will get the following output:

Hello The Rizzler, Your Total is: 1024.67

Challenge Steps

Use python to create and print a variable with .format

  1. Create a new file with the file extension .py
  2. Create a python variable that contains a name
  3. Write the python code to print the text Hello, <name> (where <name> is the name stored in your variable)
  4. Test your code with python yourFile.py
  5. Verify your solution with /challenge/verify yourFile.py
# Example program output
Hello, Rizzler

Challenge Description

Now that you understand variables, it is important to learn how to change them on the fly. This allows your program to be interactive, and can be accomplished by getting user input.

Starting with what you already know, you should be able to understand what the following does:

name = "The Rizzler"
location = "Ohio"

print("Hello, my name is", name)
print("I am from", location)

If you run this program repeatedly, the same output would be displayed every time. But what happens if you want to use a different name? Or different location? You have to open the code, change the values for each variable, save and run. This doesn't sound too bad right now, but imagine the code base was thousands of lines of python - this would not be ideal.

Because of this, you need a way to assign different values from the user in runtime - while the program is running. This can be accomplished with the input() function. We've used the print() function before to display output to the user, this time input() will "read in" input from the user.

When the program encounters the input() function, it will wait for the user to enter data until the Enter key is pressed. The sequence of characters that the user typed then get stored in a string variable for further use. The program then proceeds to run any following lines of code.

name = input()
location = input()

print("Hello, my name is", name)
print("I am from", location)

Now the variables are not assigned a specific value until runtime. Every time this program is run different values can be input - our program has become truly interactive.

You can copy the code above and see for yourself what the input() prompt looks like! You may notice that the program doesn't seem to be doing much of anything - until you type a word and hit Enter. This brings up an important question...

How does the user know the program is waiting for input? The user will have no idea that the program is waiting for input. If they know what the program is supposed to be doing, it will probably be fine. But if they don't, it might appear as though the program is hanging or not responding. You can give the user some instructions by providing a text prompt. This could be as simple as a print statement before the input line or by passing a prompt string to the input function.

Both methods will effectively accomplish the same thing, but with one small difference. If the prompt is a separate print() line before the input call, the program will display these on two separate lines. If you pass the prompt to the input() function, the program will both display the prompt and get user input on the same line.

# separate lines
print("Enter your name:")
name = input()
  
# the same line
name = input("Enter your name: ")

Challenge Steps

Use python to read a user's name and tell them Hello

  1. Create a new file with the file extension .py
  2. Write python to accept a name from the user - make sure to give them a prompt!
  3. Print Hello, <name> (where <name> is the value the user entered)
  4. Test your code with python yourFile.py
  5. Verify your solution with /challenge/verify yourFile.py
# Example Running of the program
python yourScript.py
What is your name: Greg
Hello, Greg

Challenge Description

Input is only stored in strings, but how do we do math on strings? For example, how would we add 7 to the user's age? With the knowledge we've gained so far, we may try something like this:

age = input("Enter your age: ")
future_age = age + 7
print("Age in the future", future_age)

Unfortunately, if you were to run the code above you would likely encouter a TypeError. This is because Python does not have the ability to do math on strings. So if you're expecting the user to input a numeric value, it will have to be converted from a group of characters into a number, which can then be used throughout the rest of the program. Thankfully, Python allows "type casting" and makes this process very easy. In the example above, we can most likely assume that age is supposed to be an integer (a whole number) and the input we get from the user will need to be a number. To convert age from the input string to an integer/numberical value, you can "cast" it to an integer by using the int() function. The int() function takes a string variable, and gives you the integer value stored in that string.

For example:

age = input("Enter your age: ") # read in as a string
age = int(age) # type cast to an int
future age = age + 3 # do some math
print("Age in the future", future_age) # print updated value

A shorter way to type the same thing is to call the int() function from within the input() function:

# read in as a string, then immediately cast to an int
age = int(input("Enter your age: ")) 
future_age = age + 3
print("Age in the future", future_age)

Python will let you type cast to other data types as well. The functions you may need in the future are int(), float(), and str().

Challenge Steps

Use python to calculate a users age + 7

  1. Create a new file with the file extension .py
  2. Write python to ask the user their age, and store that value as an integer
  3. Calculate what their age will be in 7 years and print the resulting number (ONLY the number! No extra output)
  4. Test your code with python yourFile.py
  5. Verify your solution with /challenge/verify yourFile.py
# Example Running of the program
python yourScript.py
What is your age: 15
22

An if statement in Python evaluates if some conditional is true or false. It contains a logical expression that compares some data (variables, program state, etc.), and a decision is made based on the result of that expression.

Python if statement syntax:

if EXPRESSION:
	# statement(s) to be executed if EXPRESSION is true

If the expression evaluates to true, then the statement(s) inside of the if block are executed. If the expression evaluates to false, then the code inside the if block is essentially skipped and the code after the end of the if block is executed.

Example of Python if statement:

discount = 0
total = 1200

if amount > 1000:
	discount = amount * 10 / 100
  
print("Total: {}".format(amount-discount))

Challenge:

Use python to determine which number is greater than another number. Remember that if an if statement doesn't evaluate to True, then the inside code doesn't run!

  1. Create a new file with the file extension .py
  2. Write python code to accept two integers (x, y) from user input
  3. Write python code that prints out which number is larger, using if statements.
# Example Running of the program
python yourScript.py
X: 15
Y: 23
23 is greater than 15
# Another Example
python yourScript.py
X: 15
Y: 5
15 is greater than 5
  1. Test your code with python yourFile.py
  2. Verify your solution with verify yourFile.py

An if-else statement operates similarily to an if statement, except it provides an additional block of code to run if the conditional evaluates to false.

Python if-else statement syntax:

if EXPRESSION:
	# statement(s) to be executed if EXPRESSION is true
else:
	# statement(s) to be executed if EXPRESSION is false

If the expression evalues to true, then the statement(s) inside of the if block are executed. If the expression evaluates to false, then the code inside of the else block are executed.

Example of Python if-else statement:

age = 25
print("age: ", age)

if age >= 18:
	print("Eligible to Vote!")
else:
	print("Not Eligible to Vote!")

Challenge:

Use python to determine if a number is even or odd

  1. Create a new file with the file extension .py
  2. Write python to accept an integer from user input
  3. Write the python code to determine if the number entered is even or odd
# Example Running of the program
python yourScript.py
Enter a number: 15
15 is odd
  1. Test your code with python yourFile.py
  2. Verify your solution with verify yourFile.py

Python also supports nested conditional statements which means we can use an if or if-else statement inside of an existing if or if-else statement.

Python Nested Conditional Statement Syntax:

if EXPRESSION1:
	# statement(s) to be executed if EXPRESSION1 is true
  if EXPRESSION2:
  	# statement(s) to be executed if EXPESSION1 and EXPRESSION2 is true

Example of Python Nested Conditional Statements:

number = 36
print("number= ", number)

if number % 2 == 0:
	if number % 3 == 0:
  		print("Divisible by 3 and 2")

Again, nesting isn't just limited to if statements. Say we have the following example: We offer different rates of discount on different purchase prices. - 20% on amounts exceeding 10000 - 10% on amounts between 5000 - 10000 - 5% on amounts between 1000 - 5000 - No discounts on amounts under 1000

amount = 2500
print("Amount: ", amount)

if amount > 10000:
  discount = amount * 20 / 100
else:
  if amount > 5000:
    discount = amount * 10 / 100
  else:
    if amount  > 1000:
      discount = amount * 5 / 100
    else:
      discount = 0

print("Total: ", amount - discount)

Challenge:

Use python to write a simple ATM system

  1. Create a new file with the file extension .py
  2. Write python code that gets two integers from the user (current balance, and amount to withdraw)
  3. Write a simple python ATM system, using nested conditionals, that can do the following:
    1. If a user requests to withdraw an amount greater than their current balance, print an insufficient funds message
    2. If a user requests to withdraw a negative amount, print an error message
    3. If the user requests to withdraw an amount that is not a multiple of 20, print an error message
    4. If the withdrawal is successful, deduct the amount from the balance and print the new balance
  4. Write the python code that print a message indicating the result of the transaction
# Example Running of the program
python yourScript.py
Balance: 15
Withdraw: 20
Error: Insufficient funds
# Another Example
pyton yourScript.py
Balance: 120
Withdraw: 20
New Balance: $100
# Another Example
pyton yourScript.py
Balance: 120
Withdraw: -20
Error: Withdraw Amount Must Be Positive
# Another Example
pyton yourScript.py
Balance: 150
Withdraw: 45
Error: Withdraw Amount Must Be a Multiple of 20
  1. Test your code with python yourFile.py
  2. Verify your solution with verify yourFile.py

Now, there might be a case in which you need to check multiple expressions to be true. If this is the case Python if-else statements support an additional way to check an expression - the elif block. This works similar to the else block, as the elif is also optional. However, an if-else block can contain only one else block, whereas there can be as many elif block as necessary following an if block.

Python if-elif-else statement syntax:

if EXPRESSION1:
	# statement(s) to be executed if EXPRESSION1 is true
elif EXPRESSION2:
	# statement(s) to be executed if EXPRESSION2 is true
else:
	statement(s) to be executed if EXPRESSION1 and EXPRESSION2 are false

The keyword elif is a short form of else if. It allows the logic to be arranged in a cascade of elif statements after the first if statement. If the first if statement evaluates to false, subsequent elif statements are evaluated one by one and comes out of the cascade if any one is satisfied. Lastly, the else block will be executed only if all the preceding if and elif conditions fail.

Using the example we covered in the Nested Conditional Section, we can get a simplied if-else statement that looks like this:

amount = 2500
print("Amount: ", amount)

if amount > 10000:
	discount = amount * 20 / 100
elif amount > 5000:
	discount = amount * 10 / 100
elif amount > 1000:
	discount = amount * 5 / 100
else:
	discount = 0
  
print("Total: ", amount - discount)

Challenge:

Use python to compare two numbers, printing the comparison result

  1. Create a new file with the file extension .py
  2. Write python to accept two integers (x, y) from user input
  3. Write the python code to determine if x is greater than, equal to, or less than y and prints the result
# Example Running of the program
python yourScript.py
X: 15
Y: 25
x (15) is less than y(25)
# Another Example Running of the program
python yourScript.py
X: 35
Y: 25
x (35) is greater than y(25)
# Example Running of the program
python yourScript.py
X: 15
Y: 15
x (15) is equal to y(15)
  1. Test your code with python yourFile.py
  2. Verify your solution with verify yourFile.py

Lastly, Python also supports logical operators. These allow you to combine two or more conditionals in one statement. These are the two supported logical operators we care about at this time:

Operator Name Example Meaning
and AND CONDITIONAL1 and CONDITIONAL2 Both CONDITIONAL1 and CONDITIONAL2 must be True to pass. If one is false it fails.
or OR CONDITIONAL1 or CONDITIONAL2 Either CONDITIONAL 1 or CONDITIONAL2 can be True to pass. If both are false it fails.

Example of Python Logical Operators:

number = 5
if number > 2 and number < 7:
    # Since 'number' is greater than 2
    # AND 'number' is less than 7
    # This if statement will equate to true
    # and print.
    print("True!")

if number < 1 or number >= 5:
    # Since this is an OR statement
    # only one of these conditions
    # needs to be satisfied in order
    # to equate to true.
    # The second statement is satisfied
    # because 'number' is greater than
    # or equal to 5.
    print("True!")

One thing to note, logical operators can be used inside of if and elif conditionals. If you use and the statement evaluates to true only if all the conditionals are true. If you use or the statement evaluates to true if one of the conditionals is true.

Challenge:

Use python to write a Student Classification System

  1. Create a new file with the file extension .py
  2. Write python code that gets two integers from the user (average test score, and attendence)
  3. Use conditionals with logical operators to determine a classification, under the following conditions:
    1. Average Test Score greater than or equal to 85 and an attendance greater than or equal to 90 means they are honors
    2. Average Test Score greater than or equal to 70 and an attendance greater than or equal to 75 means they are passing
    3. Anything else is falling
  4. Write the python code that prints the student's classification
# Example Running of the program
python yourScript.py
Average Test Score: 90
Attendance: 95
Student is a Honors Student
# Another Example
python yourScript.py
Average Test Score: 15
Attendance: 5
Student is a Failing Student
  1. Test your code with python yourFile.py
  2. Verify your solution with verify yourFile.py

Challenge Description

Now that you know how to get input from a user and type cast it, you need to learn how to do things with that input. The first thing we are going to cover is math operators. Python supports many different Math Operators, we are going to start with just 4:

  • Addition: + (e.g., a + b)
  • Subtraction: - (e.g., a - b)
  • Multiplication: * (e.g., a * b)
  • Division: / (e.g., a / b)

You most likely already know how to add and subtract things, now you just need to learn how to write the python code to do it for you! Here are some examples of doing math in python:

a = 10
b = 5

add = a + b
sub = a - b
mul = a * b
div = a / b

print(add)
print(sub)
print(mul)
print(div)

Output:

15
5
50
2

Here we are using separate variables to store all of the results, you can also re-use a variable if you'd like. Just be aware that once you update a value, the old one is gone forever! This code:

a = 10
b = 5

res = a + b
print(res)
res = a - b
print(res)
res = a * b
print(res)
res = a / b
print(res)

Will have the exact same output as above:

15
5
50
2

Challenge Steps

Add two numbers together!

  1. Create a new file with the file extension .py
  2. Get user input for 2 numbers (don't forget the prompts/type casting!)
  3. Add those two numbers together
  4. Print the result
  5. Test your code with python yourFile.py
  6. Verify your solution with verify yourFile.py to get the flag
# example output
Enter a number: 5
Enter another number: 7
12

Challenge Description

There are a few other math operators commonly used in python:

  • Modulus: % (e.g., a % b)
  • Exponent: ** (e.g., a ** b)
  • Floor Division: // (e.g., a // b)

The exponent is fairly straight forward (how many times we are multiplying a number by itself). Modulus is like division, but returns the remainder. For example, 4%2 would return 0 since 2 can fit into 4 exactly twice (with a remainder of 0). What would 5%2 return?

Floor division is just like division, but will round down if there is a remainder. For example, 5//2 would return 2, whereas 5/2 would return 2.5.

We use these math operators the same way as the other ones:

# exponential (3^3 = 27) (3*3*3 = 27)
x = 3
y = 3

exp = x ** y

print("{} ^ {} = {}".format(x, y, sum))

The output will look like this:

# example output
3 ^ 3 = 27

Challenge Steps

Use python to let the user enter a number and detect if that number is odd or even. Your program should print 0 for even and 1 for odd.

  1. Create a new file with the file extension .py
  2. Write the python code to get a number from the user (Don't forget to typecast)
  3. Use modulus to show if the number is odd or even. Your program should print 0 for even and 1 for odd. (Remember even numbers are always divisible by two) (Hint: 5 % 2 = 1, 8 % 2 = 0)
  4. Test your code with python yourFile.py
  5. Verify your solution with /challenge/verify yourFile.py to get your flag
# example output
Please enter a number: 5
1
# example output
Please enter a number: 8
0

Challenge Steps

Use python to read in two integers as input and perform floor division.

  1. Create a new file with the file extension .py
  2. Write the python code to get two numbers from the user
  3. Perform floor division on the two numbers and print the result
  4. Test your code with python yourFile.py
  5. Verify your solution with /challenge/verify yourFile.py to get the flag
# example output
Enter the first number: 7
Enter the second number: 3
The result of floor division is: 2

Challenge Description

Lets put your skills to the test! There are many common formulas that mathematicians need to memorize! In geometry, for example...

Finding the Area of shapes
Circle: π*r²
Square:
Triangle: 0.5 * b * h
Trapezoid: ((a + b) / 2) * h

To find the area of a square:

s = float(input("Length of side: "))
area = s**2 # ** to find exponent

print("Area = ", area)
# example output
Length of side: 5
Area =  25.0

Challenge Steps

Use python to read in the base and height (b and h) of a triangle using floats, then calculate and print the area.

Note: The area will be a float data type! Make sure to get user input and typecast it to a float (float() instead of int()).

  1. Create a new file with the file extension .py
  2. Write the python code to get two numbers from the user (triangle width and height)
  3. Use the formula above to calculate the area of a triangle and print the result!
  4. Test your code with python yourFile.py
  5. Verify your solution with /challenge/verify yourFile.py
# example output
Base: 3
Height: 5
Area =  7.5

Challenge Description

Programming involves alot more than just doing math on numbers. Another important aspect to programming is comparison. Comparison Operators return True or False based on the comparison being made. We will cover this in more detail later, but for now understanding how they look and what they return is important. The following Comparison Operators are important to know:

  • Equal: ==
    • a == b, returns true if a is the same as b
  • Not Equal: !=
    • a != b, returns true if a is not the same as b
  • Greater Than: >
    • a > b, returns true if a is greater than b
  • Less Than: <
    • a < b, returns true if a is less than b
  • Greater Than or Equal to: a>=b
    • a >= b, returns true if a is greater than or equal to b
  • Less Than or Equal to: a<=b
    • a <= b, returns true if a is less than or equal to b

Comparison Operators also leads us to a new data type! These comparisons return a boolean result. Boolean variables can be either True or False - only one or the other at any given time. This means that instead of resulting in an integer or a float, comparisons result in a boolean or bool. You can treat this result like a normal variable - you can store it, print it, and update it.

x = int(input("Enter a number: "))
res = x > 0 # use a variable to store result
print("Checking if number is positive: ", res)
print("Checking if number is negative: ", x < 0) # print result without storing
print("Checking if number is 0: ", x == 0)

Here are some examples of what the output might look like...

Enter a number: 5
Checking if number is positive:  True
Checking if number is negative:  False
Checking if number is 0:  False
Enter a number: -8
Checking if number is positive:  False
Checking if number is negative:  True
Checking if number is 0:  False
Enter a number: 0
Checking if number is positive:  False
Checking if number is negative:  False
Checking if number is 0:  True

Challenge Steps

Use python to read two numbers from the user and detect if the first number is smaller than the second.

  1. Create a new file with the file extension .py
  2. Write the python code to read in two numbers from a user
  3. Use comparison operators to print True, if the first number is less than or equal to the second number. If this is not the case, print False
  4. Test your code with python yourFile.py
  5. Verify your solution with /challenge/verify yourFile.py to get the flag

Example 1:

First number: 4
Second number: 8
Checking if first number is less than or equal to second:  True

Example 2:

First number: 23
Second number: 2
Checking if first number is less than or equal to second:  False

Challenge Description

While loops will repeat whatever is in the loop block while a given condition is True. It checks the conditional every iteration before executing the loop block. As soon as the condition is False, the program control passes to the line immediately following the loop.

If it fails to turn False, the loop continues to run and will not stop unless forced to stop. Such loops are called infinite loops, and are not ideal in a compute program.

Syntax of a Python while loop:

while EXPRESSION:
	# statement(s) to run will EXPRESSION evaluates to True

Example of a Python while loop:

count = 0
while count < 5:
	count = count + 1
  print("Iteration number {}".format(count))

print("End of while loop")

Challenge Steps

Use python to write a Count Down program

  1. Create a new file with the file extension .py
  2. Write python to accept an integer from the user
  3. Write a program that then counts down from the given number to 1, printing each number on a newline
  4. The program should stop when it reaches 1 and then print "Blast Off!"
  5. Test your code with python yourFile.py
  6. Verify your solution with /challenge/verify yourFile.py
# Example Running of the program
python yourScript.py
Enter A Number: 5
5
4
3
2
1
Blast Off!

Challenge Desription

A list is a built-in data type in Python. A Python list is a sequence of comma seperated items, enclosed in square brackets. Every item in a list can be made up of any type of variable we have learned about so far, and they don't necessarily need to be the same type. Examples of Python Lists:

list1 = ["Thomas", "Jefferson", "President", 3]
list2 = [1, 2, 3, 4, 5]
list3 = ["a", "b", "c", "d", "e"]

Challenge Steps

Use python to create 3 different lists

  1. Create a new file with the file extension .py
  2. Write python to create 3 python lists (a list of strings, a list of integers, and a list of floats)
  3. Test your solution with python yourFile.py
  4. Verify your solution with /challenge/verify yourFile.py

Challenge Description

Python also offers a built-in range() function that returns an iterator object, essentially a list of numbers. This object contains integers from start to stop and this can be used to run a for loop.

range() Syntax:

range(start, stop, step)
# Start is the starting value of the range. Optional. Default is 0.
# Stop is where range will stop, runs until stop-1.
# Step is how we want to increment the values in the range. Optional, default is 1.

Challenge Steps

Use python to see the different outputs of the range() command

  1. Create a new file with the file extension .py
  2. Write python to create 3 different range() calls, trying to use different start, stop, and step values.
  3. Test your solution with python yourFile.py
  4. Verify your solution with /challenge/verify yourFile.py

Challenge Description

The for loop in Python provides the ability to loop over items in an iterable sequence such as a list or string.

Syntax of a Python For Loop:

for VARIABLE in SEQUENCE:
	# statement(s)

Example of a Python For Loop with a List:

numbers = [1, 5, 6, 2, 7, 8, 2, 9, 10]
total = 0

for number in numbers:
	total = total + number
  
print("Total: ", total)

Examples of a Python For Loop with different range() Parameters:

'''
Fun tip!
You can use end='' to change how python prints, the default is end='\n' to print a special secret newline character
You won't need to use this for this challenge, we just didn't want you to have to scroll alot to read the example output :)
'''

for number in range(5):
	print(number, end=' ')
print() # Print an empty line

for number in range(10, 20):
	print(number, end=' ')
print() # Print an empty line
  
for number in range(1, 10, 2):
	print(number, end=' ')
print() # Print an empty line

Running the code above will output the following:

0 1 2 3 4 
10 11 12 13 14 15 16 17 18 19 
1 3 5 7 9 

Challenge Steps

Use python to write a program that prints even number

  1. Create a new file with the file extension .py
  2. Write python to accept a positive integer from the user
  3. Write python, using a for() loop, that iterates through the range starting at 0 to the given number
  4. Print only even numbers up until the user specified number (Hint: You may need to add one to the number the user entered to account for range printing to num-1)
  5. Test your code with python yourFile.py
  6. Verify your solution with /challenge/verify yourFile.py
# Example Running of the program
python yourScript.py
Enter A Number: 10
2
4
6
8
10

Challenge Description

Lastly, Python allows you to define your own functions. This is what we care about the most, as it allows you to write code that does a specific task and use it throughout your program. In this module we will focus on teaching you how to define your own functions (the syntax), how to pass arguments, and return values.

Python Function Syntax:

Python function definition follows these rules:

  • Function blocks begin with the keyword def followed by the function name, parentheses (), and a colon :
  • The code block then starts and must be indented
  • Finally, the statement return exits a function

Put that all together and you will get something that looks like this:

def FUNCTION_NAME():
	# Function Code Block Starts
  # Statement(s) to be executed
  return

Taking what we learned in the very first module, we can write a hello world greeting function. It would look like this:

def greeting():
	print("Hello World!")
  return

Now that this is created anytime we call the function greeting, "Hello World!" will be printed. This brings up a good point though, how do we call a function?

Defining a function only gives it a name, specifies the parameters that are to be used in the function, and structures the blocks of code to be included in the function. But, you need to be able to use that. The way to call a function is very similar to the way we called some of the built-in functions, like print() and int(). They are called by simply using the functions name. Using the greeting() function above, I will demonstrate how we would call it:

# Function Definition
def greeting():
	print("Hello World")
  return
  
# Main Program, we want to call it here
greeting()

Challenge Steps

Use python to write a functon that prints the number 1-10

  1. Create a new file with the file extension .py
  2. Write python, using a function, that prints the numbers 1-10
  3. Test your code with python yourFile.py
  4. Verify your solution with /challenge/verify yourFile.py

Challenge Description

Function arguments are the values or variables passed into a function when it is called. You can define what is to be passed when calling your function and the function's behavior will often depend on the arguments passed. This adds a new rule to our function definition:

  • Any parameters or arguments should be placed within the function definition's parentheses

While defining a function, you specify a list of variables within the parentheses (these are referred to as parameters). These parameters act as a placeholder for the data that will be passed to the function when it is called. When the function is called, value to each of these parameters must be provided and can be used just like any other variable, but are referred to by the parameter name. The values provided are known as arguments.

Example:

def greeting(name):
	print("Hello {}".format(name))
  return
  
greeting("Batman")
greeting("Brandon")
greeting("Chris")

Running this code will produce the following output:

Hello Batman
Hello Brandon
Hello Chris

Python supports mainy different types of Function Arguments, but the one we will cover in-depth is Positional/Required arguments. This is nothing new, as what we just wrote is considered a positional or required argument. They are called this, because the function cannot execute unless every parameter listed gets an argument in the correct positional order. Let's look at another example:

def printInfo(name, age):
	print("Name: ", name)
  print("Age: ", age)
  
printInfo("Brandon", 14)
printInfo("Chris")

Executing this code will print the following:

Name: Brandon
Age: 14
Traceback (most recent call last):
	File "test.py", line 6, in <module>
  	printInfo();
TypeError: printInfo() takes exactly 2 arguments (1 given)

From this we can see the first function call worked as expected because every parameter was passed in the correct order. The second one did not, as we did not pass anything for age and that is a required parameter.

Challenge Steps

Use python to write a basic calculator function

  1. Create a new file with the file extension .py
  2. Write python to accept two integers from the user
  3. Write python, using a function, that requires three parameters: number1, number2, and operation.
    1. Your calculator should support these operations: add, subtract, multiply, divide
    2. Print the result or an error message if the user attempts division by zero
  4. Call this function once for each supported operation
  5. Test your code with python yourFile.py
  6. Verify your solution with /challenge/verify yourFile.py
# Example Running of the program
python yourScript.py
Number 1: 13
Number 2: 12
25
1
156
1.08

Challenge Description

Now, sometimes we want functions to do something to our variables and return a result. This requires defining a function return value.

The return keyword as the last statement in function definition indicates the end of function block and that program flow "returns" to the calling function. Along with returning flow control, the function can also return values to the calling function. These values can be stores in variables for further processing. This introduces a change to the function definition rules:

  • Finally, the statement return [values] exits a function, optionally passing back a value to the calling function.

Let's also update our syntax:

def FUNCTION_NAME(PARAMETERS):
	# Function Code Block Starts
  # Statement(s) to be executed
  return VALUE

One thing to note, the return statement with no arguments (how we have been doing it up until this point) is the same as a return None statement.

Example:

def add(x,y,z)
	return x+y+z
  
a = 1
b = 2
c = 7
result = add(a,b,c)
print("a={}, b={}, c={}, a+b+c={},".format(a, b, c, result)

Executing this will produce the following output:

a=1, b=2, c=7, a+b+c=10

Challenge Steps

Use python to write a basic calculator function. You can update your existing python file, or make a new one! This time you will be returning the solution.

  1. Create a new file with the file extension .py
  2. Write python to accept two integers from the user
  3. Write python, using a function, that requires three parameters: number1, number2, and operation.
    1. Your calculator should support these operations: add, subtract, multiply, divide
    2. Return the result or an error message if the user attempts division by zero
    3. Print the result outside the function
  4. Call this function once for each supported operation
  5. Test your code with python yourFile.py
  6. Verify your solution with /challenge/verify yourFile.py
# Example Running of the program
python yourScript.py
Number 1: 13
Number 2: 12
25
1
156
1.08


30-Day Scoreboard:

This scoreboard reflects solves for challenges in this module after the module launched in this dojo.

Rank Hacker Badges Score