Yes I'm new to this and I'm having a very hard time learning. This has me very confused. I have tried for hours to create a loop where if the value of a variable is not what it should be, it will continue asking for raw_input until it is what it should be and the program moves to the next function, as well as display something like "Try again" It's probably simple but I can't figure it out. I'm talking about the code after first_action = raw_input(">> ")
def start():
print """You awaken in a strange lanscape, You are on a steep hillside
surrounded by trees, and you can see large mountains in the distance."""
print "....."
print "....."
print "You struggle to regain your senses, and you realize you don't know who you are, or how you got here."
print "You have the following items: %s" % i
print "It's dark, perhaps you should sleep until the sun rises."
print "What do you do?"
def cryptic_message(read):
print read, "A paper with a message written in a strange language."
def day_1():
print "_-_-_Dream_-_-_"
print "It is relativity. It is a concept you know as time."
print """This time, what is it? You ask "me" and I do not know. Ask yourself."""
print """It is illusion. Oh look, "time" to wake up!"""
print "....."
print "....."
print "You awaken, dazed and tired"
print "What do you do?"
def knife(cut, stab):
print "What do you want to do with the knife?"
knife = raw_input(">> ")
def photo(view):
print "A faded photo of a man on a park bench"
i = ['clothing','small knife','strange photo','cryptic message']
start()
first_action = raw_input(">> ")
first_action == False
while first_action is False:
if first_action == "sleep":
print "You lay on the grass for a hardly restful sleep."
first_action == True
day_1()
elif first_action == "do nothing":
print "Try again"
first_action == False
else: "Try again"
You want something like this:
inp = ''
desired = 'hello'
while inp != desired:
inp = raw_input('Enter a greeting: ')
This will continue to ask for input until inp is desired:
>>> inp = ''
>>> desired = 'hello'
>>> while inp != desired:
... inp = raw_input('Enter a greeting: ')
...
Enter a greeting: bye
Enter a greeting: no
Enter a greeting: what's up
Enter a greeting: hello
>>>
In your code:
first_action = raw_input(">> ")
while first_action != "False::
print "Try again"
first_action = raw_input(">> ")
print "You lay on the grass for a hardly restful sleep."
day_1()
Related
I'm new in python and facing an issue in getting the right output. I have a list of strings as :
list_string=[
'!DOC <p>The course starts next Sunday</t><div>',
"!DOC <p>class='default'<d>I don't wash the dishes</span></t>",
'When does the train usually leave'
]
All I want output as:
Output expected: [['The course starts next Sunday'], ["I don't wash the dishes"], 'When does the train usually leave']
What I've done is something:
import re
subtring='!DOC'
output=[]
for i in string:
if subtring in i:
text=re.findall("<p>(.*?)</t>",i, re.DOTALL)
output.append(text)
elif subtring in i:
text=re.findall("<d>(.*?)</span>",i, re.DOTALL)
output.append(text)
else:
output.append(i)
print (output)
[['The course starts next Sunday'], ["class='default'<d>I don't wash the dishes</span>"], 'When does the train usually leave']
Can anyone suggest the right way to do it?
It appears as though the second rule trumps the first so if there is a match on the second rule, use it otherwise try the first rule falling back to returning what you were given.
A solution that is close to what you have now might be:
import re
list_string =[
'!DOC <p>The course starts next Sunday</t><div>',
"!DOC <p>class='default'<d>I don't wash the dishes</span></t>",
'When does the train usually leave'
]
output=[]
for line in list_string:
retval = re.findall("<d>(.*?)</span>", line, re.DOTALL)
if retval:
output.append(retval[0])
continue
retval = re.findall("<p>(.*?)</t>", line, re.DOTALL)
if retval:
output.append(retval[0])
continue
output.append(line)
print (output)
Though if it was me, I would probably use a little function with a comprehension:
import re
def pick_out_text(text):
retval = re.findall("<d>(.*?)</span>", text, re.DOTALL)
if retval: return retval[0]
retval = re.findall("<p>(.*?)</t>", text, re.DOTALL)
if retval: return retval[0]
return text
list_string =[
'!DOC <p>The course starts next Sunday</t><div>',
"!DOC <p>class='default'<d>I don't wash the dishes</span></t>",
'When does the train usually leave'
]
output = [pick_out_text(line) for line in list_string]
print(output)
So i create a new class and i have a lot of objects in this class such as name, surname age etc.
But i am geting the same error everytime. And also i do not now how to list my arrays with using method.
Error: no implicit conversion of Array into String
def main
patients = []
puts "What do you want to do \nadd \nlist \nexit"
process = gets.chomp
if process == "add"
puts "Please enter patient's name"
patient1 = Patient_Covid_19.new()
patient1.Name = gets.chomp.to_s
patient1.Name << patients #error line
elsif process == "list"
#And i want to print the arrays(patients, ages, surnames etc.) in here but using a method.
elsif process == "exit"
puts "Have a nice day"
else
puts "Please enter add, list or exit"
main
end
end
main
Edit: It was small syntax mistake(error line). But i still need help for the list process.
You probably meant to do patients << patient1.Name.
You can loop over and print out attributes as follows:
patients.each do |patient|
puts "Name: #{patient.Name}, etc"
end
class Patient_Covid_19
attr_accessor :Ssn, :Name, :Surname, :Sex, :Age
end
def main
patients = []
puts "What do you want to do \nadd \nlist \nexit"
process = gets.chomp
if process == "add"
puts "Please enter patient's name"
patient1 = Patient_Covid_19.new()
patient1.Name = gets.chomp.to_s
patients << patient1.Name
main
elsif process == "list"
elsif process == "exit"
puts "Have a nice day"
else
puts "Please enter add, list or exit"
main
end
end
main
This is my code. When the user writes Add, he will enter the patient's information from the console and this information will be added to an array. When the user writes list, he/she will be able to see the information of the patients he has written before. I want to do the listing with a method.
The book Ruby Wizardry Chapter 4 includes the following sample program
we_wanna_ride = true
stops = ["East Bumpspark", "Endertromb Avenue", "New Mixico", "Mal Abochny"]
while we_wanna_ride
print "Where ya headin', friend?"
destination = gets.chomp
if stops.include? destination
puts "I know how to get to #{destination}! Here's the station list:"
stops.each do |stop|
puts stop
break if stop == destination
end
else
puts "Sorry, we don't stop at that station. Maybe another time!"
we_wanna_ride = false
end
end
It then goes on to pose a few additional challenges:
"What if a passenger is going the other way on the train (for instance, from Mal Abochny to East Bumpspark)? How could you update your program to work in both directions? Even trickier, what if the train route is a big circle (meaning if a passenger goes from East Bumpspark to Mal Abochny, the next stop after Mal Abochny should be East Bumpspark again)? How could you update your program to print out the right list of train stops if a passenger wants to go all the way around the circle?"
Does anybody have any ideas how to proceed here ? I'm a beginning programmer so any help would be greatly appreciated. Here's my progress so far. I figured I would get a departure from the user and then use to.i to get the input into an integer. I could then use the integer value to compare to the index position in the array. If the rider wants to go in the opposite direction I could use something like stops.each.reverse to print out the array items in reverse order.
we_wanna_ride = true
stops = ["East Bumpspark(1)", "Endertromb Avenue(2)", "New Mixico(3)", "Mal Abochny(4)"]
puts "#{stops}"
while we_wanna_ride
print "Select a destination number"
destination = gets.chomp.to_i
print "Select a departure number"
departure = gets.chomp.to_i
if departure <= destination
stops.each do |stop|
puts stop
break if stop == destination
end
else puts "Sorry"
we_wanna_ride = false
end
end
Here is how I solved this challenge. It works but is rather lengthy. More advanced ruby coders may be able to provide a shorter solution:
we_wanna_ride = true
stops = ["East Bumpspark", "Endertromb Avenue", "New Mixico", "Mal Abochny"]
while we_wanna_ride
print "Where do you wish to depart from?: "
depart = gets.chomp.split.map(&:capitalize).join(' ')
depart_index = stops.index(depart)
# puts depart_index
print "Where ya headin' friend?: "
destination = gets.chomp.split.map(&:capitalize).join(' ')
destination_index = stops.index(destination)
# puts destination_index
index_diff1 = depart_index - destination_index
index_diff2 = destination_index - depart_index
if stops.include? destination && depart
puts "\nI know how to get to #{destination}! Here's the station list:"
if destination_index > depart_index && index_diff2 < 3
stops[depart_index..-1].each do |stop|
puts stop
break if stop == destination
end
we_wanna_ride = false
elsif destination_index > depart_index && index_diff2 >= 3
dubstops = stops.concat(stops)
dubstops[0..depart_index+4].reverse_each do |stop|
puts stop
break if stop == destination
end
we_wanna_ride = false
elsif destination_index < depart_index && index_diff1 < 3
stops[0..depart_index].reverse_each do |stop|
puts stop
break if stop == destination
end
we_wanna_ride = false
elsif destination_index < depart_index && index_diff1 >= 3
dubstops = stops.concat(stops)
dubstops[depart_index..-1].each do |stop|
puts stop
break if stop == destination
end
we_wanna_ride = false
end
else
puts "Sorry, we don't service that station. Maybe another time!"
we_wanna_ride = false
end
end
I create an array from a text file which contains the english irregular verbs. I want the code to ask me the verbs in random order letting me proceed only if I respond correctly. I need to compare a string with an element of array. I wrote this:
a = []
File.open('documents/programmi_test/verbi.txt') do |f|
f.lines.each do |line|
a <<line.split.map(&:to_s)
end
end
puts ''
b = rand(3)
puts a[b][0]
puts 'infinitive'
infinitive = gets.chomp
if infinitive = a[b][1] #--> write like this, I receive alway "true"
puts 'simple past'
else
puts 'retry'
end
pastsimple = gets.chomp
if pastsimple == a[b][2] #--> write like this, I receive alway "false"
puts 'past participle'
else
puts 'retry'
end
pastpart = gets.chomp
if pastpart == a[b][3]
puts 'compliments'
else
puts 'oh, no'
end
can somebody help me?
if infinitive = a[b][1] is assigning to inifinitive the value of a[b][1], unlike pastsimple == a[b][2] that's a comparation between both values.
You could try replacing the = for ==.
a = []
File.open('documents/programmi_test/verbi.txt') do |file|
file.lines.each do |line|
a << line.split.map(&:to_s)
end
end
puts ''
b = rand(3)
puts a[b][0]
puts 'infinitive'
infinitive = gets.chomp
puts infinitive == a[b][1] ? 'simple past' : 'retry'
pastsimple = gets.chomp
puts pastsimple == a[b][2] ? 'past participle' : 'retry'
pastpart = gets.chomp
puts pastpart == a[b][3] ? 'compliments' : 'oh, no'
Heyho
I want to repeat a program after runnning a task. At the start of the program I ask some questions, than the code jumps into the task. If the task is done the questions sholud ask again..
Each Question reads some infos at the serial port. If i get the infos ten times ich will restart the programm.. but the window closes and i must start the file..
What can i do?
import serial
import struct
import datetime
print("\n")
print("This tool reads the internal Bus ")
print("-----------------------------------------------------------------------")
COM=input("Check your COM Port an fill in with single semicolon (like: 'COM13' ): ")
ser = serial.Serial(
port=COM,
baudrate=19200,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
print("\n")
print("Please choose an option: ")
print("Polling of measured values and the operating status (1)")
print("Reading Parameter memory (2)")
print("Reading Fault memory (3)")
print("EXIT (4)")
print("\n")
i=input("Reading: ")
while(i==1):
count=0
while (count<10):
print(file.name)
print(ser.isOpen())
print ("connected to: "+ ser.portstr)
data = "\xE1\x14\x75\x81"
ser.write(data)
a=(map(hex,map(ord,ser.read(46))))
with open("RS485_Reflex.txt",mode='a+') as file:
file.write(str(datetime.datetime.now()))
file.write(", Values: ,")
file.write(str(a))
file.write("\n")
print(a)
count=count+1
else:
i=0
loop=1
#-----------------------------------------------------------------------
while(i==2):
count=0
while (count<10):
print(file.name)
print(ser.isOpen())
print ("connected to: "+ ser.portstr)
data = "\xE1\x13\x00\x00\x74\x81"
ser.write(data)
a=(map(hex,map(ord,ser.read(11))))
with open("RS485_Reflex.txt",mode='a+') as file:
file.write(str(datetime.datetime.now()))
file.write(", Parameters: , ")
file.write(str(a))
file.write("\n")
print(a)
count=count+1
else:
i=0
#---------------------------------------------------------------------
while(i==3):
count=0
while (count<10):
print(file.name)
print(ser.isOpen())
print ("connected to: "+ ser.portstr)
data = "\xE1\x12\x00\x00\x73\x81"
ser.write(data)
a=(map(hex,map(ord,ser.read(11))))
with open("RS485_Reflex.txt",mode='a+') as file:
file.write(str(datetime.datetime.now()))
file.write(", Fault: , ")
file.write(str(a))
file.write("\n")
print(a)
count=count+1
else:
i=0
#----------------------------------------------------------------------
while(i==4):
file.close()
ser.close()
sys.exit(0)
file.close()
ser.close()
First, you should use If/Elif/Else statements instead of while loops.
while(i==1):
should be
if(i==1)0:
This is a simple program I wrote that you can follow:
# setup a simple run_Task method (prints number of times through the loop already)
def run_task(count):
print "Ran a certain 'task'", count,"times"
# count is a variable that will count the number of times we pass through a loop
count = 0
# loop through 10 times
while(count<10):
# ask questions
q1 = raw_input("What is your name?")
q2 = raw_input("What is your favorite color?")
# run a 'task'
run_task(count)