Last Updated on November 23, 2023 by Ankit Kochar
Python, known for its simplicity and versatility, has become a cornerstone in the world of programming. As a beginner-friendly language, Python offers a fantastic gateway into the world of coding. Mastering the basics of Python is crucial for anyone starting their programming journey or looking to expand their skill set. In this article, we’ll explore the essential topics that form the foundation of basic Python programming. From understanding variables and data types to looping constructs and functions, this guide aims to provide a comprehensive overview of fundamental Python concepts. Python is one of the easiest coding languages in the world. Let’s discuss the basic Python programming language in detail.
What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.
It is used for:
- web development (server-side),
- software development,
- mathematics,
- system scripting
- Web scraping
- Web Automation.
Why Python?
- Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
- Python has a simple syntax similar to the English language.
- Python has syntax that allows developers to write programs with fewer lines than some other programming languages.
- Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick.
- Python can be treated in a procedural way, an object-oriented way or a functional way.
Let’s Start with “Hello World!”
print(“Hello World!”)
In Python, it is only one line code for printing the hello world as output. In the above example, a print function is present which is used to print the output to the user.
Python Indentation
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important.
Python uses indentation to indicate a block of code.
if 6 > 1: print("Hello PrepBytes!!!") #Output: Hello PrepBytes!!!
Python Variables
In Python, variables are created when you assign a value to it. Python will make your workload less as there is no need to initialize any variables.
x = "Hello PrepBytes!!!" print(x) #Output: Hello PrepBytes!!!
Built-in Data Types
In programming, data type is an important concept.
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
None Type: None
We will see some data types used in some examples in the below topics.
Python Casting
Specify a Variable Type
There may be times when you want to specify a type on a variable. This can be done with casting. Python is an object-oriented language, and as such it uses classes to define data types, including its primitive types.
Casting in python is therefore done using constructor functions.
x = int(1) # x will be 1 x = float(1) # x will be 1.0 x = str("1") # x will be 's1'
Python String
Strings in python are surrounded by either single quotation marks, or double quotation marks.
‘hello’ is the same as "hello".
We can display a string literal with the print() function.
a = "Hello" print(a)
Python Booleans
In programming you often need to know if an expression is True or False.
You can evaluate any expression in Python, and get one of two answers, True or False.
When you compare two values, the expression is evaluated and Python returns the Boolean answer.
print(10 > 9) print(10 == 9) print(10 < 9)
Mostly values are True
Almost any value is evaluated to True if it has some sort of content.
Any string is True, except empty strings.
Any number is True, except 0.
Any list, tuple, set, and dictionary are True, except empty ones.
The bool() function allows you to evaluate any value, and give you True or False in return.
bool("abc") #True bool(123) #True bool(["apple", "cherry", "banana"]) #True bool([]) #False
Python List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set and Dictionary all with different qualities and usage.
Lists are created using square brackets
thislist = ["grapes", "banana", "mangoes"] print(thislist)
Python Tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set and Dictionary all with different qualities and usage.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
mytuple = ("ram","sham", "sita") print(mytuple)
Python Set
Sets are used to store multiple items in a single variable. A set is a collection which is unordered, unchangeable*, and unindexed.
myset = {"ram","sham", "sita"} print(myset)
Python Dictionaries
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
thisdict = { "Brand": "Maruti", "model": "Brezza", "year": 2022 } print(thisdict)
If, Elif, and Else
Decision making is required when we want to execute a code only if a certain condition is satisfied.
The if…elif…else statement is used in Python for decision making.
num = 3 if num > 0: print("Positive number") elif num == 0: print("Zero") else: print("Negative number")
While Loop
With the while loop we can execute a set of statements as long as a condition is true.
i = 1 while i < 6: print(i) i += 1
For Loop
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc
for x in "prepbytes": print(x)
Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
In Python a function is defined using the def keyword.
def my_function(): print("Hello from PrepBytes") my_function()
Conclusion
In conclusion, diving into the fundamental concepts of Python programming is an essential step towards becoming proficient in the language. The topics covered in this article serve as building blocks for developing more complex programs and applications. Remember, practice is key! Continuously applying these basics in small projects and exercises will solidify your understanding and set you on a path to becoming a proficient Python programmer. As you progress, exploring advanced topics and real-world applications will further enhance your skills and creativity in utilizing Python’s power.
FAQ Related to Basic Python Programming
Here are some FAQs related to basic python programming.
1. What are the essential topics in basic Python programming?
The essential topics in basic Python programming include variables, data types (such as strings, integers, floats, lists, tuples, dictionaries), control structures (if statements, loops), functions, modules, and file handling.
2. How can I practice and improve my Python skills?
Practice regularly by solving coding challenges, working on small projects, and experimenting with Python’s various features. Online platforms like LeetCode, HackerRank, and Codecademy offer exercises and projects suited for learners at different levels.
3. Why is understanding basic Python important?
Basic Python concepts form the foundation for more advanced programming. Mastering these fundamentals helps in writing efficient code, understanding complex concepts, and building sophisticated applications.
4. Where can I find additional resources to learn basic Python programming?
There are numerous online resources available, including interactive tutorials on websites like Codecademy, free courses on platforms like Coursera and edX, official Python documentation, and books like "Python Crash Course" by Eric Matthes and "Automate the Boring Stuff with Python" by Al Sweigart.
Thank you so much for very good details about python