Python is a popular programming language known for its simplicity and ease of use. One of the fundamental concepts in programming is the use of variables. In this tutorial, we will discuss the basic aspects of python language, starting with variables and data types.

What are variables?

A variable is a named storage location in a computer’s memory that is used to store data. The data stored in a variable can be changed or manipulated during the execution of a program. Variables are given a name and a data type, which defines the type of data that can be stored in the variable.

Why are variables important?

Variables are important because they allow us to store and manipulate data in a program. Without variables, we would have to write the same data over and over again in a program, which would be both time-consuming and error-prone. By using variables, we can store data once and then refer to it multiple times throughout the program.

What are data types in Python?

In Python, there are several data types that can be used to store data in variables. Some of the most commonly used data types include:

Integer (int): An integer is a whole number (positive, negative, or zero) that can be stored in a variable. For example:

age = 25

Float (float): A float is a decimal number that can be stored in a variable. For example:

height = 1.75

String (str): A string is a sequence of characters that can be stored in a variable. For example:

name = "John Doe"

Boolean (bool): A boolean is a data type that can only store two values: True or False. For example:

is_student = True

List (list): represents a collection of values, such as [1, 2, 3], and can be stored in a variable. For example:

numbers = [1, 2, 3, 4]

Tuple (tuple): similar to lists, but the values cannot be changed after the tuple is created and can be stored in a variable. For example:

person = ('John', 25, 68.5)

Dictionary (dict): represents a collection of key-value pairs and can be stored in a variable. For example:

person = {'name': 'John', 'age': 25, 'weight': 68.5}

Set (set): represents a collection of unique values and can be stored in a variable. For example:

unique_numbers = {1, 2, 3, 4}

Declaring Variables in Python

To declare a variable in Python, you simply need to assign a value to a variable name. For example:

name = "Jane Doe"

In this example, the variable name is assigned the string value of "Jane Doe".

Using Variables in Python

Once you have declared a variable in Python, you can use the variable in various ways in your program. For example, you can use the value stored in a variable to perform calculations or to print the value to the screen.

For example, to print the value stored in the name variable to the screen, you can use the following code:

print(name)

# output
# Jane Doe
Start text on the road

Your First Python Program with Python

Let’s write another simple Python program that calculates the area of a circle. This program will take the radius of the circle as input and calculate its area.

Here is the code:

radius = float(input("Enter the radius of the circle: "))
area = 3.14 * radius * radius
print("The area of the circle with radius", radius, "is", area)

When you run the program, it will ask you to enter the radius of the circle. Enter a value and press Enter. You should see the output of the program, which is the area of the circle with the given radius.

Working of the Program

In this program, we first take the radius of the circle as input from the user using the input function. The input function returns the input as a string, so we need to convert it to a float using the float function.

Next, we calculate the area of the circle using the formula 3.14 * radius * radius. Finally, we use the print function to display the result.

This program demonstrates how you can use variables and the input function to take input from the user, perform calculations, and display the result.

Before We Begin and dig deeper into coding

Before we dive into the coding part, let’s go over a few important points.

  1. Overcoming the fear of coding: Many people feel intimidated by coding and think it is difficult to learn. However, just like any other skill, coding can be learned with practice and dedication. Don’t be afraid to make mistakes, as they are an important part of the learning process.
  1. Coding is a form of communication: Just like spoken languages, coding is a way to communicate with computers. With programming, you can give instructions to a computer to perform specific tasks.
  1. Basic math skills are all you need: Although coding may seem complex, it only requires basic arithmetic skills. Most of the time, coding involves logical thinking and problem-solving skills, rather than complex mathematical calculations.

With these points in mind, let’s get started with learning the fundamentals of Python.

Python Fundamental Concepts

Before we start writing programs, there are a few basic concepts in Python that we need to understand. Let’s go over these concepts now:

  1. Numbers and Texts: In Python, there are two main data types that we use to store values – numbers and texts. Numbers can be integers or floating-point numbers, while texts are called strings. For example:
age = 25
weight = 72.5
name = "John Doe"

In this example, age is an integer, weight is a floating-point number, and name is a string.

  1. Print Output: The print function is used to display the output of a program. You can print numbers, strings, or any other data type. For example:
print(25)
print(72.5)
print("John Doe")

This will output the following:

25
72.5
John Doe

These two concepts are the building blocks for writing programs in Python. In the next lesson, we will learn how to use these concepts to write simple programs.

foot print with rocks on the beach

Using numbers, texts, comments, and print in program

In programming, we can use fixed values directly in our programs, known as literals. Here are the most commonly used literals in Python:

Integers (int): Integers are whole numbers without any decimal parts. For example:

age = 25
temperature = -10

In this example, age is an integer with the value of 25, and temperature is an integer with the value of -10.

Floating-point Numbers (float): Floating-point numbers are numbers with decimal parts. For example:

height = 1.75
weight = 72.5

