#3 Crash Course on Python !!!
This is 3rd and last article on crash course on python, in this article you’ll learn what are Tuples, If Statements, Dictionaries, Functions. Make sure you have read #2Crash course in python before reading this Article.
Tuples
A tuple looks just like a list except you use parentheses instead of square brackets. Once you define a tuple, you can access individual elements by using each item’s index, just as you would for a list. For example, if we have a rectangle that should always be a certain size, we can ensure that its size doesn’t change by putting the dimensions into a tuple, yes you read it right A TUPLE CANNOT BE CHANGED
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
Output
200
50
Let’s see what happens if we try to change one of the items in the tuple dimensions:
dimensions = (200, 50)
dimensions[0] = 250
Although you can’t modify a tuple, you can assign a new value to a variable that holds a tuple. So if we wanted to change our dimensions, we could redefine the entire tuple
dimensions = (200, 50)
print(“Original dimensions:”)
for dimension in dimensions: (#create a loop by assigning a variable to tuple)
print(dimension)
output
Original dimensions:
200
50
If Statements
At the heart of every if statement is an expression that can be evaluated as True or False and is called a conditional test. Python uses the values True and False to decide whether the code in an if statement should be executed. If a conditional test evaluates to True, Python executes the code following the if statement. If the test evaluates to False, Python ignores the code following the if statement.
For Example:-
car = ‘bmw’
car == ‘bmw’
Output
True
or
car = ‘Audi’
car == ‘audi’
False ( Yes, Python is case sensitive)
Now, lets apply if condition on any quantity for example:-
answer = 17
if answer != 42: ( != represent not equal to)
print(“That is not the correct answer. Please try again!”)
Output
That is not the correct answer. Please try again!
As you can see the answer is not equal to 42, so condition is true so its printing (That is not the correct answer. Please try again!).
Other times, it’s important to know if a value does not appear in a list. You can use the keyword not in this situation.
banned_users = [‘andrew’, ‘carolina’, ‘david’]
user = ‘marie’
if user not in banned_users:
print(user.title() + “, you can post a response if you wish.”)
Output
Marie, you can post a response if you wish.
if-else Statements
Often, you’ll want to take one action when a conditional test passes and a different action in all other cases. Python’s if-else syntax makes this possible. An if-else block is similar to a simple if statement, but the else statement allows you to define an action or set of actions that are executed when the conditional test fails. for example:-
age = 17
if age >= 18:
print(“You are old enough to vote!”)
print(“Have you registered to vote yet?”)
else:
print(“Sorry, you are too young to vote.”)
print(“Please register to vote as soon as you turn 18!”)
output
Sorry, you are too young to vote.
Please register to vote as soon as you turn 18!
The if-elif-else Chain
Often, you’ll need to test more than two possible situations, and to evaluate these you can use Python’s if-elif-else syntax. Python executes only one block in an if-elif-else chain. It runs each conditional test in order until one passes. When a test passes, the code following that test is executed and Python skips the rest of the tests. For example:-
age = 12
if age < 4:
print ( “your admission cost is 0”)
elif age < 18:
print (“your admission cost is $50”)
else
print (“your admission cost is$100”)
output
Your admission cost is $5
At this point in the chain, we know the person is at least 4 years old because the first test failed. If the person is less than 18, an appropriate message is printed and Python skips the else block. If both the if and elif tests fail, Python runs the code in the else block.
Dictionaries
Understanding dictionaries allows you to model a variety of real-world objects more accurately. In Python, a dictionary is wrapped in braces, {}You’ll be able to create a dictionary representing a person and then store as much information as you want about that person. You can store their name, age, location, profession, and any other aspect of a person you can describe.
A Simple Dictionary Consider a game featuring aliens that can have different colors and point values. This simple dictionary stores information about a particular alien:
alien_0 = {‘color’: ‘green’, ‘points’: 5}
print(alien_0[‘color’])
print(alien_0[‘points’])
Output
green
5
Removing Key-Value Pairs
When you no longer need a piece of information that’s stored in a dictionary, you can use the del statement to completely remove a key-value pair. All del needs is the name of the dictionary and the key that you want to remove. For example, let’s remove the key ‘points’ from the alien_0 dictionary along with its value:
alien_0 = {‘color’: ‘green’, ‘points’: 5}
print(alien_0)
del alien_0[‘points’]
print(alien_0)
Output
{‘color’: ‘green’}
Another example could be
alien_0 = {‘color’: ‘green’, ‘points’: 5}
alien_1 = {‘color’: ‘yellow’, ‘points’: 10}
alien_2 = {‘color’: ‘red’, ‘points’: 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
Output
{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘yellow’, ‘points’: 10}
{‘color’: ‘red’, ‘points’: 15}
Functions
If you need to perform that task multiple times throughout your program, you don’t need to type all the code for the same task again and again; you just call the function dedicated to handling that task, and the call tells Python to run the code inside the function.
def greet_user(username):
print(“Hello, “ + username.title() + “!”)
greet_user(‘jesse’)
Output
Hello, Jesse!
Entering greet_user(‘jesse’) calls greet_user() and gives the function the information it needs to execute the print statement. The function accepts the name you passed it and displays the greeting for that name
Likewise, entering greet_user(‘sarah’) calls greet_user(), passes it ‘sarah’, and prints Hello, Sarah! You can call greet_user() as often as you want and pass it any name you want to produce a predictable output every time.
When you call a function, Python must match each argument in the function call with a parameter in the function definition. The simplest way to do this is based on the order of the arguments provided. Values matched up this way are called positional arguments. To see how this works, consider a function that displays information about pets. The function tells us what kind of animal each pet is and the pet’s name, as shown here:
def describe_pet(animal_type, pet_name):
print(“I have a “ + animal_type + “.”)
print(“My “ + animal_type + “‘s name is “ + pet_name.title() + “.”) describe_pet(‘hamster’, ‘harry’)
Output
I have a hamster.
My hamster’s name is Harry.
___________________________________________________________________
Congratulations! You’ve learned the basics of Python and now you are ready to apply your knowledge to meaningful projects. First, you should continue to work on meaningful projects that interest you. Programming is more appealing when you’re solving relevant and significant problems, and you now have the skills to engage in a variety of projects.
Good luck with your continued learning!
I will bring crash course on Data Visualization with Python !!!
Do refer to my Profiles for the Further Content.!!
Linkedin : Kartik Aggarwal | LinkedIn
Medium : Kartik Aggarwal — Medium