Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

Getting Started with Python

This document serves as an introduction to Python programming, covering basic concepts such as variables, data types, and simple math operations. It includes practical exercises for users to run their first Python program, work with user input, and implement conditional logic. The document also emphasizes the importance of clear variable naming and provides tips for writing comments in code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Getting Started with Python

This document serves as an introduction to Python programming, covering basic concepts such as variables, data types, and simple math operations. It includes practical exercises for users to run their first Python program, work with user input, and implement conditional logic. The document also emphasizes the importance of clear variable naming and provides tips for writing comments in code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Getting Started with Python

Part 1 - Introducing Python

Learning Objectives:

●​ Understand what Python is​

●​ Run your first Python program​

●​ Use print() and work with text and numbers​

●​ Do basic math in Python​

What is Python?
Python is a popular, beginner-friendly programming language used in web
development, data science, automation and more.

What is a Variable?

A variable is like a container or label that stores information. You give it a name,
and it holds a value.

age = 15
name = "Ali"

In this example:

●​ age is a variable holding a number​

●​ name is a variable holding text​

Prepared by Mr. Job T. Gumbs Eng.​ April 16th 2025


M.A.D. Scientist
1
Common Types of Variables in Python

Python automatically knows what type of value you're storing. Here are the most
common types:

Type Example Description

int 10, -5 Integer (whole number)

float 3.14, 2.0 Decimal number

str "Hello" String (text)

bool True, False Boolean (true or false values)

🧪 Example:
name = "Sara" # str
age = 13 # int
height = 1.55 # float
is_student = True # bool

You can check a variable's type using the type() function:

print(type(name)) # Output: <class 'str'>

Quick Tips:

●​ Variable names should be clear (user_name, not x)​

●​ Don't use spaces or special characters in names​

●​ Python is case-sensitive (Age and age are different)

Prepared by Mr. Job T. Gumbs Eng.​ April 16th 2025


M.A.D. Scientist
2
🔸 Your First Python Program
Okay so go to www.online-python.com

print("Hello, world!")

Notice that the word print is placed in a particular colour as it is a Python key word.
("Hello, world!") is a string so it is in quotation marks “”. We use parentheses because
print is a function. A function is like a command that does something. When you use a
function, you call it with parentheses () — and you can pass information into it.

🗣️ This command prints a message to the screen.

🛠️ Exercise 1: Modify the Message


Change "Hello, world!" to something else, like your name.

print("My name is Job, M.A.D. Scientist")

M.A.D. stands for Machines | Automation | Data

Now that we can print letters and words, lets get into printing numbers.

🔸 Printing Numbers
print(42)
print(3.14)

You can print whole numbers (integers) and decimal numbers (floats).

🔸 Doing Math
Python can do basic math just like a calculator:

Prepared by Mr. Job T. Gumbs Eng.​ April 16th 2025


M.A.D. Scientist
3
print(5 + 3) addition
print(10 - 2) subtraction
print(4 * 2) multiplication
print(8 / 2) division

🛠️ Exercise 2: Simple Math Practice


Try these on your own:

●​ Add 12 and 8​

●​ Subtract 15 from 30​

●​ Multiply 7 by 6​

●​ Divide 25 by 5​

Part 2 – Variables and Input

Learning Objectives:

●​ Store information using variables​

●​ Get input from the user​

●​ Combine input and output​

🔸 What is a Variable
A variable is like a container or label that stores information.

You give it a name, and it holds a value.

age = 15
name = "Ali"

Prepared by Mr. Job T. Gumbs Eng.​ April 16th 2025


M.A.D. Scientist
4
In this example:

●​ age is a variable holding a number​

●​ name is a variable holding text​

Common Types of Variables in Python

Python automatically knows what type of value you're storing. Here are the most
common types:

Type Example Description

int 10, -5 Integer (whole number)

float 3.14, 2.0 Decimal number