In this example, height is a floating-point number with the value of 1.75, and weight is a floating-point number with the value of 72.5.

Strings (str): Strings are sequences of characters wrapped in quotation marks. In Python, you can use either single quotes or double quotes to create strings. For example:

name = "Jane Doe"
address = '123 Main Street'

In this example, name is a string with the value of “Jane Doe”, and address is a string with the value of “123 Main Street”.

These are the most commonly used literals in Python. By understanding these data types, you can store different types of values in your programs and use them to perform various operations.

Printing Numbers and Strings in Python

In Python, we use the print function to display output on the screen. In this section, we will learn how to print numbers and strings.

Let’s start with printing numbers:

print(25)
print(-12)
print(3.14)

This will output the following:

25
-12
3.14

As you can see, we can simply pass a number as an argument to the print function, and it will print the number on the screen.

Next, let’s look at how to print strings:

print("Hello, World!")
print("My name is John.")

This will output the following:

Hello, World!
My name is John.

o print a string, you need to wrap the text in quotes. You can use either single quotes or double quotes.

the print function in more detail and also look at common mistakes that you might face while using print.

# print an integer
print(37)    # Output: 37
 
# print a string
print('Superheroes')    # Output: Superheroes
 
# create a variable
capital = 'Paris'
 
# print the capital variable
print(capital)     # Output: Paris
 
# print multiple items at once
print(19, 'Spiderman')    # Output: 19 Spiderman

In this example, we have used the print function to print integers, strings, and variables. We have also shown how to print multiple items at once.

Note that when we print strings, the outer quotation marks are not displayed in the output.

Common Mistakes with print

  1. Forgetting to put quotes around strings

When printing strings, make sure to wrap the text in either single quotes or double quotes, or else you will get an error.

  1. Using commas instead of the + operator to concatenate strings

To concatenate two strings, you need to use the + operator, not a comma. For example:

print("Hello" + "World")    # Output: Hello World

The print function is a useful tool for displaying output in Python. By understanding the print function and avoiding common mistakes, you can make sure that your programs produce the output you expect.

That’s it! With these examples, you now know how to print numbers and strings using the print function in Python.

Python Comments

In programming, we can make computers ignore certain parts of the program by using comments. In Python, a comment starts with the symbol #.

For example:

# This is a comment
print(25)

In this example, the line # This is a comment is a comment, and it is ignored by the computer. The print function is executed and the output will be:

25

Why Use Comments in Python?

Even though comments are ignored by the computer, they play an important role in helping other people who read the code understand it. For example, if you are working on a project with a team of developers, comments can help them understand the logic and thought process behind the code.

In addition, comments can also be used to temporarily disable a portion of the code or to explain the working of a particular section of the code.

For example:

# Calculate the area of a circle
radius = float(input("Enter the radius of the circle: "))
area = 3.14 * radius * radius
print("The area of the circle with radius", radius, "is", area)

In this example, the comment # Calculate the area of a circle explains what the code below it does.

In conclusion, comments are a useful tool in programming, and it is a good practice to add comments to your code to help others understand it.

Slip-on banana's mistake

Common mistakes with creating variables and the use of print function

As a beginner in Python, it is common to make certain mistakes. In this section, we will cover two common mistakes that you might make.

  1. Spelling Errors: Spelling errors are a common cause of errors in programming. For example, if you use the wrong variable name or misspell a word, you will get an error. For example:
salary = 95000
# Error because of a spelling mistake
print(salary_icome)

This will result in an error:

File "<string>", line 2, in <module>
NameError: name 'salary_icome' is not defined

In this case, the error message clearly states that salary_icome is not defined.

It is important to note that Python is case-sensitive. This means that salary and Salary are considered to be two different variables.

  1. Adding Spaces at the Beginning: In Python, indentation has a special meaning. So, if you add unnecessary spaces at the beginning of a line, you will get an error. For example:
 print('Hello')  # Error

If you run this code, you will get an error because there is a space at the beginning of the line.

In conclusion, being aware of these common mistakes can help you avoid them and write error-free code in Python.

  1. Error Due to Quotation Marks: A common mistake made by beginners is forgetting to add the ending quotation marks in a string. For example:
