Very new to programming and I'm stuck. The code is not 100% finished but should still work. I'm having a problem with using an if statement that equals a variable with words. I just added the quotes and its hanging out that but before I added the quotes it said that if the case was selected then all the If statements were true and added 1 to each of them. Below is what I have. Also just a side question unrelated to this how do I add a variable result to the middle of a sentence? I have only been able to add them to the beginning or end.
(program starts)
WesternMarried=0
WesternSingle=0
WesternDivorced=0
WesternSeperated=0
EasternMarried=0
EasternSingle=0
EasternDivorced=0
EasternSeperated=0
SouthernMarried=0
SouthernSingle=0
SouthernDivorced=0
SouthernSeperated=0
MidwesternMarried=0
MidwesternSingle=0
MidwesternDivorced=0
MidwesternSeperated=0
Print "Which state is subject 1 from?"
Input State1
Print "What is the relationship status of Subject1?"
Input Relation1
Select Case State1
Case CA
Print "You are from the western region"
If (Relation1 = "Married") then
WesternMarried = WesternMarried + 1
End If
If (Relation1 = "Single") then
WesternSingle = WesternSingle + 1
End If
If (Relation1 = "Divorced") then
WesternDivorced = WesternDivorced + 1
End If
If (Relation1 = "Seperated") then
WesternSeperated = WesternSeperated + 1
End If
Case Else
Print "You might be from the midwestern states"
If (Relation1 = "Married") then
MidwesternMarried = MidwesternMarried + 1
End If
If (Relation1 = "Single") then
MidwesternSingle = MidwesternSingle + 1
End If
If (Relation1 = "Divorced") then
MidwesternDivorced = MidwesternDivorced + 1
End If
If (Relation1 = "Seperated") then
MidwesternSeperated = MidwesternSeperated + 1
End If
End Select
Print "The number of people married in the midwestern states is " ; MidwesternMarried
Print "The number of people single in the midwestern states is " ; MidwesternSingle
Print "The number of people divorced in the midwestern states is " ; MidwesternDivorced
Print "The number of people separated in the Western states is " ; MidwesternSeperated
Print "The number of people married in the Western states is " ; WesternMarried
Print "The number of people single in the Western states is " ; WesternSingle
Print "The number of people divorced in the Western states is " ; WesternDivorced
Print "The number of people separated in the Western states is " ; WesternSeperated
End
Perhaps this is a better way to do it. If you don't have quotations around your strings then it will think that it is a variable. Also, you need to have the $ after your variables, this signifies that it is a string.
WesternMarried=0
WesternSingle=0
WesternDivorced=0
WesternSeperated=0
EasternMarried=0
EasternSingle=0
EasternDivorced=0
EasternSeperated=0
SouthernMarried=0
SouthernSingle=0
SouthernDivorced=0
SouthernSeperated=0
MidwesternMarried=0
MidwesternSingle=0
MidwesternDivorced=0
MidwesternSeperated=0
Print "Which state is subject 1 from?"
Input State1$
Print "What is the relationship status of Subject1?"
Input Relation1$
Select Case State1
Case "CA"
Print "You are from the western region"
If (Relation1$ = "Married") then
WesternMarried = WesternMarried + 1
End If
If (Relation1$ = "Single") then
WesternSingle = WesternSingle + 1
End If
If (Relation1$ = "Divorced") then
WesternDivorced = WesternDivorced + 1
End If
If (Relation1$ = "Seperated") then
WesternSeperated = WesternSeperated + 1
End If
Case Else
Print "You might be from the midwestern states"
If (Relation1$ = "Married") then
MidwesternMarried = MidwesternMarried + 1
End If
If (Relation1$ = "Single") then
MidwesternSingle = MidwesternSingle + 1
End If
If (Relation1$ = "Divorced") then
MidwesternDivorced = MidwesternDivorced + 1
End If
If (Relation1$ = "Seperated") then
MidwesternSeperated = MidwesternSeperated + 1
End If
End Select
Print "The number of people married in the midwestern states is " ; MidwesternMarried
Print "The number of people single in the midwestern states is " ; MidwesternSingle
Print "The number of people divorced in the midwestern states is " ; MidwesternDivorced
Print "The number of people separated in the Western states is " ; MidwesternSeperated
Print "The number of people married in the Western states is " ; WesternMarried
Print "The number of people single in the Western states is " ; WesternSingle
Print "The number of people divorced in the Western states is " ; WesternDivorced
Print "The number of people separated in the Western states is " ; WesternSeperated
End
Update: When I saw "basic" in the title I assumed you meant VB. I have now learned BASIC is actually the language that VB is based off of... Sorry for the confusion.
Related
UserNumber = 0
UserNumber = int(raw_input("Enter a 3 digit number: "))
if UserNumber >= 100 and UserNumber <= 999:
print "My name is: xxxxx xxxxx"
print "My UBIT name is: xxxxxxx"
print "The number you entered was", UserNumber, "."
How can I make the program only run when a 3 digit number is entered (i.e a number > 99 and number < 1000? I know it has to be some sort of while loop but I don't know how to implement it.
You could use regex to check if the number is 3 digits and just ask the user again if it is not matching the regex
import re
UserNumber = int(raw_input("Enter a 3 digit number: "))
while not(re.search("^\d{3}$", str(UserNumber))):
UserNumber = int(raw_input("that was not a 3 digit number, Enter a 3 digit number: "))
if UserNumber >= 100 and UserNumber <= 999:
print "My name is: xxxxx xxxxx"
print "My UBIT name is: xxxxxxx"
print "The number you entered was", UserNumber, "."
The input is a string, therefore, you can len(input) before the cast to an integer.
The check that every character is a digit can be done with and input.isdigit.
UserNumber = 0
input = raw_input("Enter a 3 digit number: ")
if len(input) == 3 and input.isdigit():
UserNumber = int(input)
print "My name is: xxxxx xxxxx"
print "My UBIT name is: xxxxxxx"
print "The number you entered was", UserNumber, "."
But think, 007 is also a valid 3 digit number. So if you want that it is bigger than 99, you need that check too.
To your "update", that you want a "fail-save" such that somebody is forced to do a 3 digits input:
UserNumber = 0
input = ""
while not (len(input) == 3 and input.isdigit()):
input = raw_input("Enter a 3 digit number: ")
UserNumber = int(input)
print "My name is: xxxxx xxxxx"
print "My UBIT name is: xxxxxxx"
print "The number you entered was %03d." % UserNumber
As long as somebody does not input 3 digits, the question for that input will appear.
I am trying to create a simple "guess the word" game in Python. My output is something like:
String: _____ _____
Guess a word: 'e'
String:_e__o __e_e
Guess a word: 'h'
(and so on)
String: hello there
I have a function to do this, and within this function I have this code:
def guessing(word):
count = 0
blanks = "_" * len(word)
letters_used = "" #empty string
while count<len(word):
guess = raw_input("Guess a letter:")
blanks = list(blanks)
#Checks if guesses are valid
if len(guess) != 1:
print "Please guess only one letter at a time."
elif guess not in ("abcdefghijklmnopqrstuvwxyz "):
print "Please only guess letters!"
#Checks if guess is found in word
if guess in word and guess not in letters_used:
x = word.index(guess)
for x in blanks:
blanks[x] = guess
letters_used += guess
print ("".join(blanks))
print "Number of misses remaining:", len(word)-counter
print "There are", str(word.count(guess)) + str(guess)
guess is the raw input I get from the user for a guess, and letters_used is just a collection of guesses that the user has already input. What I'm trying to do is loop through blanks based on the word.index(guess). Unfortunately, this returns:
Guess a letter: e
e___
Yes, there are 1e
Help would be much appreciated!
Your code was almost correct. There were few mistakes which I have corrected:
def find_all(needle, haystack):
"""
Finds all occurances of the string `needle` in the string `haystack`
To be invoked like this - `list(find_all('l', 'hello'))` => #[2, 3]
"""
start = 0
while True:
start = haystack.find(needle, start)
if start == -1: return
yield start
start += 1
def guessing(word):
letters_uncovered_count = 0
blanks = "_" * len(word)
blanks = list(blanks)
letters_used = ""
while letters_uncovered_count < len(word):
guess = raw_input("Guess a letter:")
#Checks if guesses are valid
if len(guess) != 1:
print "Please guess only one letter at a time."
elif guess not in ("abcdefghijklmnopqrstuvwxyz"):
print "Please only guess letters!"
if guess in letters_used:
print("This character has already been guessed correctly before!")
continue
#Checks if guess is found in word
if guess in word:
guess_positions = list(find_all(guess, word))
for guess_position in guess_positions:
blanks[x] = guess
letters_uncovered_count += 1
letters_used += guess
print ("".join(blanks))
print "Number of misses remaining:", len(word)-letters_uncovered_count
print "There are", str(word.count(guess)) + str(guess)
else:
print("Wrong guess! Try again!")
me: I am very new to coding.
What i'm trying to do: Allow the user to change a txt files data. E.g. The name of a person, the email of a person, etc.
Problem: Code accepts my inputs however, it does not change the txt file.
Code i've made already.
click here for code
L = open("players.txt","r+")
edit_name = raw_input ("Enter the name of the person you wish to edit: ")
for line in L:
s = line.strip()
strings = s.split(",")
if edit_name == strings[0]:
print strings[:8]
print " \t 1 - Forename \n"
print " \t 2 - Surname \n"
print " \t 3 - Email Address \n"
print " \t 4 - Phone Number \n"
print " \t 5 - Division \n"
print " \t 6 - Points in the new division\n"
print " \t 7 - Old division\n"
print " \t 8 - Old points\n"
option = raw_input("Enter the number of what you would like to edit: ")
if option == "1":
updated_forename = raw_input ("New forename: ")
strings[0] = updated_forename
elif option == "2":
updated_surname = raw_input ("New surname: ")
strings[1] = updated_surname
elif option == "3":
updated_email = raw_input("New email: ")
strings[2] = updated_email
elif option == "4":
updated_phone_number = raw_input("New phonenumber: ")
strings[3] = updated_phone_number
elif option == "5":
updated_division = raw_input("New division: ")
strings[4] = updated_division
elif option == "6":
updated_points_new_div = raw_input("New points in division: ")
strings[5] = updated_points_new_div
elif option == "7":
updated_olddivision = raw_input("Old divison: ")
strings[6] = updated_olddivision
elif option == "8":
updated_oldpoints = raw_input("Old Points: ")
strings[7] = updated_oldpoints
print "Updated information"
print strings[:8]
L.close() #Closes the file to free us usage space.
Text file i'm wanting to edit.
click here for text file
Im guessing I need to basically save over the existing text file with the new data that has been entered. The question is how?
Any help would be appreciated.
p.s. First time posting so i cannot post pictures as i don't have 10 reputation. My apologies.
You are never actully writing to the file:
https://docs.python.org/2/tutorial/inputoutput.html
Change "L.open" to write mode "w", use "L.write()" to write new data, this means you need to rewrite the data you don't want to change and construct and write new data where you wanted it to be modified.
Pseudo-code:
Open file
for line in file
if(line.name == selectedname):
write_row_edited(something)
else:
write_line_unedited()
close file
I took the time to insert the missing peudo-code
#we need to load file into memory, so we can edit it (rewrite it modified)
file = open("players.txt","r")
data = file.read()
file.close()
datalines = data.split("\n")
#now we have the file "line-by-line" in memory so we can edit it
edit_name = raw_input ("Enter the name of the person you wish to edit: ")
file = open("players.txt","w")
for line in datalines:
s = line.strip()
strings = s.split(",")
if edit_name == strings[0]:
print strings[:8]
print " \t 1 - Forename \n"
print " \t 2 - Surname \n"
print " \t 3 - Email Address \n"
print " \t 4 - Phone Number \n"
print " \t 5 - Division \n"
print " \t 6 - Points in the new division\n"
print " \t 7 - Old division\n"
print " \t 8 - Old points\n"
option = raw_input("Enter the number of what you would like to edit: ")
if option == "1":
updated_forename = raw_input ("New forename: ")
strings[0] = updated_forename
elif option == "2":
updated_surname = raw_input ("New surname: ")
strings[1] = updated_surname
elif option == "3":
updated_email = raw_input("New email: ")
strings[2] = updated_email
elif option == "4":
updated_phone_number = raw_input("New phonenumber: ")
strings[3] = updated_phone_number
elif option == "5":
updated_division = raw_input("New division: ")
strings[4] = updated_division
elif option == "6":
updated_points_new_div = raw_input("New points in division: ")
strings[5] = updated_points_new_div
elif option == "7":
updated_olddivision = raw_input("Old divison: ")
strings[6] = updated_olddivision
elif option == "8":
updated_oldpoints = raw_input("Old Points: ")
strings[7] = updated_oldpoints
print "Updated information"
print strings[:8]
#merge string so we can write it back
newline = ",".join(strings)
file.write(newline+"\n")
else:
file.write(line+"\n")
file.close()
I am working on a script that sorts people's names. I had this working using the csv module, but as this is going to be tied to a larger pandas project, I thought I would convert it.
I need to split a single name field into fields for first, middle and last. The original field has the first name first. ex: Richard Wayne Van Dyke.
I split the names but want "Van Dyke" to be the last name.
Here is my code for the csv module that works:
with open('inputfil.csv') as inf:
docs = csv.reader(inf)
next(ccaddocs, None)
for i in docs:
#print i
fullname = i[1]#it's the second column in the input file
namelist =fullname.split(' ')
firstname = namelist[0]
middlename = namelist[1]
if len(namelist) == 2:
lastname = namelist[1]
middlename = ''
elif len(namelist) == 3:
lastname = namelist[2]
elif len(namelist) == 4:
lastname = namelist[2] + " " + namelist[3] #gets Van Dyke in lastname
print "First: " + firstname + " middle: " + middlename + " last: " + lastname
Here is my pandas-based code that I'm struggling with:
df = pd.DataFrame({'Name':['Richard Wayne Van Dyke','Gary Del Barco','Dave Allen Smith']})
df = df.fillna('')
df =df.astype(unicode)
splits = df['Name'].str.split(' ', expand=True)
df['firstName'] = splits[0]
if splits[2].notnull and splits[3].isnull:#this works for Bret Allen Cardwell
df['lastName'] = splits[2]
df['middleName'] = splits[1]
print "Case 1: First: " + df['firstName'] + " middle: " +df['middleName'] + " last: " + df['lastName']
elif splits[2].all() == 'Del':#trying to get last name of "Del Barco"
print 'del'
df['middleName'] = ''
df['lastName'] = splits[2] + " " + splits[3]
print "Case 2: First: " + df['firstName'] + " middle: " +df['middleName'] + " last: " + df['lastName']
elif splits[3].notnull: #trying to get last name of "Van Dyke"
df['middleName'] = splits[1]
df['lastName'] = splits[2] + " " + splits[3]
print "Case 3: First: " + df['firstName'] + " middle: " +df['middleName'] + " last: " + df['lastName']
There is something basic that I'm missing.
if len(name) >= 3: # (assume that user only has one middle name)
firstname = splits[0]
middlename = splits[1]
lastnames = splits[2:] ( catch all last names into a list )
Ok so the issue with my program is that for some reason when I run it the variables at the bottom come out as "None" instead of the count of the amount of ATG's in the original strings of HumanDNA, MouseDNA, and UnknownDNA. I couldn't add the part where i define these DNA's because of their length and was difficult for me to add it. How can I change it so instead it outputs the amount of times the substring is found in the original string as a variable that is outside the function and can output it in the format I have at the bottom.
def countCodon(string, substring):
i = string.find(substring)
def compareDNA(string1, string2):
string1 = raw_input("Enter string 1: ")
string2 = raw_input("Enter string 2: ")
Hamming = 0
for ch1, ch2 in zip(string1, string2):
if ch1 != ch2:
Hamming += 1
l = len(string1)
similarity_score = ((l - Hamming)/(l))
print similarity_score
HD = countCodon(humanDNA, "ATG")
MD = countCodon(mouseDNA, "ATG")
UD = countCodon(unknownDNA, "ATG")
print "Mouse: ", HD
print "Human: ", MD
print "Unknown: ", UD
MU = compareDNA(mouseDNA, unknownDNA)
HU = compareDNA(humanDNA, unknownDNA)
if MU != HU and MU > HU:
print "mouse"
elif MU != HU and MU < HU:
print "human"
elif MU == HU:
print "identity cannot be determined"
EDIT: Added the messed up part of the second function running into a similar problem.
countCodon() has no return value so HD = None
Moreover from https://docs.python.org/2/library/string.html
string.find(s, sub[, start[, end]])
Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Return -1 on failure. Defaults for start and end and interpretation of negative values is the same as for slices.
So countCodon() is giving you the index where the string "ATG" first appears, not the number of times it is present.