Code Category Page - PythonForBeginners.com https://www.pythonforbeginners.com Learn By Example Thu, 15 Jun 2023 14:24:20 +0000 en-US hourly 1 https://wordpress.org/?v=5.8.13 https://www.pythonforbeginners.com/wp-content/uploads/2020/05/cropped-pfb_icon-32x32.png Code Category Page - PythonForBeginners.com https://www.pythonforbeginners.com 32 32 201782279 Comment out a block of code in Python https://www.pythonforbeginners.com/code/comment-out-a-block-of-code-in-python Sat, 20 Mar 2021 11:51:41 +0000 https://www.pythonforbeginners.com/?p=8501 There may be many situations while testing or debugging python programs where we want a certain statement in the code or a block of statements in the code to not to be executed. For this purpose we comment out the block of code . In this article, we will see how we can comment out […]

The post Comment out a block of code in Python appeared first on PythonForBeginners.com.

]]>
There may be many situations while testing or debugging python programs where we want a certain statement in the code or a block of statements in the code to not to be executed. For this purpose we comment out the block of code . In this article, we will see how we can comment out a block of code in python using python comment. First we will see what a block of code means in python and then we will see how to comment them out.

What is a block of code?

A block of code is a group of statements in source code in any programming language which are supposed to be executed once a condition is met or a function is called.

In python, blocks of code are created by applying proper  indentation for the statements to create a block of code and separate them from other blocks of code. 

A block of code in python may consist of statements belonging to a control statements, a function or a class.

For Example, following is a block of code in if-else control statement.

number =int(input())
#This an example of block of code where a block consists of control statement(If else in this case)
if (number%2==0):
    print("number is even")
else:
    print("number is odd")

A block of code inside a function may be as follows. The following function adds a number and its square to a python dictionary as key value pair.


def add_square_to_dict(x,mydict):
    #This is an example of block of code where the block consists of an entire function
    a=x*x
    mydict[str(x)]=a
    return mydict

A block of code inside a class may be as follows.


class number:
    #This is an example of block of code where the block consists of an entire class

    def __init__(self,value):
        self.value =value
    def increment(self):
        self.value=self.value+1

Generally, a block of code extends to multiple lines. So to comment out a block of code in python, we will have to use multiline comments. First we will see the working of multiline comments and then we will try to comment out a block of code .

Working of multiline comments in python

Multiline comments are not intrinsically included as a construct in python. But single line comments and multiline strings can be used to implement multi line comments in python.

We can implement multi line comments using single line comment by inserting a # sign whenever a line break is encountered. In this way, the multiline comments are just depicted as a sequence of single line comments as shown below.


def add_square(x,y):
    a=x*x
    b=y*y
    #This is a multi line comment
    #implemented using # sign
    return a+b

We can also use multiline strings as multi line comments if we do not assign them to any variable.When the string isn’t assigned to any variable, they are parsed and evaluated by the interpreter but no byte code is generated because no address can be assigned to the strings. This affects the string working just as a comment. In this method, multi line comments can be declared using triple quotes as shown below.

def add_square(x,y):
    a=x*x
    b=y*y
    """This is a multiline comment
    implemented with the help of 
    triple quoted strings"""
    return a+b

Comment out a block of code in python using # sign

We can comment out a block of code in python by placing a # sign at the start of each statement in that particular block of code as follows.

number =int(input())
#if (number%2==0):
 #   print("number is even")
#else:
#    print("number is odd")

Comment out blocks of code in python using multiline strings

We can comment out a block of code using multiline string method as follows.

number =int(input())
"""if (number%2==0):
   print("number is even")
else:
  print("number is odd")
"""

Although this method works but we should not use multiline strings as comments to comment out block of code. The reason is that multiline comments are used as docstrings for documenting the source code.

Conclusion

We can comment out a block of code in python using # symbol but we should refrain ourselves from using multiline strings to comment out the block of code. Stay tuned for more informative articles.

