Why does my IF statement not work on python? - python

import random
circlediameter = random.randint(1,99)
pi = 3.142
print("The circle diameter is",circlediameter," Find the area")
#find 4 possible answers
circleanswer1 = circlediameter/pi
circleanswer2 = circlediameter*pi
circleanswer3 = circlediameter+pi
circleanswer4 = circlediameter
#makes sure all numbers are integers
circleanswer1 = int(circleanswer1)
circleanswer2 = int(circleanswer2)
circleanswer3 = int(circleanswer3)
circleanswer4 = int(circleanswer4)
answerlist = [circleanswer1 , circleanswer2 , circleanswer3 , circleanswer4]
#shuffles the list
random.shuffle(answerlist)
#answer 2 is always the right answer
print("Four options are: ", answerlist)
#user enters a number
useranswercircle = input("Please choose an answer: ")
int(useranswercircle)
str(useranswercircle)
str(circleanswer2)
if useranswercircle == circleanswer2:
print("EEE")
I am comparing two integers, why is my IF statement not working when i
compare two numbers. I have converted the two variables into integers, and it still isn't comparing successfully

Try with this cast:
import random
circlediameter = random.randint(1,99)
pi = 3.142
print("The circle diameter is",circlediameter," Find the area")
#find 4 possible answers
circleanswer1 = circlediameter/pi
circleanswer2 = circlediameter*pi
circleanswer3 = circlediameter+pi
circleanswer4 = circlediameter
#makes sure all numbers are integers
circleanswer1 = int(circleanswer1)
circleanswer2 = int(circleanswer2)
circleanswer3 = int(circleanswer3)
circleanswer4 = int(circleanswer4)
answerlist = [circleanswer1 , circleanswer2 , circleanswer3 , circleanswer4]
#shuffles the list
random.shuffle(answerlist)
#answer 2 is always the right answer
print("Four options are: ", answerlist)
#user enters a number
useranswercircle = input("Please choose an answer: ")
# EDIT:
# HERE IS THE TRICK
useranswercircle = int(useranswercircle)
if useranswercircle == circleanswer2:
print("EEE")

You need to indent the print:
if useranswercircle == circleanswer2:
print("EEE")

Try like this -
if str(useranswercircle) == str(circleanswer2):
print("EEE")
And remove these two statements -
str(useranswercircle)
str(circleanswer2)

Related

a list will not join the scond time but will the first time

i wanted to turn a list into a string for an auto password generator
this is the code:
import random
import string
print("hello welcome to the random password generator! ")
level_of_password = input("what level do you want your password to be?(weak, medium, strong): ")
list_of_words_for_password = ["obama", "apples", "mom", "your", "cyber"]
if level_of_password == "weak":
weak_password = list(random.sample(list_of_words_for_password, 2))
weak_password = "".join(weak_password)
print(weak_password)
elif level_of_password == "medium":
letters_for_password = list(string.ascii_letters)
numbers_for_password = []
for i in range(random.randint(10, 30)):
numbers_for_password.append(random.randint(5, 10))
letters_and_numbers_for_password = numbers_for_password + letters_for_password
medium_password = [random.sample(letters_and_numbers_for_password, random.randint(5, 20))]
medium_password = "".join(medium_password)
for the weak password it converts the list into a string just fine
but for the medium password, if I try to print it it gives me this error:
line 27, in <module>
medium_password = "".join(medium_password)
TypeError: sequence item 0: expected str instance, list found
why can I join the list of charecters for my medium password like I did for the weak one.
also, im learning python by myself, if you see something in the code that is unbearable to you, please let me know that also.
Find comments inline
import random
import string
print("hello welcome to the random password generator! ")
level_of_password = input("what level do you want your password to be?(weak, medium, strong): ")
list_of_words_for_password = ["obama", "apples", "mom", "your", "cyber"]
if level_of_password == "weak":
weak_password = list(random.sample(list_of_words_for_password, 2))
weak_password = "".join(weak_password)
print(weak_password)
elif level_of_password == "medium":
letters_for_password = list(string.ascii_letters)
numbers_for_password = []
for i in range(random.randint(10, 30)):
numbers_for_password.append(random.randint(5, 10))
letters_and_numbers_for_password = numbers_for_password + letters_for_password
#------>
medium_password = random.sample(letters_and_numbers_for_password, random.randint(5, 20)) # remove extra []
# ^^^^ ^^^^
medium_password = "".join(map(str, medium_password)) # convert intergers to string
# ^^^^^^^^^^^^^^^^^^^^^^^^^
print(medium_password)

