Python is a high-level, interpreted programming language known for its readability and simplicity. It’s widely used in various domains such as web development, data analysis, artificial intelligence, scientific computing, and more. Python’s syntax is easy to learn, and its code is often more concise compared to other programming languages.
input
functionThonny is an integrated development environment (IDE) specifically designed for beginners in Python programming. It comes with a simple interface and provides features that make learning Python easier.
The first program every programmer writes is a “Hello, World!” program. Let’s start with that in Thonny.
File
menu in the top left corner.New
to create a new file. This will open a new, empty editor window.In the new file, type the following line of code:
print("Hello, World!")
File
menu again.Save As...
.hello_world.py
and click Save
.F5
.You should see the output Hello, World!
in the shell window at the bottom.
print()
functionThe print()
function is used to output data to the standard output device (screen).
You can print text (strings) by enclosing them in single quotes ('
) or double quotes ("
):
print("Bridges to Computing Summer Camp!")
print('Happy to see you!')
print("This is track 3:", "Advanced level track")
Write a Python program introduce_yourself.py
that prints an introduction message including:
:bulb: Tip: You will save yourself some trouble during this camp if you get into the habit of organizing your Python files and other related files into a specific folder, named as
JMUcamp2024
.
My name is Bob.
I am a computer science student with a passion for coding.
I am attending this camp to learn more about computer science related skills.
Variables are used to store data. In Python, you don’t need to declare the type of a variable. Python is dynamically typed, meaning it infers the type based on the value assigned.
# Integer
age = 25
# Float
height = 5.9
# String
name = "Alice"
# Boolean
is_student = True
Numeric operators are used to perform operations on numbers. Here are the main numeric operators available in Python:
+
(Addition)-
(Subtraction)*
(Multiplication)/
(Division)%
(Modulus)**
(Exponentiation)//
(Floor Division)a = 1
b = 5
print(a + b) # Output: 15
print(a - b) # Output: 5
print(a * b) # Output: 50
print(a / b) # Output: 2.0
print(a % b) # Output: 0
print(a ** b) # Output: 100000
print(a // b) # Output: 2
Strings and lists are fundamental data types in Python. Understanding how to work with them will help you write more complex and powerful Python programs.
In Python, a string is a sequence of characters enclosed within either single quotes ('
) or double quotes ("
).
You can create a string by assigning a value to a variable:
text = "Hello, World!"
You can access individual characters in a string using indexing:
print(text[0]) # Output: H
print(text[7]) # Output: W
You can extract a substring from a string using slicing:
print(my_string[1:5]) # Output: ello
print(my_string[:5]) # Output: Hello
print(my_string[7:]) # Output: World!
You can concatenate two or more strings using the +
operator:
greeting = "Hello"
name = "Bob"
text = greeting + ", " + name + "!"
print(text) # Output: Hello, Bob!
A list in Python is a collection of items separated by commas and enclosed within square brackets ([]
).
You can create a list by assigning a sequence of values to a variable:
my_list = [1, 2, 3, 4, 5]
You can access individual elements in a list using indexings and ou slice a list to extract a sublist, similar to strings:
print(my_list[0]) # Output: 1
print(my_list[2]) # Output: 3
print(my_list[1:4]) # Output: [2, 3, 4]
print(my_list[:3]) # Output: [1, 2, 3]
print(my_list[2:]) # Output: [3, 4, 5]
In Python, there are several built-in functions that you can use with lists to perform common operations. Here are some of the most commonly used functions:
len()
: Get the length of a list.# example of len()
my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print(length) # Output: 5
sum()
: Sum all elements in a list (works only for numeric lists).# example of sum()
my_list = [1, 2, 3, 4, 5]
total = sum(my_list)
print(total) # Output: 15
my_list = [1, 2, 3, 4, 5]
# min(): Find the smallest element in a list.
smallest = min(my_list)
print(smallest) # Output: 3
# max(): Find the largest element in a list.
largest = max(my_list)
print(largest) # Output: 12
# sorted(): Return a new sorted list from the elements of a list.
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_list = sorted(my_list)
print(sorted_list) # Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
list.append(x)
: Adds an item x
to the end of the list.list.remove(x)
: Removes the first item from the list whose value is x
.list.clear()
: Removes all items from the list.# append
fruits = ['apple', 'banana', 'cherry']
fruits.append('orange')
print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']
# remove
fruits = ['apple', 'banana', 'cherry']
fruits.remove('banana')
print(fruits) # Output: ['apple', 'cherry']
# clear
fruits = ['apple', 'banana', 'cherry']
fruits.clear()
print(fruits) # Output: []
:bulb: Tip: In Python, functions are independent, reusable pieces of code that can be called with or without an object. Methods are functions that are associated with an object and are called on that object.
You have a list of grades for a student as below.
# List of grades
grades = [85.1, 90, 92, 88.9, 95]
Write a python program average_grade.py
to alculate the average grade. Print the result.
Average grade: 90.2
==
(Equal)!=
(Not equal)>
(Greater than)<
(Less than)>=
(Greater than or equal to)<=
(Less than or equal to)a = 10
b = 5
print(a == b) # Output: False
print(a != b) # Output: True
print(a > b) # Output: True
print(a < b) # Output: False
print(a >= b) # Output: True
print(a <= b) # Output: False
Control structures allow you to control the flow of your program. The most common ones are if statements and loops (for
and while
).
In Python, comparison operators are used to compare two values. They result in either True
or False
based on the comparison result. Here are the main comparison operators in Python:
==
(Equal)!=
(Not equal)>
(Greater than)<
(Less than)>=
(Greater than or equal to)<=
(Less than or equal to)a = 10
b = 5
print(a == b) # Output: False
print(a != b) # Output: True
print(a > b) # Output: True
print(a < b) # Output: False
print(a >= b) # Output: True
print(a <= b) # Output: False
if
Statement:
The if statement allows you to execute a block of code only if a condition is true.
temperature = 86 # Set the temperature
# Check if the temperature is greater than 90
if temperature > 90:
print("It's hot outside. Let's eat in King Hall.")
else:
print("The weather is nice. Let's eat outside of King Hall.")
You can also have elif
(else if) statements to check multiple conditions.
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")
for
Loop:
The for
loop is used for iterating over a sequence (e.g., a list, tuple, dictionary, set, or string).
Iterate over a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
while
Loop:
We can also use the while
loop to iterate over a sequence.
fruits = ["apple", "banana", "cherry"]
i = 0
while i < len(fruits):
print(fruits[i])
i = i + 1
Write a Python program identify_even_odd.py
, which takes a list of numbers(below) as input to find out the even and the odd numbers.
:bulb: Tip: To determine if a value is even or odd in Python, you can use the modulus operator
%
. This operator returns the remainder of a division operation. If a number divided by 2 has a remainder of 0, it is even; otherwise, it is odd.
# the list as input
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Even: [2, 4, 6, 8, 10]
Odd: [1, 3, 5, 7, 9]
Functions are reusable blocks of code that perform a specific task.
Use the def
keyword to define a function.
# define a function
def greet(name):
print("Hello,", name)
print("Welcome to Bridges to Computing Camp at JMU")
# use (invoke, or call) the function
greet("Bob")
# Output:
# Hello, Bob
# Welcome to Bridges to Computing Camp at JMU
Functions can return a value using the return statement.
# define a function
def add(a, b):
s = a + b
return s
# use (invoke, or call) the function
c = add(1 + 2)
print(c) # Output: 3
input()
functionThe input()
function in Python allows you to take user input from the console. The function reads a line from the input, converts it into a string, and returns it.
name = input("Enter your name: ")
print("Hello,", name)
This code will display the message “Enter your name: “ and wait for the user to type something. Once the user presses Enter, it captures the input as a string and stores it in the variable name, then prints a greeting.
By default, input()
returns the entered data as a string. To use the input as a different data type, you need to convert it.
a = int(input("Enter first Integer: "))
b = int(input("Enter second Integer: "))
print("a + b =", a + b)
The output will be
Enter first Integer: 10
Enter second Integer: 12
a + b = 22
Write a Python program named sequence_input.py
which should implement the following steps:
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: done
The sum of the entered numbers is: 10
The average of the entered numbers is: 2.5
The minimum of the entered numbers is: 1
The maximum of the entered numbers is: 4
Here’s a step-by-step guide to building a simple Dice Rolling Simulator in Python for beginners. This project will help you practice basic programming concepts such as loops, conditionals, functions, and user input.
random
moduleThis module contains the randint
function which will be used to generate random numbers.
import random
randint
methodThe randint
method in Python is part of the random
module, and it is used to generate random integers within a specified range.
Here’s how you can use it:
import random
# example 1: Simulating the roll of a six-sided dice,
# where the possible outcomes are between 1(inclusive) and 6(inclusive).
dice_roll = random.randint(1, 6)
print("You rolled a ", dice_roll)
# example 2: Generating a Random Number Between 10 and 20
random_number = random.randint(10, 20)
print("Random number between 10 and 20: ",random_number)
Here’s the complete code. Copy and paste the code below into your Thonny IDE, then run it.
import random
print("====Welcome====")
signal = 'yes'
# The while True loop ensures the program keeps running until the user decides to stop.
while signal == 'yes':
# Roll the dice and the result of roll_dice is printed.
dice_result = random.randint(1, 6)
print("You rolled a ", dice_result)
# The user is prompted to decide if they want to roll again. If the user inputs anything other than 'yes', the loop breaks, and the program ends.
signal = input("Do you want to roll again? (yes/no): ")
if signal != 'yes':
print("Thank you for playing!")
:bulb: Tip: Use a while
loop when the number of iterations is not known beforehand and depends on some condition.
Use a for
loop when you need to iterate over a sequence of elements or a fixed number of iterations.
There are various ways to enhance the dice rolling simulator, providing more interaction and features for the user. Feel free to modify and expand these examples to suit your needs!
Before writing your code, discuss your ideas with TAs or professors. Don’t hesitate to ask for help if you have any questions.