The post Comment out a block of code in Python appeared first on PythonForBeginners.com.

]]>
8501
Numeric Types in Python https://www.pythonforbeginners.com/basics/numeric-types-python Fri, 16 Oct 2015 07:37:46 +0000 https://www.pythonforbeginners.com/?p=6745 In any OOP language, there are many different data types. In Python, number data types are used to store numeric values. There are four different numerical types in Python: int (plain integers): this one is pretty standard — plain integers are just positive or negative whole numbers. long (long integers): long integers are integers of […]

The post Numeric Types in Python appeared first on PythonForBeginners.com.

]]>
In any OOP language, there are many different data types. In Python, number data types are used to store numeric values. There are four different numerical types in Python:
  1. int (plain integers): this one is pretty standard — plain integers are just positive or negative whole numbers.
  2. long (long integers): long integers are integers of infinite size. They look just like plain integers except they’re followed by the letter “L” (ex: 150L).
  3. float (floating point real values): floats represent real numbers, but are written with decimal points (or scientific notaion) to divide the whole number into fractional parts. 
  4. complex (complex numbers): represented by the formula a + bJ, where a and b are floats, and J is the square root of -1 (the result of which is an imaginary number). Complex numbers are used sparingly in Python. 
 
Applying the function call operator () to a numeric type creates an instance of that type. For example: calling int(x) will convert x to a plain integer. This can also be used with the long, float, and complex types. 

The post Numeric Types in Python appeared first on PythonForBeginners.com.

]]>
6745
Magic 8-ball Game Written in Python https://www.pythonforbeginners.com/code-snippets-source-code/magic-8-ball-written-in-python https://www.pythonforbeginners.com/code-snippets-source-code/magic-8-ball-written-in-python#comments Sun, 14 Apr 2013 03:46:38 +0000 https://www.pythonforbeginners.com/?p=5023 The Magic 8 Ball is a toy game for fortune-telling or seeking advice. In this article, we will implement the magic 8-ball game in Python. What is the Magic 8-Ball Game? A magic 8-ball is a hollow sphere made out of plastic and printed to look like the 8-ball from a billiards game. It is […]

The post Magic 8-ball Game Written in Python appeared first on PythonForBeginners.com.

]]>
The Magic 8 Ball is a toy game for fortune-telling or seeking advice. In this article, we will implement the magic 8-ball game in Python.

What is the Magic 8-Ball Game?

A magic 8-ball is a hollow sphere made out of plastic and printed to look like the 8-ball from a billiards game. It is filled with a dark blue or black liquid, usually alcohol, and contains a 20-sided die. Instead of numbers on the die, the sides are printed with a variety of yes, no, and maybe-type answers. A standard Magic 8 Ball has twenty possible answers, including ten affirmative answers, five non-committal answers, and five negative answers.

To play the magic 8-ball game, the player holds the ball and thinks of a yes or no question. They then shake the ball, which agitates a printed die floating in the dark blue liquid inside of the ball. When the shaking stops, the die settles to the bottom of the ball, revealing a yes, no, or vague answer. You can read more about this game on its wiki page.

The core functionality of the magic 8-ball game is to predict the outcome of a certain event from 20 possible outcomes in a random manner. To implement this functionality, we can use the random module in Python.

How to Implement Magic 8-ball Game in Python?

We can implement the magic 8-ball game in Python using the randint() function with if-else statements. Alternatively, we can also use the choice() function defined in the random module in Python to implement the magic 8-ball game. Let us discuss both approaches one by one.

Using The randint() Function

To implement the magic 8-ball game in Python using the randint() function, we will use the following steps.

  • First, we will ask the user to enter a question using the input() function.
  • Next, we will generate a random number between 1 to 20 using the randint() function. For this, we will pass the value 1 as its first input argument and the value 20 as its second input argument.
  • After generating the random number, we will select one of the possible answers using the if-else block and print it.
  • Until the user keeps entering questions, we will continue the game using a while loop. If the user doesn’t input any questions, we will terminate the loop using the break statement.

You can observe the above process in the following example.

