Why does this if statement not work in this case? [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
In this code I ask the user which way they want the text file ordered however, when run the if statement will not work and when run without the if statement it does work. Why will it not work?
way = int(input('Which way would you like the data to be sorted, Alphabetical[1], Ascending[2] Descending[3] or Average[4]'))
classno = str(input('Which class would you like to sort? Please state the entire class name no spaces please with .txt on the end'))
if way=='1':# WORKS with classno but not with if statement
f = open(classno, "r")# omit empty lines and lines containing only whitespace
lines = [line for line in f if line.strip()]
f.close()
lines.sort()# now write the output file
f = open(classno, 'w')
f.writelines(lines) # Write a sequence of strings to a file
f.close()
The other codes which i have not displayed have the same problems and all work without the if statement They all use an if statement no elif ect. if that is any use.

way is an integer, and you're checking for a string, which leads 1 == '1', and that's false.
What you should do is write -
if way == 1:
or remove the int() cast that you're doing on the input, and then you have:
way = input("Message...")
if way == '1':

Change way == '1' to way == 1 so you are checking an int against an int.

Related

Why do I have "if" expression expected error? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm very new to coding and I am learning python alone and this is my code :
from random import *
temp =Randint( 0,70 )
print(temp)
if : temp = 69
print("nice")
You made a few errors
randint is a function so it's first letter should be small case
The for loop syntax was wrong
And we use == for checking equality and = for assignment
You can try the following code below
from random import randint
temp = randint( 0,70 )
print(temp)
if temp == 69:
print("nice")
Your if statement isn't quite right. The colon needs to go at the end of the line, and in an if statement you need a double equals sign (==, which compares two elements) rather than a single equals sign (which assigns a variable). Additionally, you need to indent (put a tab before) lines that are part of a block. You can read more about Python if statements here. The fixed if statement should look like this:
if temp == 69:
print("nice")
Lastly, since Python names are case-sensitive, randint must be in all lowercase.
I hope this is helpful!
A quick thing to remember is that “==“ means two things are equal and “!=“ means if something is not equal.

python: csv.writer - commas between numbers in the output [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
i suspect that this is a simple answer, but i cannot figure out the answer. (I did give it due diligence)
i wrote a simple python program to identify prime numbers. the program is function, but i'm receiving strange results in the output. when i have it write a number with multiple digits, each number is comma separated; for example, 13 is added to the document as 1,3. I would like to have a comma after each full number (13,) and don't want commas within the number (1,3 or 1,301). eventually, i want to have each number on its own row (one of the issue that i ran into in my g1 program is that the row became too long around 50mill ;-)
Any thoughts?
#!/bin/python3
import time
import os
import csv
folderLocation = "c:/notNow/"
primeName = "primeNumbers.csv"
# notPrimeName = "noPrimeNumbers.csv"
primePath=folderLocation + primeName
# notPrimePath=folderLocation + notPrimeName
no=13
os.makedirs(folderLocation)
f = open(primePath, "w")
writer = csv.writer(f)
writer.writerow(str(no))
output: 1,3
writerow expects a sequence of items (e.g list). A string is just seen as a sequence of individual characters, try this instead:
writer.writerow([no])

I use re.sub in python3 and set count to 1,but it replaces all targets? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
This my code:
import os,re
textFile = open('D:\\hehe.txt')
textContent = textFile.read()
print(textContent)
adjRegex = re.compile(r'ADJECTIVE')
nounRegex = re.compile(r'NOUN')
verbRegex = re.compile(r'VERB')
for i in range(len(textContent)):
if(adjRegex.search(textContent) != None):
print('Enter a adjective')
textContent = adjRegex.sub(input(),textContent)
elif(nounRegex.search(textContent) != None):
print('Enter a noun')
textContent = nounRegex.sub(input(),textContent)
elif(verbRegex.search(textContent) != None):
print('Enter a verb')
textContent = verbRegex.sub(input(),textContent,count=0)
else:
break
print(textContent)
textFile.close()
If this is your real code (i. e. you aren't actually using any complex regular expressions, just string matching), you could use simple str.replace:
adjRegex = "ADJECTIVE"
textContent = textContent.replace(adjRegex, input(), 1)
Note that then all the regexes will be mere strings.
And instead of searching for regexes, you could try checking whether the substrings are present in textContent:
if adjRegex in textContent:
# replace it!
You are using re.sub the wrong way.
Why are you iterating over every character in your text? You can
just go line by line using readlines() then replace()
Put the prompt message inside input('Enter a noun') instead of
printing it
Assign input to a variable to increase readability

My script will not work, not sure if i am doing python right [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
For some odd reason, my code won't work in Visual Studio on my laptop. It gives me errors on my script. Am I doing it wrong?
The errors I got were:
Can't assign to errorexpression --line 2
Unexpected indent --line 2
Unexpected token '<dedent>' --line 6
print("welcome user")
varpassword = input("Please enter a password: ")
if varpassword = "thisisthepassword123":
print("Welcome")
else:
print("access denied")
As others have pointed out your conditional statement should use the == operator (to indicate that you are comparing the two values to see if they're equal) instead of = that assigns the value to the variable.
if varpassword = "thisisthepassword123":
I just want to add that you should avoid using a hard-coded password value especially in python since it's plain text (unless this is just sample code to illustrate)
Edit:
Use a hashing algorithm to hash your password instead and then hash the user input and compare that. So you'll put the password through something like SHA1 or so (if you want to use a hard-coded value like "thisisthepassword123" it will have a value of f61c1bbcf1f7d68106a18bd753d4fc3c4925793f. So using a library like hashlib(https://docs.python.org/2/library/hashlib.html) you can do this:
import hashlib
hashlib.sha1(userinput).hexdigest()
Also consider using salting, read this: https://crackstation.net/hashing-security.htm
Edit 2:
Also make sure that your indentation in your script matches the indentation of your code snippet
please add == to compare = is use to assign

Python help. If statement not working? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am trying to store a high-score in a txt doc and then read it to show it on screen. But when the score that the player got is higherreturning, I would like to change the high-score in the txt file.
I know approximately how to do this but the If statement in my code has a little problem:
It keeps saying False...
Here is the code:
score = 10
highscoreFile = open('Highscore.txt', 'r+')
HS = highscoreFile.read() #the HS is, let's say, 3
highscoreFile.close()
print 'Your score is', score
print 'The High-Score is', HS
if score > HS:
print 'newHS'
newHS = True
highscoreFile = open('Highscore.txt', 'w+')
highscoreFile.write('%s' %(score))
highscoreFile.close()
NOTE: if I put '<' instead for the If statement, it returns True... please explain.
You are comparing int with string.
The line
if score > HS:
should be ,
if score > int(HS):
read reads the entire file, by default. And that will be treated as a string in Python. Quoting from the documentation,
If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object.
So, you have to explicitly convert the string to a number, like this
HS = int(highscoreFile.read())

Categories