Python Password Generatr with read and random module

im kinda new to python and am programming a password generator. As of now, i think i am at a plateau where i need explanation.
At the end, where i want to generate a password with the user input given above, i get a type error
(TypeError: choice() takes 2 positional arguments but 3 were given)
What am I missing, so that the random.choice function is not working
import random
Uppercaseletters = open("Upper.txt").read()
Lowercaseletters = open("Lower.txt").read()
Numbers = open("Zahlen.txt").read()
Symbols = open("Symbole.txt").read()
Upperbool = True
Lowerbool = True
Numbersbool = True
Symbolsbool = True
whole = ""
if Upperbool:
whole += Uppercaseletters
if Lowerbool:
whole += Lowercaseletters
if Numbersbool:
whole += Numbers
if Symbolsbool:
whole += Symbols
print("Hello and welcome to the simple password generator.")
a = 1
b = 1
if b <= 10:
amount = int(input("How many passwords do you want to generate? "))
else:
print("You are exceeding the limit of a maximum of 10 Passwords")
# length auswählen lassen (maximal 20 Zeichen lang (Fehler prevention))
if a <= 20:
length = int(input("How long do you want your password to be? "))
else:
print("That password will be too long, try a number below 20")
for x in range(amount):
password = "".join(random.choice(whole, length))
print(password)
I believe you are looking for something like this:
import random
Uppercaseletters = open("Upper.txt").read()
Lowercaseletters = open("Lower.txt").read()
Numbers = open("Zahlen.txt").read()
Symbols = open("Symbole.txt").read()
Upperbool = True
Lowerbool = True
Numbersbool = True
Symbolsbool = True
whole = ""
if Upperbool:
whole += Uppercaseletters
if Lowerbool:
whole += Lowercaseletters
if Numbersbool:
whole += Numbers
if Symbolsbool:
whole += Symbols
print("Hello and welcome to the BMD's simple password generator.")
amount = 100
length = 100
while amount>10:
amount = int(input("How many passwords do you want to generate? "))
if amount>10:
print("You are exceeding the limit of a maximum of 10 Passwords")
while length>20:
length = int(input("How long do you want your password to be? "))
if length>20:
print("That password will be too long, try a number below 20")
for passwords in range(amount):
password = ""
for character in range(length):
password = password + random.choice(list(whole))
print(password)
I modified it so that it does not allow amounts above 10 and lengths above 20.

openpyxl first column is empty when using append method