import random
while True:
    question=input("Ask the magic 8 ball a question: (press enter to quit) ")
    answer=random.randint(1,20)
    if question=="":
        print("Stopping the Game.")
        break
    if answer==1:
        print("It is certain.")
    elif answer==2:
        print("It is decidedly so.")
    elif answer==3:
        print("Without a doubt.")
    elif answer==4:
        print("Yes definitely.")
    elif answer==5:
        print("You may rely on it.")
    elif answer==6:
        print("As I see it, yes.")
    elif answer==7:
        print("Most likely.")
    elif answer==8:
        print("Outlook good.")
    elif answer==9:
        print("Yes.")
    elif answer==10:
        print("Signs point to yes.")
    elif answer==11:
        print("Reply hazy, try again.")
    elif answer==12:
        print("Ask again later.")
    elif answer==13:
        print("Better not tell you now.")
    elif answer==14:
        print("Cannot predict now.")
    elif answer==15:
        print("Concentrate and ask again.")
    elif answer==16:
        print("Don't count on it.")
    elif answer==17:
        print("My reply is no.")
    elif answer==18:
        print("My sources say no.")
    elif answer==19:
        print("Outlook not so good.")
    elif answer==20:
        print("Very doubtful.")

Output:

Ask the magic 8 ball a question: (press enter to quit) Python is awesome
Yes.
Ask the magic 8 ball a question: (press enter to quit) PFB is great.
Yes definitely.
Ask the magic 8 ball a question: (press enter to quit) 
Stopping the Game.

In the above code, we have used 20 if-else blocks to implement the answers. You can observe that the if-else blocks made the code redundantly large. Hence, we can use a Python dictionary to imitate the functionality of the if-else blocks. For this, we will use the numbers as the keys and the answers for each number as the corresponding values.

After predicting a number using the randint() method, we can get the answer from the dictionary and print it as shown below.

import random
answer_dict={1:"It is certain.",
            2:"It is decidedly so.",
            3: "Without a doubt.",
            4:"Yes definitely.",
            5:"You may rely on it.",
            6:"As I see it, yes.",
            7:"Most likely.",
            8:"Outlook good.",
            9:"Yes.",
            10:"Signs point to yes.",
            11:"Reply hazy, try again.",
            12:"Ask again later.",
            13:"Better not tell you now.",
            14:"Cannot predict now.",
            15:"Concentrate and ask again.",
            16:"Don't count on it.",
            17:"My reply is no.",
            18:"My sources say no.",
            19:"Outlook not so good.",
            20:"Very doubtful."}
while True:
    question=input("Ask the magic 8 ball a question: (press enter to quit) ")
    answer=random.randint(1,20)
    if question=="":
        print("Stopping the Game.")
        break
    answer_string=answer_dict[answer]
    print(answer_string)

Output:

Ask the magic 8 ball a question: (press enter to quit) Python is awesome.
Yes definitely.
Ask the magic 8 ball a question: (press enter to quit) PFB is great.
Reply hazy, try again.
Stopping the Game.

In this example, we first generate a random number between 1 to 20 using the randint() function to predict the answer. As we have already defined the dictionary with numbers as keys and the possible answers as their values, we use the indexing operator to get the string value associated with the random number and print it.

Using The choice() Function

Instead of the randint() function, we can also use the choice() function defined in the random module to implement the magic 8-ball game. The choice() function takes a list as its input argument and returns a random element from the list. To implement the game, we will put all 20 answers in a list. After this, whenever the user asks a question, we will select a value from the list using the choice function and print it as shown in the following example.

import random
answer_list=['It is certain.', 
             'It is decidedly so.', 
             'Without a doubt.',
             'Yes definitely.', 
             'You may rely on it.', 
             'As I see it, yes.',
             'Most likely.',
             'Outlook good.', 
             'Yes.', 
             'Signs point to yes.',
             'Reply hazy, try again.', 
             'Ask again later.', 
             'Better not tell you now.',
             'Cannot predict now.', 
             'Concentrate and ask again.',
             "Don't count on it.", 
             'My reply is no.', 
             'My sources say no.', 
             'Outlook not so good.',
             'Very doubtful.']
