Python basics: numbers, variables, strings, logic and type conversion
AdvertisementIntroduction
Python is a high-level, general-purpose programming language used in software development, automation, web applications, data analysis, and artificial intelligence.
Learning Python involves understanding how instructions are written, how values are represented, how expressions are evaluated, and how programs produce results.
This guide introduces fundamental programming concepts through small examples.
Python Statements and Expressions
A statement is an instruction that Python executes. An expression is a piece of code that produces a value.
Example of an expression:
10 + 20
Result:
30
Example of a statement:
total = 10 + 20
This statement calculates a value and assigns it to the variable total.
You can display the result using:
print(total)
Output:
30
Working with Numbers
Python supports integers and floating-point numbers.
Integers
Integers represent whole numbers.
age = 25
quantity = 100
temperature = -5
Floating-Point Numbers
Floating-point numbers represent values that can have fractional parts.
price = 99.50
height = 1.75
percentage = 85.5
Arithmetic Operations
a = 15
b = 4
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(a ** b)
Output:
19
11
60
3.75
3
3
50625
| Operator | Description |
|---|---|
+ |
Addition |
- |
Subtraction |
* |
Multiplication |
/ |
Division |
// |
Floor division |
% |
Remainder |
** |
Exponentiation |
Understanding Operator Precedence
When an expression contains multiple operators, Python follows rules that determine the order of evaluation.
For example:
result = 2 + 3 * 4
print(result)
Output:
14
Multiplication occurs before addition.
Parentheses can change the evaluation order:
result = (2 + 3) * 4
print(result)
Output:
20
Use parentheses when they make a complicated expression easier to understand.
Variables and Assignment
Variables allow programs to store and refer to values.
name = "Alex"
age = 22
salary = 35000.50
print(name)
print(age)
print(salary)
The assignment operator = assigns the value on the right to the variable on the left.
For example:
number = 10
number = 25
print(number)
Output:
25
The second assignment replaces the value previously associated with the variable.
Naming Variables
Valid variable names can contain letters, digits, and underscores, but cannot begin with a digit.
Examples:
student_name = "Alex"
age2 = 21
total_marks = 450
Invalid examples:
# 2age = 21
# student-name = "Alex"
Python is case-sensitive. Therefore, age, Age, and AGE are different names.
Strings in Python
A string represents text.
Strings can be written using single or double quotation marks.
first_name = "Alex"
city = 'Ahmedabad'
print(first_name)
print(city)
You can combine strings using the concatenation operator:
first_name = "Alex"
last_name = "Sharma"
full_name = first_name + " " + last_name
print(full_name)
Output:
Alex Sharma
String Formatting
F-strings provide a convenient way to insert variable values into text.
name = "Alex"
age = 22
print(f"My name is {name} and I am {age} years old.")
Output:
My name is Alex and I am 22 years old.
Boolean Values and Comparisons
A Boolean value represents either True or False.
Comparison operators compare values and produce Boolean results.
print(10 > 5)
print(10 < 5)
print(10 == 10)
print(10 != 5)
Output:
True
False
True
True
The comparison operators are:
| Operator | Meaning |
|---|---|
== |
Equal to |
!= |
Not equal to |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal to |
<= |
Less than or equal to |
Remember that = is used for assignment, while == compares two values.
Logical Operators
Logical operators combine or reverse Boolean conditions.
Python provides three primary logical operators.
AND
The expression is true only when both conditions are true.
age = 25
print(age >= 18 and age <= 60)
Output:
True
OR
The expression is true when at least one condition is true.
is_weekend = False
is_holiday = True
print(is_weekend or is_holiday)
Output:
True
NOT
The not operator reverses a Boolean value.
is_raining = False
print(not is_raining)
Output:
True
Logical operators are useful for combining conditions in decision-making programs.
Type Conversion
Type conversion changes a value from one data type to another when the conversion is supported.
Examples:
number = int("25")
price = float("99.50")
text = str(100)
print(number)
print(price)
print(text)
Output:
25
99.5
100
Common conversion functions include:
int(): Converts a compatible value to an integer.float(): Converts a compatible value to a floating-point number.str(): Produces a string representation of a value.bool(): Converts a value to its Boolean interpretation.
Invalid conversions may raise an exception.
For example, int("hello") raises a ValueError because the string does not represent an integer.
Taking Input from Users
The input() function reads text entered by the user.
name = input("Enter your name: ")
print(f"Welcome, {name}!")
Example:
Enter your name: Alex
Welcome, Alex!
The value returned by input() is a string. Convert it when you need to perform numerical calculations.
number1 = int(input("Enter the first number: "))
number2 = int(input("Enter the second number: "))
print("Sum:", number1 + number2)
This example accepts two integers and displays their sum.
Common Python Errors
Understanding errors is an essential part of programming.
SyntaxError
A syntax error occurs when Python cannot parse the code.
Incorrect:
print("Hello)
Correct:
print("Hello")
NameError
A NameError can occur when a name is used before it has been defined.
Incorrect:
print(total)
If total has not been defined, Python raises a NameError.
Correct:
total = 100
print(total)
TypeError
A TypeError can occur when an operation is used with incompatible types.
For example:
# This raises a TypeError:
# print("Age: " + 25)
One solution is to convert the number to a string:
print("Age: " + str(25))
Alternatively, use an f-string:
print(f"Age: {25}")
Practical Example: Simple Calculator
The following program combines variables, user input, type conversion, arithmetic, and output.
print("Simple Calculator")
number1 = float(input("Enter the first number: "))
number2 = float(input("Enter the second number: "))
print("Addition:", number1 + number2)
print("Subtraction:", number1 - number2)
print("Multiplication:", number1 * number2)
if number2 != 0:
print("Division:", number1 / number2)
else:
print("Division is not possible because the second number is zero.")
The program calculates four results and checks whether the divisor is zero before performing division.
Practice Exercises
Try solving these exercises without looking at the solutions first.
Exercise 1: Basic Arithmetic
Create two variables, assign numerical values, and print their sum, difference, and product.
Exercise 2: Personal Information
Ask the user for their name and age. Display a message containing both values.
Exercise 3: Even or Odd
Ask the user to enter an integer and determine whether it is even or odd using the modulo operator.
Hint:
number % 2
Exercise 4: Temperature Conversion
Convert a temperature from Celsius to Fahrenheit using:
Fahrenheit = (Celsius * 9 / 5) + 32
Exercise 5: Comparison
Ask the user to enter two numbers and display which number is greater, or report that they are equal.
Suggested Learning Path
After understanding these introductory concepts, continue with:
- Variables and data types
- Operators and expressions
- Conditional statements
- Loops
- Strings and string methods
- Lists, tuples, sets, and dictionaries
- Functions
- Modules and packages
- Exception handling
- File handling
- Object-oriented programming
- Practical projects
Practise each topic with small programs to strengthen your understanding.
Conclusion
Python programming becomes easier when its fundamental concepts are learned step by step. Understanding expressions, variables, data types, operators, comparisons, and type conversion provides a foundation for writing more complex programs.
Rather than memorizing every command, focus on understanding what each statement does, why it works, and how different concepts can be combined to solve problems.
Official resources
About this guide. This is a written study guide for the topic of this episode, prepared to go with the video above. It is not a word-for-word transcript, so the video may cover things in a different order.