I'm new to Python, and i'm programming a simple math question program. The user is prompted a math question, and the user have to type the correct answer. All of the questions, solutions and answers are saved to a local excel ark. That is the summary of my project, now comes the problem:
When i append resultsArr the question column is blank in the excel ark. When i print resultArr i get an array back with the question as the first index in the array.
So i get an array back with all of the values, but for some reason it doesn't accept the first index. I have tried to manually write a string in its place, and that works.
main.py - current version
from colors import colors
from mathQuestion import mathQuestion
from openpyxl import Workbook
gameResults = []
score = 0
def saveData(rows):
wb = Workbook()
ws = wb.active
ws.append(["Question", "Answer", "Solution"])
[ws.append(x) for x in rows]
wb.save("data.xlsx")
wb.close()
while True:
result = mathQuestion()
gameResults.append(
[result["question"], result["answer"], result["solution"]])
if(result["answer"] == result["solution"]):
score += 1
print(f"{colors.green}Correct{colors.default}, your current score: {colors.yellow+str(score)+colors.default}")
else:
print(colors.red+"Game Over"+colors.default)
break
saveData(gameResults)
mathQuestion.py
from random import randint
from colors import colors
def oddOrEven():
number = randint(1, 1000)
numberIsOdd = number % 2 != 0
question = f"Is {number} odd or even: "
if(numberIsOdd):
solution = "odd"
else:
solution = "even"
while True:
userInput = input(question)
if(userInput == "odd" or userInput == "even"):
return {
"answer": userInput,
"question": question,
"solution": solution
}
else:
print("Only odd or even")
def muliply():
a = randint(0, 10)
b = randint(0, 10)
question = f"What is {a} * {b}: "
solution = a*b
while True:
userInput = input(question)
try:
return {
"answer": int(userInput),
"question": question,
"solution": solution
}
except:
print("Only numbers are allowed")
mathFunctions = [
oddOrEven,
muliply
]
def mathQuestion():
return mathFunctions[randint(0, len(mathFunctions)-1)]()
Github repo

How can I modify this code so it doesn't go back to the beginning of the function, but a little bit after the beginning?

I'm working on a school project and I have a problem. I have to write code for apothecary where clients can buy medicine. So, I need to make restrictions, which one doesn't go with others and etc. Here is the code:
def prodajLek():
lekovi = Fajl1.UcitavanjeLekova()
lekoviRed = []
brojacZaForPetlju = 1
n = 0
cena = 0
kolicina = []
korpa = []
rednibrojevilekova = []
ukupnacena = 0
print(" Fabricki naziv Genericki naziv Serijski broj Kolicina Cena \n")
for i in lekovi:
x = i.strip().split("|")
lekoviRed.append(x)
if lekoviRed[n][5] == "False":
print(brojacZaForPetlju,"\t {:10} \t {:10} \t\t\t {:3} \t\t\t {:4} \t\t {:5}".format(x[0],x[1],x[2],x[3],x[4]))
brojacZaForPetlju = brojacZaForPetlju + 1
n = n + 1
print("\n\n\n\n")
rednibrleka = input("Izaberite redni broj leka koji zelite da prodate:\n>>\t")
rednibrleka = int(rednibrleka)
rednibrleka = rednibrleka - 1
rednibrojevilekova.append(rednibrleka)
kolicinaZahteva = input("Koju kolicinu zelite da prodate?\n>>\t")
kolicinaZahteva = int(kolicinaZahteva)
if kolicinaZahteva > int(lekoviRed[rednibrleka][3]):
print("Nema toliko na lageru!\n")
Fajl1.LekarMenu()
kolicina.append(kolicinaZahteva)
cena = int(lekoviRed[rednibrleka][4])
korpa.append(cena)
print("Da li zelite da kupite jos lekova?\n1.Da\n2.Ne\n")
nastavakKupovine = input(">>")
if nastavakKupovine == "1":
prodajLek()
elif nastavakKupovine == "2":
Fajl1.LekarMenu()
So, when I get to the nastavakKupovine input, when I press 1, I need to continue shopping and store my row numbers, my price and quantity in arrays rednibrojlekova = [] , korpa = [] and kolicina = []. But I have a problem, because I dont know how to continue this without reseting these arrays to empty.
The standard idiom for what you want to do is a while True loop. Rather than show how to change your (rather long) function, here's a very simple one which hopefully shows the principle in a straightforward way:
def ask():
answers = []
while True:
response = input("What do you have to say? ")
answers.append(response)
check = input("Type 'q' to quit, anything else to repeat: ")
if check == "q":
break
else:
continue
return answers
For this simple function, the else: continue part isn't necessary, because the loop will continue anyway, but I've included it so you can see how to use it.
Here's an example of the function in action:
>>> ask()
What do you have to say? Something
Type 'q' to quit, anything else to repeat:
What do you have to say? Another thing
Type 'q' to quit, anything else to repeat:
What do you have to say? Ok, done
Type 'q' to quit, anything else to repeat: q
['Something', 'Another thing', 'Ok, done']
>>>
You can find out more about while, break and continue by reading the More Control Flow Tools chapter of the official Python tutorial.