while True:
    question=input("Ask the magic 8 ball a question: (press enter to quit) ")
    if question=="":
        print("Stopping the Game.")
        break
    answer_string=random.choice(answer_list)
    print(answer_string)

Output:

Ask the magic 8 ball a question: (press enter to quit) Python is awesome
You may rely on it.
Ask the magic 8 ball a question: (press enter to quit) PFB is great
You may rely on it.
Ask the magic 8 ball a question: (press enter to quit) PFB is awesome.
My reply is no.
Ask the magic 8 ball a question: (press enter to quit) PFB is good.
Yes definitely.
Ask the magic 8 ball a question: (press enter to quit) 
Stopping the Game.

In this example, we have stored all the possible answers in a list. When the user asks for an answer, we directly select a random answer from the list using the choice() function and print it.

Conclusion

In this article, we discussed three ways to implement the magic 8-ball game in Python. To learn more about Python programming, you can read this article on rolling the dice game in Python. You might also like this article on python trees.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

The post Magic 8-ball Game Written in Python appeared first on PythonForBeginners.com.

]]>
https://www.pythonforbeginners.com/code-snippets-source-code/magic-8-ball-written-in-python/feed 16 5023
Python Code : Convert KM/H to MPH https://www.pythonforbeginners.com/code-snippets-source-code/python-code-convert-kmh-to-mph Sun, 23 Sep 2012 11:26:05 +0000 https://www.pythonforbeginners.com/?p=667 Convert KM/H to MPH This script converts speed from KM/H to MPH, which may be handy for calculating speed limits when driving abroad, especially for UK and US drivers. The conversion formula for kph to mph is : 1 kilometre = 0.621371192 miles #!/usr/bin/env python kmh = int(raw_input("Enter km/h: ")) mph = 0.6214 * kmh […]

The post Python Code : Convert KM/H to MPH appeared first on PythonForBeginners.com.

]]>
Convert KM/H to MPH

This script converts speed from KM/H to MPH, which may be handy for calculating
speed limits when driving abroad, especially for UK and US drivers. 

The conversion formula for kph to mph is : 1 kilometre = 0.621371192 miles
#!/usr/bin/env python
kmh = int(raw_input("Enter km/h: "))
mph =  0.6214 * kmh
print "Speed:", kmh, "KM/H = ", mph, "MPH"

The post Python Code : Convert KM/H to MPH appeared first on PythonForBeginners.com.

]]>
667
Python Code : Get all the links from a website https://www.pythonforbeginners.com/code/regular-expression-re-findall https://www.pythonforbeginners.com/code/regular-expression-re-findall#comments Sat, 22 Sep 2012 12:17:13 +0000 https://www.pythonforbeginners.com/?p=591 Overview In this script, we are going to use the re module to get all links from any website. One of the most powerful function in the re module is "re.findall()". While re.search() is used to find the first match for a pattern, re.findall() finds *all* the matches and returns them as a list of […]

The post Python Code : Get all the links from a website appeared first on PythonForBeginners.com.

]]>
Overview

In this script, we are going to use the re module to get all links from any website. 

One of the most powerful function in the re module is "re.findall()".

While re.search() is used to find the first match for a pattern, re.findall() finds *all*
the matches and returns them as a list of strings, with each string representing one match.

Get all links from a website


This example will get all the links from any websites HTML code. 

To find all the links, we will in this example use the urllib2 module together
with the re.module
import urllib2
import re

#connect to a URL
website = urllib2.urlopen(url)

#read html code
html = website.read()

#use re.findall to get all the links
links = re.findall('"((http|ftp)s?://.*?)"', html)

print links

Happy scraping!

The post Python Code : Get all the links from a website appeared first on PythonForBeginners.com.

]]>
https://www.pythonforbeginners.com/code/regular-expression-re-findall/feed 1 591