Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python skips my if statement when I type 0 as the user input even though it should (I think) generate a random number

I’m trying to make a script that gives a random number of abilities if the user writes 0 but now it just completely ignores my if statement and just doesn’t print any abilities at all even though it works perfectly fine when you enter anything else

import random

def RandomizeAbilities():
    NumberOfAbilities = int(input("How many abilities do you want your character to have? (1-100, leave 0 for random) "))
    if NumberOfAbilities == "0":
        NumberOfAbilities == random.randint(0,101)
    GeneratedAbilities = 0
    while GeneratedAbilities < NumberOfAbilities:
        AbilitiesDictionary = open("Abilities.txt", "r")
        Abilities = AbilitiesDictionary.read()
        ListOfTiers = Abilities.split(",")
        RandomizedAbility = random.choice(ListOfTiers)
        print("Your character's Ability is: ", RandomizedAbility)
        GeneratedAbilities += 1

Abilites.txt:

Absolute Zero,Absorption,Abstract Existence

if you need the rest of the code it’s available at https://github.com/Paloftzer/TSWCharCreator

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are comparing an Integer to a String, both are fundamentally different data-types and therefore the if-statement returns False.

Try this:

import random

def RandomizeAbilities():
    NumberOfAbilities = int(input("How many abilities do you want your character to have? (1-100, leave 0 for random) "))
    if NumberOfAbilities == 0: # changed to int '0' instead of '"0"'
        NumberOfAbilities = random.randint(0,101)
    GeneratedAbilities = 0
    while GeneratedAbilities < NumberOfAbilities:
        AbilitiesDictionary = open("Abilities.txt", "r")
        Abilities = AbilitiesDictionary.read()
        ListOfTiers = Abilities.split(",")
        RandomizedAbility = random.choice(ListOfTiers)
        print("Your character's Ability is: ", RandomizedAbility)
        GeneratedAbilities += 1

To get a better grasp of the concept behind data-types, I would strongly recommend to read:

https://docs.python.org/3/library/stdtypes.html

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading