Python Programming


CybHer Dojo.


Challenges

The first thing to learn when programming is how to print information to the screen, as a program is only useful if you can see its results. In Python to print to the screen, we will use the print() function (we will cover functions in more detail later).

Print Syntax:

Text that you want to print, must be in quotes. Later, we will show you how to print other things too!

print("STRING MESSAGE TO PRINT")

For example:

print("My Output!!")

When run this will display the following:

My Output!!

In addition to printing things to the screen, you 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.

Comment Syntax:

# 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?

Challenge:

Use python to print the text 'Hello World!' to the screen.

  1. Create a new file with the file extension .py
  2. Write the python code to print the text Hello World!
  3. Test your code with python yourFile.py
  4. Verify your solution with verify yourFile.py

Connect with SSH

Link your SSH key, then connect with: ssh [email protected]

Programming is so much more than printing things to the screen. We also 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 lesson 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

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 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)

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

Challenge:

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 verify yourFile.py

Connect with SSH

Link your SSH key, then connect with: ssh [email protected]

Sometimes when we print, we want to include some more information instead of just the value stored in a variable. This can be accomplished in a couple different ways. The first way is simply adding multiple strings and variables together. A string of words needs to be wrapped in quotation marks "like this." Variables can be printed by just including the variable name. We need to use commas to separate each thing we want to print.

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)

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. The other way we could accomplish this is by using a format string. This requires some different pieces: the variable placeholders {}, the .format() function call, and the variables to be printed. 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:

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 a variable
# Example program output
Hello, Rizzler
  1. Test your code with python yourFile.py
  2. Verify your solution with verify yourFile.py

Connect with SSH

Link your SSH key, then connect with: ssh [email protected]

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 using 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. 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 inputed. So the 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 a couple of questions...

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:

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 of your name variable
# Example Running of the program
python yourScript.py
What is your name: Greg
Hello, Greg
  1. Test your code with python yourFile.py
  2. Verify your solution with verify yourFile.py

Connect with SSH

Link your SSH key, then connect with: ssh [email protected]

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 an integer (a whole number) and the input we get from the user will need to be an integer. To convert age from the input string to an integer/numberical value, you can simply "cast" it to an integer using the int() function. The int() function takes a string variable, and gives you the integer value stored in that string.

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

A shorter way to type the same thing:

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

Python will let you type cast to other data types as well. The ones you should be concerned about are int(), float(), and str().

Challenge:

Use python to calculate a users age + 7

  1. Create a new file with the file extension .py
  2. Write python to accept an integer from user input that represents their age
  3. Write the python code to calculate their age in 7 years and prints the resulting number
# Example Running of the program
python yourScript.py
What is your age: 15
22
  1. Test your code with python yourFile.py
  2. Verify your solution with verify yourFile.py

Connect with SSH

Link your SSH key, then connect with: ssh [email protected]

Knowledge Check I

That was quite a bit of learning you just did! This challenge will pull together some of the concepts from the previous challenges to help you hammer them down and become more comfortable with them.

Challenge:

Use Python to create a short 1-sentence Mad Lib. If you don't know what a MadLib is, you can click here to see what they are. In short, you will have a pre-written sentence that is missing a few words (verbs, nouns, adjectives), and then you will ask the user to supply the missing words.

Let me show you an example!

Here is our incomplete sentence: Hello, {Name}! Welcome to {Place} where we make {Plural Noun}.

You would then ask the user for words to fill in the sentence. That may look something like this:

Please give me a Name: Carl
Please give me a Place: Taco Bell
Please give me a Noun: Hamburgers

Here is your Mad Lib!

Hello, Carl! Welcome to Taco Bell, where we make Hamburgers.

In this challenge use printing, user input, and format a string to create a user generated MadLib!

Run verify yourFile.py to verify your solution!

Connect with SSH

Link your SSH key, then connect with: ssh [email protected]

Knowledge Check I

That was quite a bit of learning you just did! This challenge will pull together some of the concepts from the previous challenges to help you hammer them down and become more comfortable with them.

Challenge:

Your friend has asked you if you could write him a simple program that reads in 5 numbers, and then prints out the average of those 5 numbers.

Use input, print, and int to complete this challenge!

Run verify yourFile.py to verify your solution!

Connect with SSH

Link your SSH key, then connect with: ssh [email protected]

Now that you know how to get input from a user, 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, the following are what we care about right now:

<table> <thead> <tr> <th>Operator</th> <th>Name</th> <th>Example</th> </tr> </thead> <tbody> <tr> <td>+</td> <td>Addition</td> <td>a+b</td> </tr> <tr> <td>-</td> <td>Subtraction</td> <td>a-b</td> </tr> <tr> <td>*</td> <td>Multiplication</td> <td>a*b</td> </tr> <tr> <td>/</td> <td>Division</td> <td>a/b</td> </tr> <tr> <td>%</td> <td>Modulus</td> <td>a*b</td> </tr> <tr> <td>**</td> <td>Exponent</td> <td>a**b</td> </tr> <tr> <td>//</td> <td>Floor Division</td> <td>a//b</td> </tr> </tbody> </table>

You likely have used every operator before - besides Modulus and Floor Division. 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 rather straight forward. It 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.

Here is an example of how you might use these math operators...

# add 2 numbers together
x = int( input("Enter your first number: ") )
y = int( input("Enter your second number: ") )

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

The output will look like this:

# example output
Enter your first number: 4
Enter your second number: 5
4 * 5 = 20

Challenge:

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)
# example output
Please enter a number: 5
1
# example output
Please enter a number: 8
0
  1. Test your code with python yourFile.py
  2. Verify your solution with verify yourFile.py

Connect with SSH

Link your SSH key, then connect with: ssh [email protected]

Challenge:

Use python to read in two integers as input and performs 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 using the appropriate operator.
# example output
Enter the first number: 7
Enter the second number: 3
The result of floor division is: 2
  1. Test your code with python yourFile.py
  2. Verify your solution with verify yourFile.py

Connect with SSH

Link your SSH key, then connect with: ssh [email protected]

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: s²
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:

Use python to read in the width and height of a triangle using float, 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.

  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 to calculate the area of a triangle and print the result!
# example output
Base: 3
Height: 5
Area =  7.5
  1. Test your code with python yourFile.py
  2. Verify your solution with verify yourFile.py

Connect with SSH

Link your SSH key, then connect with: ssh [email protected]

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:

<table> <thead> <tr> <th>Operator</th> <th>Name</th> <th>Example</th> </tr> </thead> <tbody> <tr> <td>==</td> <td>Equal</td> <td>a==b, returns true if a is the same as b</td> </tr> <tr> <td>!=</td> <td>Not Equal</td> <td>a!=b, returns true if a is not the same as b</td> </tr> <tr> <td>></td> <td>Greater Than</td> <td>a>b, returns true if a is greater than b</td> </tr> <tr> <td><</td> <td>Less Than</td> <td>a<b, returns true if a is less than b</td> </tr> <tr> <td>>=</td> <td>Greater Than or Equal to</td> <td>a>=b, returns true if a is greater than or equal to b</td> </tr> <tr> <td><=</td> <td>Less Than or Equal to</td> <td>a<=b, returns true if a is less than or equal to b</td> </tr> </tbody> </table>

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:

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

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
  1. Test your code with python yourFile.py
  2. Verify your solution with verify yourFile.py

Connect with SSH

Link your SSH key, then connect with: ssh [email protected]

Knowledge Check I

Now that you've gotten to play around with basic math in Python, we are going to test your knowledge!

Challenge:

In this challenge, you will make a math test with 5 questions! You will need to read in answers for each question and check to make sure they're correct! At the end, tally the score and give them their percentage grade!

Use input to display the math equation and read in their answer. Then check the answer and keep track of which ones they get wrong or right.

Run verify <your_python_file.py> to check your code and get the flag!

Connect with SSH

Link your SSH key, then connect with: ssh [email protected]

Knowledge Check II

Now that you've gotten to play around with basic math in Python, we are going to test your knowledge!

Challenge:

Take in two numbers and, using floor division and the modulus operator, tell us how many times the second number fits into the first number, and what the remainder would be.

Example:

Enter first number: 100
Enter second number: 3

3 goes into 100 33 times with a remainder of 1.

Run verify <your_python_file.py> to check your code and get the flag!

Connect with SSH

Link your SSH key, then connect with: ssh [email protected]

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

Connect with SSH

Link your SSH key, then connect with: ssh [email protected]

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

Connect with SSH

Link your SSH key, then connect with: ssh [email protected]

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

Connect with SSH

Link your SSH key, then connect with: ssh [email protected]

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

Connect with SSH

Link your SSH key, then connect with: ssh [email protected]

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:

<table> <thead> <tr> <th>Operator</th> <th>Name</th> <th>Example</th> <th>Meaning</th> </tr> </thead> <tbody> <tr> <td>and</td> <td>AND</td> <td>CONDITIONAL1 and CONDITIONAL2</td> <td>Both CONDITIONAL1 and CONDITIONAL2 must be True to pass. If one is false it fails.</td> </tr> <tr> <td>or</td> <td>OR</td> <td>CONDITIONAL1 or CONDITIONAL2</td> <td>Either CONDITIONAL 1 or CONDITIONAL2 can be True to pass. If both are false it fails.</td> </tr> </tbody> </table>

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

Connect with SSH

Link your SSH key, then connect with: ssh [email protected]

Knowledge Check I

This challenge is going to test what you have learned in the conditionals module!

Challenge

In this challenge, you will create a program that takes in three inputs from the user, IN THIS ORDER:

  1. A number. Remember to convert it.
  2. One of the following math operators (+, -, *, /).
  3. A number. Remember to convert it.

NOTE: Do not include any numbers, or hyphens ('-') in your 'input' prompts.

Your program will identify what math operator is selected and then perform the operation, printing out the answer to the screen (Note: print ONLY the number.)

To test your code, run verify <your_python_file.py>, and get the flag!

Connect with SSH

Link your SSH key, then connect with: ssh [email protected]

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:

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!"
# Example Running of the program
python yourScript.py
Enter A Number: 5
5
4
3
2
1
Blast Off!
  1. Test your code with python yourFile.py
  2. Verify your solution with verify yourFile.py

Connect with SSH

Link your SSH key, then connect with: ssh [email protected]

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:

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 verify yourFile.py

Connect with SSH

Link your SSH key, then connect with: ssh [email protected]

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:

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 verify yourFile.py

Connect with SSH

Link your SSH key, then connect with: ssh [email protected]

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:

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
# Example Running of the program
python yourScript.py
Enter A Number: 10
2
4
6
8
10
  1. Test your code with python yourFile.py
  2. Verify your solution with verify yourFile.py

Connect with SSH

Link your SSH key, then connect with: ssh [email protected]

Knowledge Check I

This challenge is going to test your python knowledge up to this point!

Challenge

In this challenge you will write a program to calculate the hailstone number of a user supplied integer. This challenge will apply the collatz conjecture. This sounds scary, but it is rather simple.

The collatz conjecture states that any given number (N) will eventually become 1 given the following calculations:

  • If N is even, we divide it by two, and that becomes our new N.
  • If N is odd, we do the formula 3N + 1, and that becomes our new N.

We repeat this as many times as we need for N to equal 1. The hailstone number is how many calculations it takes to get from our starting N, to 1.

Example

If you were to start with N = 8. Then the following sequence would happen:

8 / 2 = 4

4 / 2 = 2

2 / 2 = 1

So, including our starting number of 8, the hailstone number would be 4. Since N was 8 -> 4 -> 2 -> 1 (4 numbers in total).

This challenge will require you to use conditionals, loops, and if statements to finish!

Your code must do 2 things:

  1. Take in one number from the user.
  2. Calculate the hailstone number and print out ONLY the number.

To test your code, run verify <your_python_file.py>, and get the flag!

Connect with SSH

Link your SSH key, then connect with: ssh [email protected]

30-Day Scoreboard:

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

Rank Hacker Badges Score