str "Hello" String (text)

bool True, False Boolean (true or false values)

🧪 Example:
name = "Sara" # str
age = 13 # int
height = 1.55 # float
is_student = True # bool

You can check a variable's type using the type() function:

print(type(name)) # Output: <class 'str'>

Quick Tips:

●​ Variable names should be clear (user_name, not x)


●​ Don't use spaces or special characters in names
●​ Python is case-sensitive (Age and age are different)
Prepared by Mr. Job T. Gumbs Eng.​ April 16th 2025
M.A.D. Scientist
5
Now let us think about applications for text and variables. We can use text and variables
to get user input in Python. This makes your programs interactive and personalized.
Here are some real-life applications where getting user input is essential:

🔸 A. User Login or Sign-Up Forms


Ask the user for a username and password to log in or create an account.

username = input("Enter username: ")


password = input("Enter password: ")
print("Welcome,", username)

🔸 B. Simple Calculators
Let users input numbers to perform math operations.

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))
print("The sum is", num1 + num2)

🧠 Used in: Finance apps, educational tools, engineering software.

🔸 C. Quizzes and Games


Ask the user questions and give feedback based on answers.

answer = input("What is 5 + 3? ")


if answer == "8":
print("Correct!")
else:
print("Try again.")

🧠 Used in: Educational games, trivia apps, tests.


Prepared by Mr. Job T. Gumbs Eng.​ April 16th 2025
M.A.D. Scientist
6
🔸 D. Chatbots and Virtual Assistants
Take input from the user and respond accordingly.

name = input("Hi! What's your name? ")


print("Nice to meet you,", name)

🧠 Used in: Customer service, personal assistants (like Siri, Alexa).

🔸 E. Decision-Making Programs
Ask questions and give different outputs based on input.

age = int(input("How old are you? "))


if age >= 17:
print("You can drive!")
else:
print("You are too young to drive.")

🧠 Used in: Government forms, recommendation tools, surveys.

🔸 F. Personalized Stories or Mad Libs


Use input to fill in parts of a story.

name = input("Enter a name: ")


place = input("Enter a place: ")
print(name, "went on an adventure to", place)

🧠 Used in: Creative writing tools, learning games.

🔸 G. Menus and Options


Let users choose actions in your program.

Prepared by Mr. Job T. Gumbs Eng.​ April 16th 2025


M.A.D. Scientist
7
print("1. Say Hello")
print("2. Say Goodbye")
choice = input("Choose an option: ")

if choice == "1":
print("Hello!")
elif choice == "2":
print("Goodbye!")

🧠 Used in: Any app or game that needs menus.


So we just introduced something new; if, else, and elif (which means "else if") in Python.
In class 3 we shall explain in more detail but here is a quick explanation.

🔹 if – the first condition


It checks if something is true. If it is, it runs the code under it.

age = 18

if age == 18:

print("You are 18!")

🔸 elif – short for “else if”


If the if condition was false, Python checks the elif.​
You can have many elif blocks.

age = 16

if age == 18:

print("You are 18!")

elif age == 16:

Prepared by Mr. Job T. Gumbs Eng.​ April 16th 2025


M.A.D. Scientist
8
print("You are 16!")

🔻 else – the fallback


If none of the if or elif conditions are true, else runs as the final option.

age = 14

if age == 18:

print("You are 18!")

elif age == 16:

print("You are 16!")

else:

print("You are not 16 or 18")

🧪 Example to try:
color = input("Enter a color: ")

if color == "red":

print("Stop!")

elif color == "green":

print("Go!")

else:

print("Color not recognized.")

Prepared by Mr. Job T. Gumbs Eng.​ April 16th 2025


M.A.D. Scientist
9
🛠️ Exercise 3: Your Own Introduction
Create variables for your name, age, and favorite color, then print them all.

🔸 Getting User Input


name = input("What is your name? ")
print("Hello,", name)

