0% found this document useful (0 votes)
16 views13 pages

Python Coding Basics: Variables & Data Types

This lesson introduces the fundamentals of coding in Python, covering key concepts such as variables, data types, keywords, and basic programming structures. It emphasizes Python's readability and versatility, making it suitable for various applications, and provides guidelines for naming variables and using operators. The lesson also includes examples of simple programs and explains the order of operations in Python.
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)
16 views13 pages

Python Coding Basics: Variables & Data Types

This lesson introduces the fundamentals of coding in Python, covering key concepts such as variables, data types, keywords, and basic programming structures. It emphasizes Python's readability and versatility, making it suitable for various applications, and provides guidelines for naming variables and using operators. The lesson also includes examples of simple programs and explains the order of operations in Python.
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

In this lesson, we will discuss the fundamentals of coding using Python.

We will explore
essential concepts like variables (labeled containers for storing values), data types
(categories of values like numbers and text), and how to name and work with variables
effectively. We will also learn about keywords (reserved words with special meanings),
common data types in Python, and how to write simple programs to display information
and take input from users. Additionally, we will cover arithmetic operators, the order of
operations, and the concept of operator precedence.

Introduction
You may be wondering why we are studying Python in this course. Python is renowned for
its readability, which makes it a great starting point. It is also versatile, allowing
programmers to create everything from web applications to data science projects. It also
has an extensive collection of libraries so you have access to tools for many tasks. At the
end of this lecture, you should be able to understand Python concepts like variables and
data types, and write simple programs that display output and even take input from the user.

● Why Python?
○ Easy to read and learn
○ Versatile (web, data science, scripting)
○ Large community and libraries

Python Introduction Created by Guido van Rossum


And released in 1991 Python has become one of the most
popular

Programming languages in the world Whether it’s powering web applications

Creating software Solving math problems


Or even automating the boring stuff on your With Python:
computer ● You can build web apps
● Automate tasks
● Manage big data
● Connect to databases

It’s truly a swiss army knife of programming So why Python?


● It works on almost any device
● From Windows PC to raspberry Pi

Its simple syntax means you can write less ● Easy to learn and use
code and do more - fast! ● Supports procedural, object-oriented
or functional programming
● Perfect for complex and quick
projects
And whether you prefer coding in a simple Python’s design focuses on readability
text editor, or a powerful IDE like PyCharm
or Eclipse, Python supports all.

It uses lines and spaces to organize code Unlike the curly brackets and semicolons
you see in many other languages

Goals of this Lecture

● Understand core Python concepts


● Write simple programs
Variables, Objects, and Data Types
Think of variables as containers with labels. You can use these labels to store values, which
we call objects. Every object has a type, which tells us what kind of value it holds. For
instance, we have numbers, text, and logical values (true or false).

● A value is one of the fundamental things, like a word or a number, that a program
manipulates.
● A variable is a name that refers to a value.
● Every variable in Python is an object. Objects are the actual data values.
● Objects are classified into data types.
● A data type describes what kind of value a variable holds (numbers, text, etc.)

Variable Names (Identifiers)


In Python, we have rules for naming our variables. They must start with a letter or an
underscore and can contain letters, numbers, and underscores. Remember, Python is
case-sensitive, so `myVar` and `myvar` are considered different. As a best practice, choose
descriptive names that reflect the purpose of the variable, and stick to lowercase letters
with underscores to separate words.

Rules:
● Start with a letter (a-z, A-Z) or underscore (_)
● Contain letters, numbers, and underscores
● Case-sensitive (`myVar` is different from `myvar`)

Best Practices:
● Use descriptive names (`age` instead of `x`)
● Use lowercase with underscores (`first_name`)

Keywords (Reserved Words)


Keywords are special words that have predefined meanings in Python. Examples include if,
else, for, and while. These words are reserved for specific actions, so you cannot use them
as variable names. We have to familiarize ourselves with keywords so we can prevent errors
as we start coding.

● Keywords define the language's syntax rules and structure.


● You cannot use them as variable names!
● You can see a list of Python 3 keywords and their description below. You will use
some of the keywords later when we move to other topics.

Python 3 Keywords
Keyword Description

False Boolean value representing falsity

None Represents the absence of a value

True Boolean value representing truth

and Logical AND operator

as Creates an alias for a module or exception

assert Used for debugging and testing

async Defines a coroutine function (asynchronous)

await Waits for a coroutine to complete

break Exits a loop prematurely

class Defines a new class

continue Skips the current iteration of a loop

def Defines a function

del Deletes an object or reference

elif Else if conditional statement

else The else part of an if-elif-else statement

except Handles exceptions

finally Code that always executes after a try-except block


for Iterates over a sequence

from Imports specific attributes from a module

global Indicates a variable is defined at the module level

if Conditional statement

import Imports a module

in Membership test operator (checks if a value is in a sequence)

is Identity test operator (checks if two objects are the same)

lambda Creates an anonymous function

nonlocal Indicates a variable is not local

not Logical NOT operator

or Logical OR operator