Digit 1 is not defined? (ISBN Calculator - Python)

mainmenu = input("Welcome to my ISBN calculator, please select an option\n\
1. Load ISBN Calculator\n\
2. Exit Program\n\
")
(mainmenu)
if mainmenu == ("2"):
print ("The ISBN Calculator will now close, thank you for using!")
time.sleep(1.5)
exit()
elif mainmenu == ("1"):
ISBN = input(" Please enter the 10 digit number exactly\n\
")
Digit1 = int(ISBN[0])*11
Digit2 = int(ISBN[1])*10
Digit3 = int(ISBN[2])*9
Digit4 = int(ISBN[3])*8
Digit5 = int(ISBN[4])*7
Digit6 = int(ISBN[5])*6
Digit7 = int(ISBN[6])*5
Digit8 = int(ISBN[7])*4
Digit9 = int(ISBN[8])*3
Digit10 = int(ISBN[9])*2
sum=(Digit1+Digit2+Digit3+Digit4+Digit5+Digit6+Digit7+Digit8+Digit9+Digit10)
num=sum%11
Digit11=11-num
if Digit11==10:
Digit11='X'
ISBNNumber=str(ISBN)+str(Digit11)
print('The ISBN number is --> ' + ISBNNumber)
This is my code and it always comes up with the error of Digit 1 is not defined whenever I try enter my 10 digit number, any help?
Why the line:
(mainmenu)
?
In your if statements remove the ():
if mainmenu == "1":
...
elif mainmenu == "2":
...
else:
print("Invalid menu option")
exit()
It will be work. Indent is important.
mainmenu = input("Welcome to my ISBN calculator, please select an option\n\
1. Load ISBN Calculator\n\
2. Exit Program\n\
")
if mainmenu == "2":
print ("The ISBN Calculator will now close, thank you for using!")
time.sleep(1.5)
exit()
elif mainmenu == "1":
ISBN = input(" Please enter the 10 digit number exactly\n")
Digit1 = int(ISBN[0])*11
Digit2 = int(ISBN[1])*10
Digit3 = int(ISBN[2])*9
Digit4 = int(ISBN[3])*8
Digit5 = int(ISBN[4])*7
Digit6 = int(ISBN[5])*6
Digit7 = int(ISBN[6])*5
Digit8 = int(ISBN[7])*4
Digit9 = int(ISBN[8])*3
Digit10 = int(ISBN[9])*2
sum=(Digit1+Digit2+Digit3+Digit4+Digit5+Digit6+Digit7+Digit8+Digit9+Digit10)
num=sum%11
Digit11=11-num
if Digit11==10:
Digit11='X'
ISBNNumber=str(ISBN)+str(Digit11)
print('The ISBN number is --> ' + ISBNNumber)
Note. This code is just work code, not a good implementation.
The problem occurs when you execute that code with Python 2. Use Python 3 instead.
In Python 2, input evaluates the input you provide, so if you enter 1, then mainmenu is 1 (the number) and not "1" (the string), thus both of your if-checks fail and your code arrives at the sum=... part without any ISBN number being inputted.
As commented above, your "ISBN" is quite different from the standard, which has either 10 or 13 digits including check digit.
A clean implementation for ISBN-10 calculation would be:
from string import digits
checkTemplate = digits + "X"
def isbn(isbnBody):
"""append check digit to a isbn given as string without check digit"""
assert len(isbnBody) == 9
s = sum([int(isbnChar)*multiplier for isbnChar, multiplier in zip(isbnBody, range(1,10))])
checkDigit = checkTemplate[s % 11]
return isbnBody + checkDigit

Categories