๐Ÿ Python Basics: From Variables to Conditional Statements ๐Ÿ“š

๐Ÿ Python Basics: From Variables to Conditional Statements ๐Ÿ“š

A Practical Guide for Beginners in Python Programming ๐Ÿš€

ยท

6 min read

Introduction

Hello everyone! In this article, I'll provide a practical guide to getting started with Python. ๐Ÿ Follow this guide to begin your journey with Python programming.

Before we begin, make sure to install Python and a text editor like PyScripter. Feel free to use your favourite IDE as well! โœจ

Let's dive into the exciting world of Python programming together!

Practical Guide

#-------------------------------------------------------------------------------
# Name:        Practical Guide Python - I
# Purpose:     Practical Guide on Python
#
# Author:      Kunal
#
# Created:     27/11/2023
# Copyright:   (c) Kunal 2023
#-------------------------------------------------------------------------------

# -> This is a single-line comment in Python. We use the '#' symbol to write comments in Python.
# -> Shortcut for comment is CTRL+/ on Windows 

# We use print() function in Python to display messages on the screen.
# You can write messages in ' ' single quotes or double quotes "" both will work
print("Hello World")
print('Python')

# We can also save this file with the extension after saving; the file will be .py. Just like in C we have .c, in Java .java, the same is for Python .py

# Just try to run this code on your system to check if everything is working fine

"""
This is multiline comments in Python. We use comments for documentation
or in simple terms, it increases code readability. Comments are ignored by
compiler and interprets. Python is an interpreted scripting language.

"""

#-------------------------------------------------------------------------------

# First program in Python
print('Hello World')

# print is a function. Anything written inside the quote is known as a string
# What is String? "String is a collection or sequence of characters"
# e.g., "Hello", "Hi", "Bye"

#-------------------------------------------------------------------------------

# Variables

"""
Many textbooks define a variable as the container where our value is stored.
Variable values can be changed. Variables mean they can vary.

We can store any data into variables like numbers, strings.

If you are coming from learning C, C++, Java, then like these programming
languages. We don't need to define data type and then variable name.
<DataType> <VarName> = literal; you can directly write the name of the variable and
value.
"""

name = "IRON MAN"
age = 22

print(name)
print(age)

#-------------------------------------------------------------------------------

# 4 types of variables
# string, numbers, float, boolean

name = "IRON MAN"  # string
age = 22  # number
height = 5.5  # float
is_adult = True  # boolean

#-------------------------------------------------------------------------------

# Taking Input from the user
""" here in Python, we use input() function to take input from the user
below is the example show """

year = input('Which year of Engg. do you study?')
print(year)

"""
here in this program, we took input from the user and stored the value
in the year variable and then displayed it on the output screen using
print() function
"""

year = input('Which year of Engg. do you study?')
print("I study in " + year + " year")

# here you can see we used '+' symbol it means concatenation operation
# now the above program will display I study in 3 years (the year which user has entered for demo I took 3)

#-------------------------------------------------------------------------------

# type conversion
oldAge = input("enter your old age?")
newAge = oldAge + 5
print(newAge)

"""
The above code will throw error

Traceback (most recent call last):
  File "<module1>", line 99, in <module>
TypeError: can only concatenate str (not "int") to str

WHY?
every input in Python is by default string
so the above code took oldAge as a string and 5 as a number
so it throws the error so how to solve this error it's simple
here we will use type conversion

"""

oldAge = int(input("enter your old age?"))
newAge = oldAge + 5
print(newAge)

"""
Now after type conversion, you will get your desired result
"""
"""
we can do multiple conversions like
float()
str()
bool()
"""


# write a program to add, sub, multiply two numbers

first = int(input("Enter the First Number"))
second = int(input("Enter the second Number"))

print(first + second)
print(first - second)
print(first * second)

"""
check the output for the above code
"""
#-------------------------------------------------------------------------------

# String Methods in Python
name = "learn"
print(name.upper())  # convert string into uppercase
print(name.lower())  # convert string into lowercase

print(name.find('l'))  # finds the char in the string it will return index(pos) if found otherwise -1

print(name.replace("python"))  # we replace learn with python using this function

#-------------------------------------------------------------------------------

# Keywords
"""
keywords in Python are predefined words that our interpreter already knows like
in, pass, break, input, print, etc.
we can't declare keywords as variables
"""

name = "learn python "
print('p' in name)

"""
in the above code, we used the 'in' keyword to search p is there in the name variable or not
this will return Boolean Return (True/False)
"""



# the next two concepts are operators and operator precedence
# Operators -> https://www.geeksforgeeks.org/python-operators/
# Operator Precedence - > https://www.programiz.com/python-programming/precedence-associativity

# InShort
"""
Operators are special symbols that perform particular mathematical operations on variables
and values

Arithmetic operators + - / % *
Basic mathematical operations like addition, subtraction, division, multiplication
"""
# example

print(3+4)
print(3-3)
print(5/4)
print(4%4)

"""
There are many other operators to explore you can refer to the above link to learn
and explore more on Python operators
"""

# Comparison Operators
"""
These operators are used to compare, return the boolean value True or False
<, >, <=, >=, ==, !=
"""
# example
print(3==3)
print(4>3)
print(4!=2)
print(8<3)

# Logical Operators
"""
or, and, not

"""
print(3==3 or 4==4)
print(4>3 and 5<3)

#-------------------------------------------------------------------------------
# Conditional statements in Python
"""
if you want to apply conditions than we use these statements
if
if-else
if-elif
"""

# example
# single condition code
age=18
if age >=18:
    print("You are adult")
    print("You can Vote")
print("Thank You")


# if-else code
age = 15
if age >=18:
    print("You can Vote")
else:
    print("You can't Vote")


# testing multiple condition in Python using elif
age = 30
if age >= 18:
    print("You are adult")
elif age < 18 and age > 3:
    print("You are in school")
else:
    print("You are a child")

"""
the above code is used for testing multiple conditions you can put as much elif you
want according to your problem statement and the last condition which will get executed is 'else' block
"""

# Note
"""
In other programming language
{
This is block
}

in Python, we define a block using indentation
example:
    if age==18:
        print("Hello")
"""


# so now as a beginner, we will try to build a micro-project in Python
# i.e A simple calculator before going to this code you can try it yourself once

# Project: Build a simple calculator which can perform + , - , / , % and * operations

first = int(input("Enter First number "))
op = (input("Enter Operation : + , - , / , * , %"))
second = int(input("Enter second number "))

if op == '+':
    print(first + second)
elif op == '-':
    print(first - second)
elif op == '/':
    print(first / second)
elif op == '*':
    print(first * second)
elif op == '%':
    print(first % second)
else:
    print("Please Enter a Valid Input")

#THE END

Quick Recap What we have learned from this guide

  1. Introduction to Python Basics: Covering variables, comments, and the print() function for displaying messages.

  2. Understanding Variables: Explaining variable types like strings, numbers, floats, and booleans.

  3. User Interaction: How to take user input using the input() function and handle type conversions.

  4. String Manipulation: Exploring string methods such as upper(), lower(), find(), and replace().

  5. Keywords and Operators: Overview of keywords, arithmetic, comparison, and logical operators in Python.

  6. Conditional Statements: Using if, if-else, and if-elif-else for decision-making in Python.

  7. Mini Project - Simple Calculator: Implementing basic arithmetic operations based on user input.

  8. Code Structure in Python: Highlighting the importance of indentation for defining blocks of code.

ย