🛠️ Exercise 4: Interactive Profile


Ask the user for:

●​ Their name​

●​ Favorite food​

●​ Favorite animal​

Then print a fun sentence using all three!​

Example:

name = input("What is your name? ")


food = input("What is your favorite food? ")
animal = input("What is your favorite animal? ")

print(name, "likes eating", food, "with a", animal)

Prepared by Mr. Job T. Gumbs Eng.​ April 16th 2025


M.A.D. Scientist
10
Part 3 – Conditions and Logic

🧠 Learning Objectives:
●​ Use if statements to make decisions​

●​ Understand comparison operators (==, >, <, !=)​

●​ Make simple programs that respond to input​

Here's another explanation for if, else, and elif (which means "else if") in Python.

🔹 if – the first condition


It checks if something is true. If it is, it runs the code under it.

age = 18

if age == 18:

print("You are 18!")

🔸 elif – short for “else if”


If the if condition was false, Python checks the elif.​
You can have many elif blocks.

age = 16

if age == 18:

print("You are 18!")

elif age == 16:

print("You are 16!")

Prepared by Mr. Job T. Gumbs Eng.​ April 16th 2025


M.A.D. Scientist
11
🔻 else – the fallback
If none of the if or elif conditions are true, else runs as the final option.

age = 14

if age == 18:

print("You are 18!")

elif age == 16:

print("You are 16!")

else:

print("You are not 16 or 18")

🧪 Example to try:
color = input("Enter a color: ")

if color == "red":

print("Stop!")

elif color == "green":

print("Go!")

else:

print("Color not recognized.")

Prepared by Mr. Job T. Gumbs Eng.​ April 16th 2025


M.A.D. Scientist
12
Here is the “Guess the Number Game” we used;

import random

# Generate a random number between 1 and 100

secret_number = random.randint(1, 100)

# Welcome message

print(" 🎉 Welcome to 'Guess the Number'!")


print("I'm thinking of a number between 1 and 100.")

# Ask the player to guess

guess = int(input("Take a guess: "))

# Check if the guess is correct

if guess == secret_number:

print(" 🎯 You got it! Great job!")


else:

print(" ❌ Nope! The number was", secret_number)

How it works:
1.​ The program randomly chooses a number between 1 and 10.​

2.​ It asks the user to guess the number.​

3.​ It checks if the guess is correct and responds.​

Prepared by Mr. Job T. Gumbs Eng.​ April 16th 2025


M.A.D. Scientist
13
Here is the version of the game which we used during class. In this version we added a
“While True” loop

import random

# Generate a random number between 1 and 100

secret_number = random.randint(1, 100)

print(" 🎉 Welcome to 'Guess the Number'!")


print("I'm thinking of a number between 1 and 100.")

# Keep asking until the player gets it right

while True:

guess = int(input("Take a guess: "))

if guess < secret_number:

print("Too low. Try again!")

elif guess > secret_number:

print("Too high. Try again!")

else:

print(" 🎯 You got it! Well done!")


break # Exit the loop

Prepared by Mr. Job T. Gumbs Eng.​ April 16th 2025


M.A.D. Scientist
14
How It Works:

●​ The while True: loop keeps running forever — until the player guesses
correctly.​

●​ The break statement stops the loop when the guess is correct.​

●​ The game gives feedback if the guess is too high or too low.​

🛠️ Exercise 5: Voting Age Check


Ask the user their age, then tell them if they can vote (age 18+).

age = int(input("Enter your age: "))

if age >= 18:


print("You can vote!")
else:
print("You are too young to vote.")

🔸 Comparison Operators Cheat Sheet:


Operator Meaning

== equal to

!= not equal to

> greater than

< less than

>= greater or equal

<= less or equal

Prepared by Mr. Job T. Gumbs Eng.​ April 16th 2025


M.A.D. Scientist
15
🛠️ Final Exercise: Mini Quiz Game
answer = input("What is the capital of France? ")

