Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 20, 2021 12:24 pm GMT

Python 101! Introduction to Python

image

Python is an interpreted, high-level language created by Guido van Rossum and released in 1991. It is dynamically typed and garbage collected.

Python programs have the extension .py and can be run from the command line by typing python file_name.py.

Probably its most noticeable characteristic is its use of significant white space to delimit code blocks, instead of the more popular {} symbols.

End-of-line semicolons (;) are optional and usually not used in Python.

Python becomes the best solution in many domains from web applications, data analysis, data science, machine learning, and AI.

Common Feature Provided By python :

  • Simplicity: Think less of the syntax of the language and more of the code.

  • Open Source: A powerful language and it is free for everyone to use and alter as needed.

  • Portability: Python code can be shared and it would work the same way it was intended to. Seamless and hassle-free.

  • Being Embeddable & Extensible: Python can have snippets of other languages inside it to perform certain functions.

  • Being Interpreted: The worries of large memory tasks and other heavy CPU tasks are taken care of by Python itself leaving you to worry only about coding.

  • Huge amount of libraries: Data Science? Python has you covered. Web Development? Python still has you covered.

  • Object Orientation: Objects help breaking-down complex real-life problems into such that they can be coded and solved to obtain solutions.

Applications of Python.

  • Artificial Intelligence
  • Desktop Application
  • Automation
  • Web Development
  • Data Wrangling, Exploration And Visualisation.

Installation:

Download the latest version of Python for your operating system here. You can read more about setting up a python development using VS Code from this tutorial by pythontutorial.net.

Python Hello World.

As Raghu Venkatesh, Engineering Manager at Atlassian said, if you can write hello world you can change the world. So let create our first python program, hello world program.

First, create a new folder where you will be saving you python files, let say Lux.

Second, launch the VS code and open the new folder you created, Lux.

Third, create a new python file, let say app.py file and enter the following code and save the file:

print('Hello, World!')

The print() is a built-in function that displays a message on the screen. In our case, itll show the message 'Hello, Word!'.

Executing the Python program.

To execute the app.py file we created above, you first launch the Command Prompt on Windows or Terminal on macOS or Linux.

Then, navgiate to the folder containing our file, for our case Lux.

After that, type the following command to execute the app.py file:

Python3 app.py

If everything is fine, youll see the following message on the screen:

Hello, World!

Comments

A comment is text in a program's code, script, or another file that is not meant to be seen by the user running the program. However, is seen when viewing the source code.

Comments help make code easier to understand by explaining what is happening and help prevent portions of a program from executing.

# single line comment'''multiline commentUsing  docstring'''

NOTE: Use comments where appropriate and don't over do it.

Arithmetic Operators.

print(46 + 2)  # 48 (addition)print(10 - 9)  # 1 (subtraction)print(3 * 3)  # 9 (multiplication)print(84 / 2)  # 42.0 (division)print(2 ** 8)  # 256 (exponent)print(11 % 2)  # 1 (remainder of the division)print(11 // 2)  # 5 (floor division)

Variables

Variables are used to store information to be referenced and manipulated in a computer program. They also provide a way of labeling data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves. It is helpful to think of variables as containers that hold information. Their sole purpose is to label and store data in memory. This data can then be used throughout your program.

favourite_food = "Rsti"print(favourite_food)

Note:

Variables do not need to be declared. Their data types are inferred from their assignment statement, which makes Python a dynamically typed language. This means that different data types can be assigned to the same variable throughout the code.

favourite_food = "Rsti"print(favourite_food)favourite_food = 26print(favourite_food)favourite_food = Falseprint(favourite_food)

Comparison, Logical, and Conditional Operators.

Comparison: ==, !=, <, >, <=, >=
Logical: and, or, not
Conditionals: if, else, elif

# logical operators:laundry_day = "Monday"today = "Tuesday"on_vacation = Falseif today is laundry_day and today is not "Sunday" and on_vacation is False:  print("It's laundry day!")else:  print("The laundry can wait!")# comparison operators:age = 21if age >= 21:  print("You can drive a trailer")elif age >= 16:  print("You can drive a car")else:  print("You can ride a bike")  

Data Types

1). Strings.

#Example 1:language = "Python"#Example 2:multiline_str = '''oneperline'''  #Example 3, escape characters:escape_str = "She said: \"Python is great!\""print(escape_str) # She said: "Python is great!"  # Example 4, concatenate strings:one = "Lux"two = "Academy"print(one + " " + two) # Lux Academy # Example 5: interpolation.# method 1first_name = "Lux"last_name = "Academy"greet = f"Welcome at {first_name} {last_name}!" print(greet)  # Welcome at Lux Tech Academy!# method 2first_name = "Lux"last_name = "Academy"greet = 'Welcome at {} {}!'.format(first_name, last_name)print(greet)  # Welcome at Lux Tech Academy!# method 3first_name = "Lux"last_name = "Academy"greet = 'Welcome at{first} {last} !'.format( first=first_name, last=last_name) print(greet)  # Welcome at Lux Tech Academy!#Example 6, extract substringsname = "Monty Python"print(name[6:9]) # Pytprint(name[6:]) # Pythonprint(name[:5]) # Monty

2). Numbers

Python supports three numeric data types: int, float, and complex. They are inferred, so need not be specified.

age = 18 # intpi = 3.14 # floattotal = age + pi # floatprint(type(age), type(pi), type(total)) # <class 'int'> <class 'float'> <class 'float'>