pass Empty statement, does nothing

raise Raises an exception

return Returns a value from a function

try Starts a block to catch exceptions

while Creates a loop that executes as long as a condition is true

with Context manager for resource management

yield Pauses and resumes generator functions


Common Data Types
Numbers:

Type Format Description

int a = 10 Signed Integer

long a = 345L (L) Long integers, they can also be represented in octal and
hexadecimal

float a= (.) Floating point real values


45.67

complex a= (J) Contains integer in the range 0 to 255.


3.14J

Strings:
● Strings in Python can be enclosed in either single quotes (') or double quotes (" - the
double quote character), or three of the same separate quote characters (''' or """).
● str: String of characters (e.g., "Hello", "Python")

Boolean:
● bool: Represents True or False values

You can find out the data type of a value by executing the following.
print(type("Hello, World!"))
print(type(17))

NOTES:

● Most of the time Python will do variable conversion automatically.


● You can also use Python conversion functions int(), long(), float(), complex() to
convert data from one type to another.
Sample Program
Let's look at a simple example. Here, we create variables called `name`, `age`, and `height`,
assigning them values of different types. Then, we use the `print` function to display these
values in a formatted way. Notice how we combine text and variables within the print
statement.

name = "Alice" # String variable


age = 30 # Integer variable
height = 1.65 # Float variable

print("My name is", name)


print("I am", age, "years old")
print("My height is", height, "meters")

● To execute the program, open a text editor, copy and paste the code and save the file
as
[Link]
● In your console (once you have installed Python), you can execute the ff:

python3 [Link]
● If you did not install Python in your computer, you can run it using an online
interpreter. Check this out: [Link]

Statements and Expressions


Statements are instructions that the Python interpreter can execute to perform some
actions. You've already seen the assignment statement, where we give values to variables,
and the print statement, which displays output. Expressions, on the other hand, are
combinations of values, variables, and operators that produce a result. This result can be a
number, text, or a logical value.

● Statements: Instructions that do something (e.g., assignment, printing)


● Expressions: Produce a value (e.g., 2 + 3, "Hello" + "World")
● An expression needs to be evaluated.
● The evaluation of an expression produces a value.
● A value or a variable all by itself is a simple expression.
Operators and Operands
Operators are symbols that act on values, known as operands. Think of them as the actions
you perform on your data. In Python, we have operators for arithmetic, comparisons, and
more. The operands are the values these operators work with.

● Operators: Symbols that perform operations (e.g., +, -, *, /)


● Operands: The values that operators work on (e.g., in 2 + 3, the operands are 2 and
3)

Python Arithmetic Operators


Here's a quick overview of common arithmetic operators in Python. We have addition (`+`),
subtraction (`-`), multiplication (`*`), and division (`/`). The double slash (`//`) performs floor
division, giving you the whole number result of a division. The percent sign (`%`) calculates
the remainder after division (modulo), and the double asterisk (`**`) raises a number to a
power.

Operator Meaning Example

+ Add two operands or unary plus x + y


+2

- Subtract right operand from the left or unary minus x - y


-2

* Multiply two operands x * y

/ Divide left operand by the right one (always results into float) x / y

// Floor division - division that results into whole number adjusted to x // y

the left in the number line

% Modulus - remainder of the division of left operand by the right x % y (remainder of x/y)

** Exponent - left operand raised to the power of right 2**3 (x ot the power y)
Input
Now, let's see how we can make our programs interactive. The input() function allows us to
take input from the user. By default, it takes input as a string, which we can store in a
variable. In this example, we ask for the user's name and then print a personalized greeting.

● input() function:
○ Gets input from the user
○ Returns the input as a string

name = input("Enter your name: ")


print("Hello,", name)

Check this: [Link]

NOTE: If you are using an online interpreter such as onecompiler, it's not really that
interactive as when you are using the command line. You have to input your input even
before you are asked for it.

Look:
Order of Operations
The order of evaluation of expressions depends on the rules of precedence.

Python's Rules of Precedence


● Parentheses have the highest precedence and can be used to force an expression to
evaluate it in the order you want.
● Exponentiation has the next highest precedence.
● Multiplication and both Division operators have the same precedence, which are
higher than addition and subtraction, which also have the same precedence.
● Operators with the same precedence are evaluated from left to right.

Operator Precedence Table


To see the full order of operations in Python, refer to this precedence table. It lists all the
operators and their relative priorities.

Order Operator Description

1 ** Exponentiation

2 +x, -x, ~x Unary plus, unary minus, bitwise NOT

3 *, /, //, % Multiplication, division, floor division,


modulus

4 +, - Addition, subtraction

5 <<, >> Bitwise left shift, bitwise right shift

6 & Bitwise AND

7 ^ Bitwise XOR

8 | Bitwise OR

9 in, not in, is, is not, <, <=, >, >=, !=, Comparisons, membership tests, identity
== tests

10 not, or, and Logical NOT, OR, AND


References
● Python Tutorial [Link]
● Python Operators [Link]
● Python Data Types
[Link]

You might also like