if answer == "Paris":

print("Correct!")

else:

print("Oops! The answer is Paris.")

🧠 Bonus: Add more questions and keep score! As you practice more and
more you can turn this into a fun trivia game.

Rules for Naming Integers (Variables):

1. Names must start with a letter or an underscore (_)


age = 10
_score = 25

❌ Not allowed:
1score = 25 # ❌ Starts with a number

2. Names can include letters, numbers, and underscores


player1_score = 100
total2 = 45

3. No spaces allowed

Use underscores _ to separate words.

Prepared by Mr. Job T. Gumbs Eng.​ April 16th 2025


M.A.D. Scientist
16
✅ car_speed​
❌ car speed (this will cause an error)
4. No special characters like !, @, $, %, etc.
$score = 50 # ❌ Not allowed

5. Don’t use Python keywords

Words like if, else, print, input, etc., are reserved by Python and can’t be used as variable
names.

❌ print = 20​
✅ my_print = 20
6. Names are case-sensitive
score = 10
Score = 20

These are two different variables in Python.

Bonus Tips 💡:
✅ ❌
●​ Choose names that make sense:​
age = 15 is better than a = 15​

●​ Keep it short, but clear.

How to Write a Comment

Comments are notes we put in so that when we look at the code in the future, we can
follow along easily. Use the # symbol to start a comment:
Prepared by Mr. Job T. Gumbs Eng.​ April 16th 2025
M.A.D. Scientist
17
# This is a comment
print("Hello") # This prints Hello to the screen

Python ignores anything after the # on that line.

🧠 Why Use Comments?


●​ To explain what your code does​

●​ To leave reminders for yourself or others​

●​ To temporarily turn off a line of code (for testing)​

# print("This line is turned off")


print("This line runs")

Comments are not required, but they're very helpful for writing clean,
understandable code — especially as your programs get bigger!

What is Casting?

Casting means converting one data type into another.​


In Python, you can convert (or "cast") between types like:

●​ int() → to convert to an integer​

●​ str() → to convert to a string​

●​ float() → to convert to a decimal (float)​

Casting a String to an Integer

Sometimes, user input comes in as a string, even if it's a number:

Prepared by Mr. Job T. Gumbs Eng.​ April 16th 2025


M.A.D. Scientist
18
age = input("Enter your age: ") # age is a string!

To do math with it, you need to cast it to an integer:

age = int(input("Enter your age: "))


print(age + 5) # Now this works!

⚠️ Important:
The string must actually look like a number, or you'll get an error:


# This works:
int("25") #


# This will crash:
int("hello") # Error!

🧪 Example:
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")

# Convert both to integers before adding


sum = int(num1) + int(num2)
print("The sum is", sum)

The type() Function in Python

The type() function in Python tells you the data type of a value or variable.

F = 7.3 + 4
print(type(F))

🔍 What happens here:


F = 7.3 + 4 adds a float (7.3) and an integer (4) → result is a float: 11.3
Prepared by Mr. Job T. Gumbs Eng.​ April 16th 2025
M.A.D. Scientist
19
type(F) returns <class 'float'>

So it prints:

<class 'float'>

🧠 Quick Tip:
Adding an int and a float always gives a float

type() helps you check what kind of value a variable holds

Summary & Wrap-Up


In just 3 classes, you’ve learned:

●​ How to print and do math​

●​ Use variables and get input​

●​ Make decisions using if statements​

🧪 Optional Homework:
Create a short program that:

1.​ Asks the user for their age​

2.​ Asks for their favorite hobby​

3.​ If they’re under 18, prints: “Keep having fun with [hobby]!”​

4.​ If they’re 18 or older, prints: “Nice! Hope you still enjoy [hobby]!”

Prepared by Mr. Job T. Gumbs Eng.​ April 16th 2025


M.A.D. Scientist
20

You might also like