Hello All,
In this article we will learn all python basics with very simple examples.
Here is the complete source code Download Here
Concept 1: Printing the Message
1. Create file called 01_hello_world.py
2. Write the below code
print('Python is best programming language')
Print : print statement is used to print the data in console
3. Open command prompt and type the file name 01_hello_world.py and press enter
PS D:\Python> .\01_hello_world.py
Then output will be
Here we will go through the concept to taking the input from command.
We use method called input. The input() function takes input from the user and returns it
Syntax:
variable_to_hold_the_input = input('[prompt message]')
Example:
1. Create file called 02_Input_from_user.py
2. Write the below statement
name = input("Enter your name ?\n") print("Entered Name is : " + name)
3. Open command prompt and type the file name 02_Input_from_user.py and press enter
PS D:\Python> .\02_Input_from_user.py
Then output will be
Concept 3: Datatypes in Python
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:
type() : function is used to determine the type of data type.
Example:
# Numbers : It contains positive or negative whole numbers
age = 30 print(age) print(type(age))
Output:
30
<class 'int'>
#Decimal : It is a real number with floating point representation.
price = 30.00002 print(price) print(type(price))
Output:
30.00002
<class 'float'>
#String : A string is a collection of one or more characters put in a single quote, double-quote or triple quote
name = "Python" print(name) print(type(name))
Output:
Python
<class 'str'>
#Boolean : Boolean objects that represents True or False.
is_required = True print(is_required) print(type(is_required))
Output:
True
<class 'bool'>
Concept 4: Type Conversion in Python
string to int conversion, when we read any input from command prompt it will be a string. we get conversion error str to int/float/bool conversion error. So we need to convert the same to required datatype
Below Program gives error, because we are not converting input value to int.
print("Welcome to Age Calculator") yob = input("Enter your year of birth : ") age = 2022 - yob print("Your age is : "+age)
Output:
PS D:\Python> & "C:/Program Files/Python310/python.exe"
d:/Python/04_Type_Conversion.py
Welcome to Age Calculator Enter your year of birth : 1988 Traceback (most recent call last): File "d:\Python\04_Type_Conversion.py", line 4, in <module> age = 2022 - yob TypeError: unsupported operand type(s) for -: 'int' and 'str'
Solution for above error is type conversion. Please find below
print("Welcome to Age Calculator") yob = input("Enter your year of birth : ") age = 2022 - int(yob) print("Your age is : "+str(age))
Output:
PS D:\Python> & "C:/Program Files/Python310/python.exe" d:/Python/04_Type_Conversion.py Welcome to Age Calculator Enter your year of birth : 1988 Your age is : 34
In the above example we have converted the string to integer and integer to string.
age = 2022 - int(yob) print("Your age is : "+str(age))
Concept 5: f-strings
In previous example we have done string concatenation by using + operator. It works fine, but what if we have more items to concatenate and Also conversion will be hectic part when we do concatenation(We cannot concatenate one datatype with other)
f-strings will helps to avoid type conversion and also code looks cleaner
f-strings released in python 3, we need to use "f" and variable will be mentioned within "{}"
Here is sample syntax
print(f"Your string {variable}")
Here is the example
name = input("Enter your name : ") age = int(input("Enter your age : ")) # with + Operator print("Hello "+name+" Welcome your age is "+str(age)) # using f-strinfgs print(f"Hello {name} Welcome your age is {age}")
# String concatination using + Operator
print("Hello "+name+" Welcome your age is "+str(age))
Above statement we have used + operator to concatenate, we need to maintain space between values and also type conversion, but in f-strings want require like this.
print(f"Hello {name} Welcome your age is {age}")
finally output of the program is
PS D:\Python> & "C:/Program Files/Python310/python.exe"
d:/Python/05_f_Strings.py Enter your name : Chakrapani U Enter your age : 34 Hello Chakrapani U Welcome your age is 34 Hello Chakrapani U Welcome your age is 34 PS D:\Python>
Concept 6: format()
As like f-strings we have another way to do it, that is .format(function), we keep empty place holder, later we will assign the value with the help of format method
name = input("Enter your name : ") age = int(input("Enter your age : ")) # String concatination using + Operator print("Hello "+name+" Welcome your age is "+str(age)) # With format method message = "Hello {} Welcome your age is {}" final_output = message.format(name,age) print(final_output)
Output:
PS D:\Python> & "C:/Program Files/Python310/python.exe" d:/Python/06_format.py Enter your name : Chakrapani U Enter your age : 34 Hello Chakrapani U Welcome your age is 34 Hello Chakrapani U Welcome your age is 34
In above example we need to mention the value in order name, first and age later inside format method, if we change the order then our output will be different, name place age will get displayed and age place name.
To avoid this we can use keys shown below
message = "Hello {n} Welcome your age is {a}" final_output = message.format(a=age,n=name) print(final_output)
Concept 7: Import External Libraries inside python file
Others libraries are used with the help of import keyword. In this example we use built in library called os, with this we can use some functions like clear screen like Console, list all files are present in directory
# import os import os # Clearing the console output os.system('cls') print("===============WELCOME TO PYTHON WORLD===============") # List all files print(os.listdir())
and output is
===============WELCOME TO PYTHON WORLD=============== ['.git', '.vscode', '01_hello_world.py', '02_Input_from_user.py', '03_data_types.py',
'04_Type_Conversion.py', '05_f_Strings.py', '06_format.py',
'07_import_other_libraries.py', '08_datetime.py', '09_list_data.py',
'10_tuples.py', '11_if_elif.py', '11_sets.py', '12_dictionary.py',
'apis', 'README.md']
Concept 8: Handling Date Time in python
If we want to use the date time in python we need to import the datetime library(class)
# importing datetime library import datetime # get todays date print(datetime.date.today()) # get current year print(datetime.date.today().year) # get current month print(datetime.date.today().month) # get current day print(datetime.date.today().day) # ctime(const time_t *timer) returns a string representing the
# localtime based on the argument timer. print(datetime.date.today().ctime())
above example shows the datetime usage
here is the output
PS D:\Python> & "C:/Program Files/Python310/python.exe" d:/Python/08_datetime.py 2022-04-29 2022 4 29 Fri Apr 29 00:00:00 2022
Concept 9: Conditional Statement In Python
Based on condition we can execute some statements, if elif else will helps us to do
print("Welcome To Check Day Based On Number") number = int(input("Enter Number to Check Which Day Falls : ")) if (number==1): print("Monday") elif (number==2): print("Tuesday") elif (number==3): print("Wednesday") elif (number==4): print("Thursday") elif (number==5): print("Friday") elif (number==6): print("Saturday") elif (number==7): print("Sunday") else: print("Not a valid choice")
Here is the output
PS D:\Python> & "C:/Program Files/Python310/python.exe" d:/Python/11_if_elif.py Welcome To Check Day Based On Number Enter Number to Check Which Day Falls : 5 Friday PS D:\Python> & "C:/Program Files/Python310/python.exe" d:/Python/11_if_elif.py Welcome To Check Day Based On Number Enter Number to Check Which Day Falls : 3 Wednesday PS D:\Python> & "C:/Program Files/Python310/python.exe" d:/Python/11_if_elif.py Welcome To Check Day Based On Number Enter Number to Check Which Day Falls : 10 Not a valid choice
Concept 10: Loops In Python
When we need specific code to be executed several numbers of times repeatedly, then we use loops.
We have two types of loops in python.
- While loop
- For loop
# Prints out 0,1,2,3,4,5,6,7,8,9 and come out if count reaches 10 count = 0 while count < 10: print(count) #Here we are increasing the value to 1 every run count += 1
0 1 2 3 4 5 6 7 8 9
names = ['chakrapani','upadhyaya','shreshta','shraddha'] for name in names: print(name)
PS D:\Python_Programming> & "C:/Program Files/Python310/python.exe"
d:/Python_Programming/13_loops.py chakrapani upadhyaya shreshta shraddha
# Prints out the numbers 0,1,2,3,4,5,6,7,8,9 for x in range(10): print(x)
0 1 2 3 4 5 6 7 8 9