Worksheet 5 - Python Introduction: Difference between revisions
No edit summary |
No edit summary |
||
| Line 17: | Line 17: | ||
# Basic input | # Basic input | ||
name = input("Enter your name: ") | name = input("Enter your name: ") | ||
print("Hello | print(f"Hello {name}!") | ||
</syntaxhighlight> | </syntaxhighlight> | ||
| Line 27: | Line 27: | ||
=Basic Math Operations= | =Basic Math Operations= | ||
python | |||
<syntaxhighlight lang="python"> | |||
# Basic operations | # Basic operations | ||
print(5 + 3) # Addition | print(5 + 3) # Addition | ||
| Line 42: | Line 42: | ||
Bonus Challenge: Create a calculator that allows the user to choose the operation (addition, subtraction, etc.) they want to perform on two numbers. | Bonus Challenge: Create a calculator that allows the user to choose the operation (addition, subtraction, etc.) they want to perform on two numbers. | ||
=Variables= | |||
python | |||
<syntaxhighlight lang="python"> | |||
# Storing and printing variables | # Storing and printing variables | ||
name = "Alice" | name = "Alice" | ||
favorite_number = 7 | favorite_number = 7 | ||
print("My name is | print(f"My name is {name} and my favorite number is {favorite_number}") | ||
</syntaxhighlight> | |||
Task: Assign a new value to favorite_number and print it out. | Task: Assign a new value to favorite_number and print it out. | ||
| Line 55: | Line 57: | ||
Bonus Challenge: Write a small program that asks for the user’s name and age, then prints a statement with both. | Bonus Challenge: Write a small program that asks for the user’s name and age, then prints a statement with both. | ||
=Data Types= | |||
python | |||
<syntaxhighlight lang="python"> | |||
# Assigning different data types | # Assigning different data types | ||
my_string = "Hello" | my_string = "Hello" | ||
| Line 67: | Line 69: | ||
print("Float:", my_float, type(my_float)) | print("Float:", my_float, type(my_float)) | ||
Task: Create a new variable of type boolean (True/False) and print its type. | Task: Create a new variable of type boolean (True/False) and print its type. | ||
</syntaxhighlight> | |||
Additional Challenge: Write a program that uses an integer and a float and prints their sum. | Additional Challenge: Write a program that uses an integer and a float and prints their sum. | ||
| Line 73: | Line 76: | ||
=Conditional Statements= | |||
python | |||
<syntaxhighlight lang="python"> | |||
# Basic conditional check | # Basic conditional check | ||
number = int(input("Enter a number: ")) | number = int(input("Enter a number: ")) | ||
| Line 84: | Line 87: | ||
else: | else: | ||
print("Zero") | print("Zero") | ||
</syntaxhighlight> | |||
Task: Modify the program to check if the number is even or odd. | Task: Modify the program to check if the number is even or odd. | ||
| Line 90: | Line 95: | ||
Bonus Challenge: Add a check to see if the number is a multiple of both 2 and 3. | Bonus Challenge: Add a check to see if the number is a multiple of both 2 and 3. | ||
=Loops= | |||
python | |||
<syntaxhighlight lang="python"> | |||
# Printing numbers from 1 to 10 | # Printing numbers from 1 to 10 | ||
for i in range(1, 11): | for i in range(1, 11): | ||
print(i) | print(i) | ||
</syntaxhighlight> | |||
Additional Challenge: Write a loop to print numbers from 1 to 10 in reverse order. | Task: Print only even numbers from 1 to 10. try '''for i in range(0, 10, 2):''' | ||
Additional Challenge: Write a loop to print numbers from 1 to 10 in reverse order. Try '''for i in range(10, 0, -1):''' | |||
Bonus Challenge: Use a loop to calculate the sum of numbers from 1 to 20. | Bonus Challenge: Use a loop to calculate the sum of numbers from 1 to 20. | ||
=Lists= | |||
python | |||
<syntaxhighlight lang="python"> | |||
# Basic list and printing items | # Basic list and printing items | ||
favorite_foods = ["Pizza", "Burgers", "Ice Cream"] | favorite_foods = ["Pizza", "Burgers", "Ice Cream"] | ||
for food in favorite_foods: | for food in favorite_foods: | ||
print(food) | print(food) | ||
</syntaxhighlight> | |||
==Using append()== | |||
The append() method adds a single element to the end of a list. | |||
<syntaxhighlight lang="python"> | |||
my_list = [1, 2, 3] | |||
my_list.append(4) | |||
print(my_list) # Output: [1, 2, 3, 4] | |||
</syntaxhighlight> | |||
==Using insert()== | |||
The insert() method allows you to add an element at a specific index. | |||
<syntaxhighlight lang="python"> | |||
my_list = [1, 2, 3] | |||
my_list.insert(1, 1.5) # Insert 1.5 at index 1 | |||
print(my_list) # Output: [1, 1.5, 2, 3] | |||
</syntaxhighlight> | |||
==Using extend()== | |||
If you want to add multiple elements (from another list, for example), you can use the extend() method. | |||
<syntaxhighlight lang="python"> | |||
my_list = [1, 2, 3] | |||
my_list.extend([4, 5]) | |||
print(my_list) # Output: [1, 2, 3, 4, 5] | |||
</syntaxhighlight> | |||
==Using the + Operator== | |||
You can also combine lists using the + operator, but this creates a new list rather than modifying the original. | |||
<syntaxhighlight lang="python"> | |||
my_list = [1, 2, 3] | |||
my_list = my_list + [4] | |||
print(my_list) # Output: [1, 2, 3, 4] | |||
</syntaxhighlight> | |||
==Using * for Unpacking== | |||
If you're using Python 3.5 or later, you can use the unpacking operator * to add elements. | |||
<syntaxhighlight lang="python"> | |||
my_list = [1, 2, 3] | |||
my_list = [*my_list, 4] | |||
print(my_list) # Output: [1, 2, 3, 4] | |||
</syntaxhighlight> | |||
Task: Add a new food item to the list and print all items. | Task: Add a new food item to the list and print all items. | ||
| Line 115: | Line 170: | ||
Bonus Challenge: Create a list of numbers, find the maximum, minimum, and average of the list, and print each. | Bonus Challenge: Create a list of numbers, find the maximum, minimum, and average of the list, and print each. | ||
=Functions= | |||
python | |||
<syntaxhighlight lang="python"> | |||
# Basic function | # Basic function | ||
def greet(name): | def greet(name): | ||
print("Hello,", name, "!") | print("Hello,", name, "!") | ||
greet("Alice") | greet("Alice") | ||
</syntaxhighlight> | |||
Task: Write a function that calculates the square of a number and returns the result. | Task: Write a function that calculates the square of a number and returns the result. | ||
| Line 128: | Line 187: | ||
Bonus Challenge: Write a function that takes two numbers and returns their sum, difference, product, and quotient. | Bonus Challenge: Write a function that takes two numbers and returns their sum, difference, product, and quotient. | ||
=String Manipulation= | |||
python | |||
<syntaxhighlight lang="python"> | |||
# Convert string to uppercase | # Convert string to uppercase | ||
sentence = input("Enter a sentence: ") | sentence = input("Enter a sentence: ") | ||
print("Uppercase:", sentence.upper()) | print("Uppercase:", sentence.upper()) | ||
</syntaxhighlight> | |||
Task: Print the sentence in lowercase. | Task: Print the sentence in lowercase. | ||
Additional Challenge: Replace all spaces in the sentence with underscores. | Additional Challenge: Replace all spaces in the sentence with underscores using '''print("Modified sentence:", sentence.replace(" ", "_"))''' | ||
Latest revision as of 09:50, 27 October 2024
Printing Output
# Basic printing
print("Hello, World!")
Task: Modify the code to print a personal greeting like "Hello, [Your Name]!"
Additional Challenge: Ask the user for their name and greet them personally.
Bonus Challenge: Modify the program to greet two different names in separate lines.
Input from the User
# Basic input
name = input("Enter your name: ")
print(f"Hello {name}!")
Task: Ask the user for their age and print it.
Additional Challenge: Write a program that asks for the user’s birth year, calculates their age, and prints it.
Bonus Challenge: Modify the program to ask for the user’s favorite food and print, "Hello [name], who is [age] years old and loves [food]!"
Basic Math Operations
# Basic operations
print(5 + 3) # Addition
print(10 - 4) # Subtraction
print(7 * 6) # Multiplication
print(8 / 2) # Division
Task: Create a program that calculates the area of a rectangle (length * width).
Additional Challenge: Ask the user to input the rectangle’s length and width.
Bonus Challenge: Create a calculator that allows the user to choose the operation (addition, subtraction, etc.) they want to perform on two numbers.
Variables
# Storing and printing variables
name = "Alice"
favorite_number = 7
print(f"My name is {name} and my favorite number is {favorite_number}")
Task: Assign a new value to favorite_number and print it out.
Additional Challenge: Prompt the user for their favorite color, store it in a variable, and print a statement like "My favorite color is [color]."
Bonus Challenge: Write a small program that asks for the user’s name and age, then prints a statement with both.
Data Types
# Assigning different data types
my_string = "Hello"
my_integer = 25
my_float = 3.14
print("String:", my_string, type(my_string))
print("Integer:", my_integer, type(my_integer))
print("Float:", my_float, type(my_float))
Task: Create a new variable of type boolean (True/False) and print its type.
Additional Challenge: Write a program that uses an integer and a float and prints their sum.
Bonus Challenge: Ask the user to input a number and print its type.
Conditional Statements
# Basic conditional check
number = int(input("Enter a number: "))
if number > 0:
print("Positive number")
elif number < 0:
print("Negative number")
else:
print("Zero")
Task: Modify the program to check if the number is even or odd.
Additional Challenge: Write a program to check if the input number is divisible by 5.
Bonus Challenge: Add a check to see if the number is a multiple of both 2 and 3.
Loops
# Printing numbers from 1 to 10
for i in range(1, 11):
print(i)
Task: Print only even numbers from 1 to 10. try for i in range(0, 10, 2):
Additional Challenge: Write a loop to print numbers from 1 to 10 in reverse order. Try for i in range(10, 0, -1):
Bonus Challenge: Use a loop to calculate the sum of numbers from 1 to 20.
Lists
# Basic list and printing items
favorite_foods = ["Pizza", "Burgers", "Ice Cream"]
for food in favorite_foods:
print(food)
Using append()
The append() method adds a single element to the end of a list.
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
Using insert()
The insert() method allows you to add an element at a specific index.
my_list = [1, 2, 3]
my_list.insert(1, 1.5) # Insert 1.5 at index 1
print(my_list) # Output: [1, 1.5, 2, 3]
Using extend()
If you want to add multiple elements (from another list, for example), you can use the extend() method.
my_list = [1, 2, 3]
my_list.extend([4, 5])
print(my_list) # Output: [1, 2, 3, 4, 5]
Using the + Operator
You can also combine lists using the + operator, but this creates a new list rather than modifying the original.
my_list = [1, 2, 3]
my_list = my_list + [4]
print(my_list) # Output: [1, 2, 3, 4]
Using * for Unpacking
If you're using Python 3.5 or later, you can use the unpacking operator * to add elements.
my_list = [1, 2, 3]
my_list = [*my_list, 4]
print(my_list) # Output: [1, 2, 3, 4]
Task: Add a new food item to the list and print all items.
Additional Challenge: Write a program that asks the user for their top 3 favorite movies and stores them in a list.
Bonus Challenge: Create a list of numbers, find the maximum, minimum, and average of the list, and print each.
Functions
# Basic function
def greet(name):
print("Hello,", name, "!")
greet("Alice")
Task: Write a function that calculates the square of a number and returns the result.
Additional Challenge: Write a function to calculate the area of a triangle, given base and height.
Bonus Challenge: Write a function that takes two numbers and returns their sum, difference, product, and quotient.
String Manipulation
# Convert string to uppercase
sentence = input("Enter a sentence: ")
print("Uppercase:", sentence.upper())
Task: Print the sentence in lowercase.
Additional Challenge: Replace all spaces in the sentence with underscores using print("Modified sentence:", sentence.replace(" ", "_"))