Introduction to Python Programming

A simple, book-style learning guide for Python programming fundamentals

Chapter Overview

Main idea: This chapter moves from simply evaluating Python expressions to writing small programs that store data, display information, accept user input, make decisions, and work with objects and basic statistics.
Variables
Store values so you can use them later.
Arithmetic
Use Python operators for calculations.
Strings & print
Display text and work with quoted strings.
User input
Read keyboard input and convert it when needed.
Decision making
Use comparisons and if to choose what runs.
Objects & dynamic typing
Understand values, types and variable references.
Descriptive statistics
Find minimum, maximum and range in data.
Python style
Write code that is easier to read and maintain.

Topics in This Guide

  1. Introduction
  2. Variables and Assignment Statements
  3. Arithmetic
  4. print and Single-/Double-Quoted Strings
  5. Triple-Quoted Strings
  6. Getting Input from the User
  7. Decision Making: if and Comparison Operators
  8. Objects and Dynamic Typing
  9. Basic Descriptive Statistics
  10. Wrap-Up and Revision

Introduction

The source chapter assumes that you have already used IPython as a calculator. Now the focus changes: instead of only evaluating expressions, you start writing actual Python statements and small scripts.

ExpressionVariableInputDecisionProgram
Remember: The chapter is a fundamentals chapter. The goal is to understand how Python statements work and how small pieces combine into a program.

Variables and Assignment Statements

A variable is a name that refers to a value/object. You create or change a variable with the assignment symbol =.

Creating variables

x = 7
y = 3
x + y
10

The statements x = 7 and y = 3 store values for later use.

Calculations in an assignment

total = x + y
total
10

Python evaluates the right-hand side first and then assigns the result to the name on the left.

Important: Read = as "is assigned". It is different from ==, which asks whether two values are equal.

Variable names

Python variable names may contain letters, digits and underscores, but they cannot begin with a digit. Python is case-sensitive, so number and Number are different names.

student_name = "Aman"
age2 = 20
# 2age = 20   # invalid: starts with a digit

Types

Every Python value has a type. The built-in type() function lets you inspect it.

type(7)
type(10.5)
int float
Good style: Put spaces around assignment and binary operators, for example total = x + y. Clear formatting makes code easier to read.

Arithmetic

Python provides familiar arithmetic operators plus operators that are especially useful in programming.

OperationOperatorExampleMeaning
Addition+7 + 3Add two values
Subtraction-7 - 3Subtract the right value
Multiplication*7 * 3Multiply values
Exponentiation**2 ** 10Raise a value to a power
True division/7 / 4Division producing a floating-point result
Floor division//7 // 4Largest integer not greater than the result
Remainder%17 % 5Remainder after division

Exponentiation and square roots

2 ** 10
9 ** (1 / 2)
1024 3.0

A square root can be expressed as raising a number to the power 1/2.

True division vs. floor division

7 / 4
7 // 4
-13 / 4
-13 // 4
1.75 1 -3.25 -4
Easy way to remember: / gives the normal division result. // gives the floor of the result. With negative numbers, floor means moving to the next smaller integer, so -13 // 4 is -4.

Remainder operator

17 % 5
7.5 % 3.5
2 0.5

The remainder operator is commonly useful when checking divisibility, such as finding whether a number is even.

8 % 2
9 % 2
0 1

Straight-line form

Programming expressions are written in a horizontal, straight-line form. For example, a fraction is written using / or //.

Parentheses

10 * (5 + 3)
10 * 5 + 3
80 53

Parentheses can force part of an expression to be evaluated first and can make the intended calculation clearer.

Operator precedence

PriorityOperatorsGrouping
Highest()Inside parentheses first
Next**Right to left
Next* / // %Left to right
Lowest among these arithmetic operators+ -Left to right
2 + 3 * 4
(2 + 3) * 4
14 20
Tip: If an expression is complicated, use parentheses or split it into smaller statements. Readability is often more important than saving one line of code.

Exceptions and tracebacks

Some operations cannot be completed. For example, division by zero raises ZeroDivisionError.

123 / 0
ZeroDivisionError: division by zero

Using a variable that has not been defined can raise NameError.

z + 7
NameError: name 'z' is not defined
Remember: A traceback is Python's way of giving information about an error. Do not panic when you see one—read the final error type and message first.

Function print and Single-/Double-Quoted Strings

The built-in print() function displays text or values.

print('Welcome to Python!')
print("Welcome to Python!")
Welcome to Python! Welcome to Python!

A string is a sequence of characters. You can normally delimit it with single quotes or double quotes.

Printing several values

print('Welcome', 'to', 'Python!')
Welcome to Python!

When multiple arguments are passed to print, Python separates them with spaces by default.

Escape sequences