3). Booleans.

# booleansa = Trueb = Falseif a is True and b is False:  print("YAY!")

4). Lists.

A list in Python is what other programming languages call an array. They use Zero-based indexing, and the items can contain any type of data. List items are nested in [].

# can store any data typemultiple_types = [True, 3.7, "Python"]# access and modifyfavourite_foods = ["pasta", "pizza", "french fries"]print(favourite_foods[1]) # pizzafavourite_foods[0] = "rsti"print(favourite_foods[0]) # rsti# subsetsprint(favourite_foods[1:3]) # ['pizza', 'french fries']print(favourite_foods[2:]) # ['french fries']print(favourite_foods[0:2]) # ['rsti', 'pizza']# appendfavourite_foods.append("paella")# insert at indexfavourite_foods.insert(1, "soup")# removefavourite_foods.remove("soup")# get lengthprint(len(favourite_foods)) # 4# get subset (the original list is not modified)print(favourite_foods[1:3]) # ['pizza', 'french fries']# lists inside listsfavourite_drinks = ["water", "wine", "juice"]favourites = [favourite_foods, favourite_drinks]print(favourites[1][2]) # juice

5). Tuples

Tuples are just like lists, but immutable (cannot be modified). They are surrounded by ().

#tuplesnew_tuple = ("a", "b", "c", "d")print(len(new_tuple)) # 4print(new_tuple[1]) # bprint(new_tuple[1:4]) # ('b', 'c', 'd')

6). Dictionaries.

Dictionaries are key-value pairs. They are surrounded by {} and are similar to objects in JavaScript. The values can have any data type.

language_creators = {  "Python" : "Guido van Rossum",  "C" : "Dennis Ritchie",  "Java" : "James Gosling",  "Go": "Robert Griesemer",  "Perl" : "Larry Wall"}# access, modify, deleteprint(language_creators["Python"]) # Guido van Rossumlanguage_creators["Go"] = ["Robert Griesemer", "Rob Pike", "Ken Thompson"]print(language_creators["Go"]) # ['Robert Griesemer', 'Rob Pike', 'Ken Thompson']print(len(language_creators)) # 5del language_creators["Perl"]print(len(language_creators)) # 4# print keys and valuesprint(language_creators.keys())print(language_creators.values())

Loops.

For loops

# foor loopfor x in range(0, 3):  print(x)# loop through listfor x in ["Python", "Go", "Java"]:  print(x)# loop through dictionarylanguage_creators = {  "Python" : "Guido van Rossum",  "C" : "Dennis Ritchie",  "Java" : "James Gosling",}for key, value in language_creators.items():  print("Language: {}; Creator: {}".format(key, value))

While loops.

# while looplevel = 0while(level < 10):  level += 1

Functions.

Functions are defined using the def keyword.

# functionsdef allowed_to_drive(age):  if age >= 21:    return True  else:    return Falseprint(allowed_to_drive(42)) # Trueprint(allowed_to_drive(12)) # False

Default values for arguments may also be defined.

def is_laundry_day(today, laundry_day = "Monday", on_vacation = False):  if today is laundry_day and today is not "Sunday" and on_vacation is False:    return True  else:    return Falseprint(is_laundry_day("Tuesday")) # Falseprint(is_laundry_day("Tuesday", "Tuesday")) # Trueprint(is_laundry_day("Friday", "Friday", True)) # False

Classes.

Classes are collections of variables and functions that work with those variables.
Classes in Python are defined with the class keyword. They are similar to classes in other languages like Java and C#, but differences include self being used instead of this to refer to the object resulted from the class. Also, the constructor functions name is init, instead of the more popular classname. self must be used every time a class variable is referenced and must be the first argument in each functions argument list, including the constructor.

Python does not support method overloading, but it can be achieved to some extent by using default values for arguments (shown in the Functions section).

# classesclass Email:  # __ means private  __read = False  def __init__(self, subject, body):    self.subject = subject    self.body = body  def mark_as_read(self):    self.__read = True  def is_read(self):    return self.__read  def is_spam(self):    return "you won 1 million" in self.subjecte = Email("Check this out", "There are a bunch of free online course here: https://course.online")print(e.is_spam()) # Falseprint(e.mark_as_read())print(e.is_read()) # True

Python also supports inheritance, which means that classes can be set to inherit methods and variables from another class or multiple classes (multiple inheritance).

# inheritanceclass EmailWithAttachment(Email):  def __init__(self, subject, body, attachment):    super(EmailWithAttachment, self).__init__(subject, body)    self.__attachment = attachment  def get_attachment_size(self):    return len(self.__attachment)email_with_attachment = EmailWithAttachment("you won 1 million dollars", "open attachment to win", "one million.pdf")print(email_with_attachment.is_spam()) # Trueprint(email_with_attachment.get_attachment_size()) # 15

File I/O

# writetodos_file = open("todos.txt", "wb")todos_file.write(bytes("buy a new domain name
", "UTF-8"))todos_file.write(bytes("work on the side project
", "UTF-8"))todos_file.write(bytes("learn a new programming language
", "UTF-8"))todos_file.close()# readtodos_file = open("todos.txt", "r+")todos_file_contents = todos_file.read()print(todos_file_contents)

Original Link: https://dev.to/grayhat/python-101-introduction-to-python-3kg5

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To