print('Hello)   # Error

n this case, Python doesn’t know what 'Hello is. It is not a string because it doesn’t have the ending quotation mark, and it is not a variable because you cannot use quotation marks in variable names.

  1. Forgetting Commas in the Print Function: Another common mistake is forgetting to use commas in the print function. For example:
age = 20
print('Age:' age)   # Error

In this case, Python interprets 'Age:' age as a single item. Since it is neither a string nor a variable, you will get an error.

In conclusion, being aware of these common mistakes can help you avoid them and write error-free code in Python.

a child learning arithmetic

Introduction to Operators in Python

Up until now, we have learned about values, variables, and how to print them. However, in real-world projects, we need to perform operations on these values and variables, not just print them.

In this lesson, we will learn about operators, which are special symbols that allow us to perform operations on values and variables.

For example:

number = 5
total = number + 10
print(total)

In this program, + is an operator that is used to perform addition.

Here is a list of operators we will learn in this lesson:

OperatorSyntaxMeaning
+x + yAddition
-x - ySubtraction
*x * yMultiplication
/x / yDivision
%x % yRemainder
**x ** yExponentiation

Let’s start with the + operator.

The + Operator

The + operator is used to add two operands (values or variables). For example:

x = 10
y = 20

# using + to perform addition
total = x + y + 30

print(total)    # Output: 60

n this program, total = x + y + 30 first computes the sum of x, y, and 30. Then, the result is assigned to the total variable.

We can also perform addition directly without using an extra variable. For example:

x = 12.5
y = 10

print(x + y)     # Output: 22.5

In this example, the line print(x + y) first computes the sum of x and y. Then, the result is directly printed on the screen.

The - Operator

The - operator subtracts the value on the right from the value on the left. For example:

x = 10
y = 6

result = x - y
print(result)    # Output: 4

In this program, result = x - y first subtracts y from x. Then, the result is assigned to the result variable.

Here is another example:

x = 10
y = 6

print('Result:', x - y)

This statement prints the string ‘Result:’ and then prints the difference of x and y.

The - operator works by subtracting the value on the right from the value on the left.

The * Operator

The * operator multiplies two values or variables. For example:

number1 = 5
number2 = 10

# computing the product of number1 and number2
product = number1 * number2
print(product)    # Output: 50

In this program, we first define two variables, number1 and number2, and store values in them. Then, we calculate the product of number1 and number2 and store it in the product variable. Finally, we print the product using the print function.

Here is another example:

number = 5.5

# computing the product of number and 10
product = number * 10
print(product)    # Output: 55.0

In this program, we define a variable number and store a value in it. Then, we calculate the product of number and 10 and store it in the product variable. Finally, we print the product using the print function.

The / Operator

The / operator is used for division. For example:

number = 25

result = number / 4
print(result)    # Output: 6.25

In this program, we define a variable number and store a value in it. Then, we divide number by 4 and store the result in the result variable. Finally, we print the result using the print function.

Here is another example:

number = 25

result = number / 5
print(result)    # Output: 5.0

In this program, we divide number by 5 and store the result in the result variable. Finally, we print the result using the print function.

Note that the / operator always returns a float value. In this case, 25 divided by 5 results in 5.0 and not 5.

The % Operator

The % operator computes remainder when one number is divided by another.

divisor = 5
dividend = 25

# compute remainder
remainder = dividend % divisor

print(remainder) # Output: 0
# In the above program, 25 divided by 5 is 5 with 0 as the remainder.

The ** Operator

The ** operator computes the exponential (power) of a number. Let’s take an example:

base = 2.5
power = 3
 
result = base ** power
print(result)

# Output

# 15.625
Time for conversion

Conversions

We can convert data of one type to another using type conversion functions.

In Python, there are types of conversion functions:

int(x) – Converts x to an integer. float(x) – Converts x to a float. For example:

# convert string to integer
string = "25"
number = int(string)
print(number) # Output: 25

# convert integer to float
integer = 25
float_number = float(integer)
print(float_number) # Output: 25.0

# convert string to float
string = "25.5"
float_number = float(string)
print(float_number) # Output: 25.5
keyboard for user input

User Inputs

In Python, we can also ask the user for input and assign it to a variable. This can be done using the input() function. For example:

name = input('Enter your name: ')
print('Your name is', name)

User Input Without Prompt

full_name = input()
print('Full name:', full_name)

The full_name = input() statement doesn’t print anything but makes the program wait until the user gives input.

When we don’t provide a prompt message in the input function, the user might not know what to enter. But when we provide a prompt message, it gives clear instructions to the user about what kind of input is expected. In the above example, when the user runs the program, it waits for the input without displaying any prompt message. Hence, it’s always a good practice to provide a clear prompt message to the user.

Let’s put conversion with user inputs together in the next example:

# Take inputs from the user
number1 = input("Enter a number: ")
number2 = input("Enter another number: ")

# converting the strings to integers
number1 = int(number1)
number2 = int(number2)

product = number1 * number2
print('Product:', product)

# Sample Output
# -------------
# Enter a number: 5
# Enter another number: 10
# Product: 50
Conclusion

Conclusion

The article covers the basic concepts of Python programming. It discusses numbers, including integers and floating-point numbers, and strings, which are sequences of characters wrapped in quotation marks. Variables are introduced as a way to store data for later use in the program, and the print() function is explained as a way to display output. The article also covers the use of comments in a program, which starts with a # symbol, and various arithmetic operators. Data conversion is discussed, including the use of the int() and float() functions to convert data types. The article concludes with a discussion of the input() function, which is used to get input from the user and always returns input as a string.

https://ahmedradwan.dev

Reach out if you want to join me and write articles with the nerds 🙂