SequencePurposeExample
\nNew lineprint('A\nB')
\tHorizontal tabprint('A\tB')
\\Backslash characterprint('C:\\Temp')
\"Double quote inside a double-quoted stringprint("Say \"Hi\"")
\'Single quote inside a single-quoted stringprint('It\'s Python')
print('Welcome\nto\nPython!')
Welcome to Python!

Long strings

A long string can be continued onto another source line using the continuation character \. The source chapter also notes that parentheses are the preferred way to break long code lines when possible.

print('This is a long message that is '
      'split into two strings.')
This is a long message that is split into two strings.

Printing an expression

print('Sum is', 7 + 3)
Sum is 10

Triple-Quoted Strings

Triple-quoted strings use either ''' or """. The source chapter recommends three double quotes in its style guidance.

Multiline text
Store text that spans several source lines.
Embedded quotes
Include both single and double quote characters more conveniently.
Docstrings
Document the purpose of program components.
message = """This is a string
that spans two lines."""
print(message)
This is a string that spans two lines.

Internally, a multiline string contains newline characters where the source lines were separated.

Including both kinds of quotes

print("""Display "hi" and 'bye' in quotes""")
Display "hi" and 'bye' in quotes
Common mistake: If you put an unescaped single quote inside a single-quoted string, Python may think the string ended early and report a SyntaxError. You can escape the quote or choose a different string delimiter.

Getting Input from the User

The built-in input() function displays a prompt and waits for the user to type something. The important point is that input() always returns a string.

name = input("What's your name? ")
print(name)
What's your name? Paul Paul

Why numeric input can surprise beginners

value1 = input('Enter first number: ')
value2 = input('Enter second number: ')
print(value1 + value2)

If the user enters 7 and 3, the values are strings, so + concatenates them.

73

This is string concatenation: the second string is placed after the first string.

Convert input to an integer

value = int(input('Enter an integer: '))
another_value = int(input('Enter another integer: '))
print(value + another_value)
Enter an integer: 7 Enter another integer: 13 20

Convert to floating-point

price = float(input('Enter price: '))

Use float() when the input may contain a decimal value.

Conversion errors

If text cannot be converted to the requested numeric type, Python raises an exception such as ValueError.

int('hello')
ValueError: invalid literal for int()
Remember: input() → string. If you need a number, explicitly convert it with int() or float().

Decision Making: The if Statement and Comparison Operators

A condition is a Boolean expression that evaluates to either True or False.

7 > 4
7 < 4
True False

Comparison operators

OperatorMeaningExample
>greater thanx > y
<less thanx < y
>=greater than or equal tox >= y
<=less than or equal tox <= y
==equal tox == y
!=not equal tox != y

Basic if syntax

if number1 == number2:
    print('The numbers are equal')

The structure is:

ifcondition:indented suite
Two very common mistakes:
1. Forgetting the colon after the condition.
2. Writing = when you mean ==. Read = as "assigned" and == as "is equal to".

Comparing two integers

number1 = int(input('Enter first integer: '))
number2 = int(input('Enter second integer: '))

if number1 == number2:
    print(number1, 'is equal to', number2)

if number1 != number2:
    print(number1, 'is not equal to', number2)

if number1 < number2:
    print(number1, 'is less than', number2)

if number1 > number2:
    print(number1, 'is greater than', number2)

if number1 <= number2:
    print(number1, 'is less than or equal to', number2)

if number1 >= number2:
    print(number1, 'is greater than or equal to', number2)
Enter first integer: 37 Enter second integer: 42 37 is not equal to 42 37 is less than 42 37 is less than or equal to 42

Comments, docstrings and whitespace

A comment starts with # and is ignored by Python.

# This comment explains the next statement
age = 20

The source chapter also introduces a script-level docstring to describe a program's purpose:

"""Compare two integers using if statements."""

Blank lines and spaces make code easier to read. Indentation is different: indentation is part of Python's syntax for an if suite.

Chaining comparisons

Python allows comparisons such as:

x = 3
1 <= x <= 5
True

This is a convenient way to ask whether a value lies within a range.

Splitting a long statement

Long statements can be split across lines. The source chapter notes that using parentheses to break long lines is preferred when practical.

print('Enter two integers, and I will tell you',
      'the relationships they satisfy.')

Objects and Dynamic Typing

Python values such as 7, 4.1 and 'dog' are objects. Every object has a type and a value.

ValueType
7int
4.1float
'dog'str

Variables refer to objects

When you assign an object to a variable, the variable name becomes associated with that object.

x = 7
x + 10
17

Dynamic typing

Python uses dynamic typing. The type is associated with the object a variable currently refers to; the same variable name can later refer to an object of another type.

x = 7
print(type(x))

x = 4.1
print(type(x))

x = 'dog'
print(type(x))
<class 'int'> <class 'float'> <class 'str'>
Easy mental model: The variable is a name/reference; the object is the actual value with a type. Reassigning the variable changes which object it refers to.

Garbage collection

Python creates objects in memory and automatically removes objects that are no longer needed. This automatic memory cleanup is called garbage collection.

Why it matters: You normally do not need to manually free every object. Python helps manage memory automatically.

Operator precedence so far

OrderOperators
1()
2**
3* / // %
4+ -
5> <= < >=
6== !=

Intro to Data Science: Basic Descriptive Statistics

Data science often begins by getting to know the data. Descriptive statistics provide simple ways to summarize a collection of values.

Minimum
The smallest value.
Maximum
The largest value.
Range
The span from minimum to maximum.
Count
The number of values in the collection.
Sum
The total of the values.
Later topics
Mean, median, mode, variance and standard deviation are developed in later chapters.

Finding the minimum manually

The chapter demonstrates a simple algorithm for three values:

  1. Assume the first value is the smallest.
  2. Compare the second value with the current minimum. Replace the minimum if needed.
  3. Compare the third value with the current minimum. Replace it if needed.
  4. Display the final minimum.
number1 = int(input('Enter first integer: '))
number2 = int(input('Enter second integer: '))
number3 = int(input('Enter third integer: '))

minimum = number1

if number2 < minimum:
    minimum = number2

if number3 < minimum:
    minimum = number3

print('Minimum value is', minimum)
Enter first integer: 27 Enter second integer: 12 Enter third integer: 36 Minimum value is 12

Using built-in min() and max()

Python already provides built-in functions for common tasks.

min(36, 27, 12)
max(36, 27, 12)
12 36

Range

For the values 36, 27, 12, the minimum is 12 and the maximum is 36, so the range extends from 12 through 36.

Data-science lesson: A range gives a quick picture of the span of values, but it does not tell you how the values are distributed inside that span.

Reduction

The source introduces reduction as a functional-style programming idea: many values are reduced to one result. min() and max() are examples. Other reductions encountered later include sum, average, variance and standard deviation.

Many valuesReductionOne result

Wrap-Up

This chapter builds the first practical layer of Python programming. You move from calculator-style expressions to small programs that can store, display, receive, compare and summarize data.

What you should know now

  • Create variables with assignment statements.
  • Understand common Python numeric types such as int and float.
  • Use +, -, *, **, /, // and %.
  • Understand parentheses and operator precedence.
  • Use print() to display values and text.
  • Use single-, double- and triple-quoted strings.
  • Use escape sequences such as \n and \t.
  • Remember that input() returns a string.
  • Convert input with int() or float() when required.
  • Use comparison operators and if statements for decisions.
  • Understand Python's objects and dynamic typing.
  • Use type(), min() and max().
  • Understand the basic idea of range and reduction in descriptive statistics.

Quick Memory Map

VariablesArithmeticStringsInputifObjectsStatistics

If you remember one idea: Python programs are built by combining values, names, expressions and statements. Once you understand those building blocks, larger programs become combinations of the same ideas.

Common Beginner Mistakes

1. Using = instead of ==
= assigns a value; == compares two values.
2. Forgetting that input() returns text
input() returns a string even when the user types digits.
3. Forgetting the colon after if
Write if condition:.
4. Incorrect indentation
The statements belonging to an if suite must be indented.
5. Forgetting operator precedence
Use parentheses when the intended evaluation order is not obvious.
6. Dividing by zero
/ and // cannot divide by zero.

Revision Questions

1. What is a variable?
Show answer

A variable is a name associated with an object/value so the program can refer to it later.

2. What is the difference between = and ==?
Show answer

= assigns a value. == tests equality and produces True or False.

3. What does 7 / 4 produce?
Show answer

1.75. True division produces a floating-point result.

4. What does 7 // 4 produce?
Show answer

1. Floor division gives the greatest integer that is not greater than the mathematical result.

5. Why does input() need conversion for arithmetic?
Show answer

Because input() returns a string. Use int() or float() when numeric arithmetic is required.

6. What is dynamic typing?
Show answer

Python determines the type of the object a variable refers to while the program executes, and a variable can later refer to an object of another type.

7. What are minimum, maximum and range?
Show answer

Minimum is the smallest value, maximum is the largest value, and range describes the span from the minimum to the maximum.

Practice

  1. Create variables for your name, age and height, then print them.
  2. Calculate the result of 8 * (10 - 3) / 2 and explain the evaluation order.
  3. Write examples showing the difference between /, // and %.
  4. Ask the user for two integers and print their sum.
  5. Ask the user for a number and use if to determine whether it is greater than 100.
  6. Write a program that compares two integers using all six comparison operators.
  7. Create a triple-quoted multiline message and print it.
  8. Use type() to inspect an integer, float and string.
  9. Write a program that finds the minimum of three user-entered integers.
  10. Use min() and max() on a collection of values and describe the resulting range.